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 struct dentry *proc_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { int err; struct super_block *sb; struct pid_namespace *ns; char *options; if (flags & MS_KERNMOUNT) { ns = (struct pid_namespace *)data; options = NULL; } else { ns = task_active_pid_ns(current); options = data; /* Does the mounter have privilege over the pid namespace? */ if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) return ERR_PTR(-EPERM); } sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns); if (IS_ERR(sb)) return ERR_CAST(sb); if (!proc_parse_options(options, ns)) { deactivate_locked_super(sb); return ERR_PTR(-EINVAL); } if (!sb->s_root) { err = proc_fill_super(sb); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; /* User space would break if executables appear on proc */ sb->s_iflags |= SB_I_NOEXEC; } return dget(sb->s_root); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <[email protected]>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
static struct dentry *proc_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { int err; struct super_block *sb; struct pid_namespace *ns; char *options; if (flags & MS_KERNMOUNT) { ns = (struct pid_namespace *)data; options = NULL; } else { ns = task_active_pid_ns(current); options = data; /* Does the mounter have privilege over the pid namespace? */ if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) return ERR_PTR(-EPERM); } sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns); if (IS_ERR(sb)) return ERR_CAST(sb); /* * procfs isn't actually a stacking filesystem; however, there is * too much magic going on inside it to permit stacking things on * top of it */ sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH; if (!proc_parse_options(options, ns)) { deactivate_locked_super(sb); return ERR_PTR(-EINVAL); } if (!sb->s_root) { err = proc_fill_super(sb); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; /* User space would break if executables appear on proc */ sb->s_iflags |= SB_I_NOEXEC; } return dget(sb->s_root); }
167,444
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 *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) { typedef struct _TIMInfo { size_t id, flag; } TIMInfo; TIMInfo tim_info; Image *image; int bits_per_pixel, has_clut; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, height, image_size, pixel_mode, width; ssize_t count, y; unsigned char *tim_data, *tim_pixels; unsigned short word; /* 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); } /* Determine if this a TIM file. */ tim_info.id=ReadBlobLSBLong(image); do { /* Verify TIM identifier. */ if (tim_info.id != 0x00000010) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tim_info.flag=ReadBlobLSBLong(image); has_clut=tim_info.flag & (1 << 3) ? 1 : 0; pixel_mode=tim_info.flag & 0x07; switch ((int) pixel_mode) { case 0: bits_per_pixel=4; break; case 1: bits_per_pixel=8; break; case 2: bits_per_pixel=16; break; case 3: bits_per_pixel=24; break; default: bits_per_pixel=4; break; } image->depth=8; if (has_clut) { unsigned char *tim_colormap; /* Read TIM raster colormap. */ (void)ReadBlobLSBLong(image); (void)ReadBlobLSBShort(image); (void)ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image->columns=width; image->rows=height; if (AcquireImageColormap(image,pixel_mode == 1 ? 256UL : 16UL) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); tim_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 2UL*sizeof(*tim_colormap)); if (tim_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,2*image->colors,tim_colormap); if (count != (ssize_t) (2*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=tim_colormap; for (i=0; i < (ssize_t) image->colors; i++) { word=(*p++); word|=(unsigned short) (*p++ << 8); image->colormap[i].blue=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 10) & 0x1f)); image->colormap[i].green=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 5) & 0x1f)); image->colormap[i].red=ScaleCharToQuantum( ScaleColor5to8(1UL*word & 0x1f)); } tim_colormap=(unsigned char *) RelinquishMagickMemory(tim_colormap); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Read image data. */ (void) ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image_size=2*width*height; bytes_per_line=width*2; width=(width*16)/bits_per_pixel; tim_data=(unsigned char *) AcquireQuantumMemory(image_size, sizeof(*tim_data)); if (tim_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image_size,tim_data); if (count != (ssize_t) (image_size)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); tim_pixels=tim_data; /* Initialize image structure. */ image->columns=width; image->rows=height; /* Convert TIM raster image to pixel packets. */ switch (bits_per_pixel) { case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { SetPixelIndex(indexes+x,(*p) & 0x0f); SetPixelIndex(indexes+x+1,(*p >> 4) & 0x0f); p++; } if ((image->columns % 2) != 0) { SetPixelIndex(indexes+x,(*p >> 4) & 0x0f); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; 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; } } break; } case 16: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 10) & 0x1f))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 5) & 0x1f))); SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 0) & 0x1f))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; 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++)); SetPixelBlue(q,ScaleCharToQuantum(*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; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image->storage_class == PseudoClass) (void) SyncImage(image); tim_pixels=(unsigned char *) RelinquishMagickMemory(tim_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ tim_info.id=ReadBlobLSBLong(image); if (tim_info.id == 0x00000010) { /* 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 (tim_info.id == 0x00000010); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) { typedef struct _TIMInfo { size_t id, flag; } TIMInfo; TIMInfo tim_info; Image *image; int bits_per_pixel, has_clut; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, height, image_size, pixel_mode, width; ssize_t count, y; unsigned char *tim_data, *tim_pixels; unsigned short word; /* 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); } /* Determine if this a TIM file. */ tim_info.id=ReadBlobLSBLong(image); do { /* Verify TIM identifier. */ if (tim_info.id != 0x00000010) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tim_info.flag=ReadBlobLSBLong(image); has_clut=tim_info.flag & (1 << 3) ? 1 : 0; pixel_mode=tim_info.flag & 0x07; switch ((int) pixel_mode) { case 0: bits_per_pixel=4; break; case 1: bits_per_pixel=8; break; case 2: bits_per_pixel=16; break; case 3: bits_per_pixel=24; break; default: bits_per_pixel=4; break; } image->depth=8; if (has_clut) { unsigned char *tim_colormap; /* Read TIM raster colormap. */ (void)ReadBlobLSBLong(image); (void)ReadBlobLSBShort(image); (void)ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image->columns=width; image->rows=height; if (AcquireImageColormap(image,pixel_mode == 1 ? 256UL : 16UL) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); tim_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 2UL*sizeof(*tim_colormap)); if (tim_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,2*image->colors,tim_colormap); if (count != (ssize_t) (2*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=tim_colormap; for (i=0; i < (ssize_t) image->colors; i++) { word=(*p++); word|=(unsigned short) (*p++ << 8); image->colormap[i].blue=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 10) & 0x1f)); image->colormap[i].green=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 5) & 0x1f)); image->colormap[i].red=ScaleCharToQuantum( ScaleColor5to8(1UL*word & 0x1f)); } tim_colormap=(unsigned char *) RelinquishMagickMemory(tim_colormap); } 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)); } /* Read image data. */ (void) ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image_size=2*width*height; bytes_per_line=width*2; width=(width*16)/bits_per_pixel; tim_data=(unsigned char *) AcquireQuantumMemory(image_size, sizeof(*tim_data)); if (tim_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image_size,tim_data); if (count != (ssize_t) (image_size)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); tim_pixels=tim_data; /* Initialize image structure. */ image->columns=width; image->rows=height; /* Convert TIM raster image to pixel packets. */ switch (bits_per_pixel) { case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { SetPixelIndex(indexes+x,(*p) & 0x0f); SetPixelIndex(indexes+x+1,(*p >> 4) & 0x0f); p++; } if ((image->columns % 2) != 0) { SetPixelIndex(indexes+x,(*p >> 4) & 0x0f); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; 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; } } break; } case 16: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 10) & 0x1f))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 5) & 0x1f))); SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 0) & 0x1f))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; 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++)); SetPixelBlue(q,ScaleCharToQuantum(*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; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image->storage_class == PseudoClass) (void) SyncImage(image); tim_pixels=(unsigned char *) RelinquishMagickMemory(tim_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ tim_info.id=ReadBlobLSBLong(image); if (tim_info.id == 0x00000010) { /* 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 (tim_info.id == 0x00000010); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,611
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: acc_ctx_new(OM_uint32 *minor_status, gss_buffer_t buf, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret, req_flags; gss_OID_set supported_mechSet, mechTypes; gss_buffer_desc der_mechTypes; gss_OID mech_wanted; spnego_gss_ctx_id_t sc = NULL; ret = GSS_S_DEFECTIVE_TOKEN; der_mechTypes.length = 0; der_mechTypes.value = NULL; *mechToken = *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = mechTypes = GSS_C_NO_OID_SET; *return_token = ERROR_TOKEN_SEND; *negState = REJECT; *minor_status = 0; ret = get_negTokenInit(minor_status, buf, &der_mechTypes, &mechTypes, &req_flags, mechToken, mechListMIC); if (ret != GSS_S_COMPLETE) { goto cleanup; } ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) { *return_token = NO_TOKEN_SEND; goto cleanup; } /* * Select the best match between the list of mechs * that the initiator requested and the list that * the acceptor will support. */ mech_wanted = negotiate_mech(supported_mechSet, mechTypes, negState); if (*negState == REJECT) { ret = GSS_S_BAD_MECH; goto cleanup; } sc = (spnego_gss_ctx_id_t)*ctx; if (sc != NULL) { gss_release_buffer(&tmpmin, &sc->DER_mechTypes); assert(mech_wanted != GSS_C_NO_OID); } else sc = create_spnego_ctx(); if (sc == NULL) { ret = GSS_S_FAILURE; *return_token = NO_TOKEN_SEND; goto cleanup; } sc->mech_set = mechTypes; mechTypes = GSS_C_NO_OID_SET; sc->internal_mech = mech_wanted; sc->DER_mechTypes = der_mechTypes; der_mechTypes.length = 0; der_mechTypes.value = NULL; if (*negState == REQUEST_MIC) sc->mic_reqd = 1; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; ret = GSS_S_COMPLETE; cleanup: gss_release_oid_set(&tmpmin, &mechTypes); gss_release_oid_set(&tmpmin, &supported_mechSet); if (der_mechTypes.length != 0) gss_release_buffer(&tmpmin, &der_mechTypes); return ret; } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
acc_ctx_new(OM_uint32 *minor_status, gss_buffer_t buf, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret, req_flags; gss_OID_set supported_mechSet, mechTypes; gss_buffer_desc der_mechTypes; gss_OID mech_wanted; spnego_gss_ctx_id_t sc = NULL; ret = GSS_S_DEFECTIVE_TOKEN; der_mechTypes.length = 0; der_mechTypes.value = NULL; *mechToken = *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = mechTypes = GSS_C_NO_OID_SET; *return_token = ERROR_TOKEN_SEND; *negState = REJECT; *minor_status = 0; ret = get_negTokenInit(minor_status, buf, &der_mechTypes, &mechTypes, &req_flags, mechToken, mechListMIC); if (ret != GSS_S_COMPLETE) { goto cleanup; } ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) { *return_token = NO_TOKEN_SEND; goto cleanup; } /* * Select the best match between the list of mechs * that the initiator requested and the list that * the acceptor will support. */ mech_wanted = negotiate_mech(supported_mechSet, mechTypes, negState); if (*negState == REJECT) { ret = GSS_S_BAD_MECH; goto cleanup; } sc = (spnego_gss_ctx_id_t)*ctx; if (sc != NULL) { gss_release_buffer(&tmpmin, &sc->DER_mechTypes); assert(mech_wanted != GSS_C_NO_OID); } else sc = create_spnego_ctx(0); if (sc == NULL) { ret = GSS_S_FAILURE; *return_token = NO_TOKEN_SEND; goto cleanup; } sc->mech_set = mechTypes; mechTypes = GSS_C_NO_OID_SET; sc->internal_mech = mech_wanted; sc->DER_mechTypes = der_mechTypes; der_mechTypes.length = 0; der_mechTypes.value = NULL; if (*negState == REQUEST_MIC) sc->mic_reqd = 1; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; ret = GSS_S_COMPLETE; cleanup: gss_release_oid_set(&tmpmin, &mechTypes); gss_release_oid_set(&tmpmin, &supported_mechSet); if (der_mechTypes.length != 0) gss_release_buffer(&tmpmin, &der_mechTypes); return ret; }
166,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = r - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } 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
static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, static unsigned int mb_ss_ref(const int16_t *src) { unsigned int res = 0; for (int i = 0; i < 256; ++i) { res += src[i] * src[i]; } return res; } static uint32_t variance_ref(const uint8_t *src, const uint8_t *ref, int l2w, int l2h, int src_stride_coeff, int ref_stride_coeff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int diff; if (!use_high_bit_depth_) { diff = ref[w * y * ref_stride_coeff + x] - src[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { diff = CONVERT_TO_SHORTPTR(ref)[w * y * ref_stride_coeff + x] - CONVERT_TO_SHORTPTR(src)[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } /* The subpel reference functions differ from the codec version in one aspect: * they calculate the bilinear factors directly instead of using a lookup table * and therefore upshift xoff and yoff by 1. Only every other calculated value * is used so the codec version shrinks the table to save space and maintain * compatibility with vp8. */ static uint32_t subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; xoff <<= 1; yoff <<= 1; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // Bilinear interpolation at a 16th pel step. if (!use_high_bit_depth_) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src[w * y + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref); uint16_t *src16 = CONVERT_TO_SHORTPTR(src); const int a1 = ref16[(w + 1) * (y + 0) + x + 0]; const int a2 = ref16[(w + 1) * (y + 0) + x + 1]; const int b1 = ref16[(w + 1) * (y + 1) + x + 0]; const int b2 = ref16[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src16[w * y + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } class SumOfSquaresTest : public ::testing::TestWithParam<SumOfSquaresFunction> { public: SumOfSquaresTest() : func_(GetParam()) {} virtual ~SumOfSquaresTest() { libvpx_test::ClearSystemState(); } protected: void ConstTest(); void RefTest(); SumOfSquaresFunction func_; ACMRandom rnd_; }; void SumOfSquaresTest::ConstTest() { int16_t mem[256]; unsigned int res; for (int v = 0; v < 256; ++v) { for (int i = 0; i < 256; ++i) { mem[i] = v; } ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(256u * (v * v), res); } } void SumOfSquaresTest::RefTest() { int16_t mem[256]; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 256; ++j) { mem[j] = rnd_.Rand8() - rnd_.Rand8(); } const unsigned int expected = mb_ss_ref(mem); unsigned int res; ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(expected, res); } }
174,595
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: sec_decrypt(uint8 * data, int length) { if (g_sec_decrypt_use_count == 4096) { sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key); rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len); g_sec_decrypt_use_count = 0; } rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length); g_sec_decrypt_use_count++; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
sec_decrypt(uint8 * data, int length) { if (length <= 0) return; if (g_sec_decrypt_use_count == 4096) { sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key); rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len); g_sec_decrypt_use_count = 0; } rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length); g_sec_decrypt_use_count++; }
169,810
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 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return (-1); /* XXX: check what the second '&& type' is about */ if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* * check whether there's a handshake message (client hello?) waiting */ if ((ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* * Continue handshake if it had to be interrupted to read app data with * SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret = dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return (ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (rr->type != SSL3_RT_ALERT && rr->length != 0) s->cert->alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* * We now have application data between CCS and Finished. Most likely * the packets were reordered on their way, so buffer the application * data for later processing rather than dropping the connection. */ if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) < 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } rr->length = 0; goto start; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length = 0; s->rwstate = SSL_NOTHING; return (0); } if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return (len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf, &(rr->data[rr->off]), n); if (!peek) { rr->length -= n; rr->off += n; if (rr->length == 0) { s->rstate = SSL_ST_READ_HEADER; rr->off = 0; } } #ifndef OPENSSL_NO_SCTP /* * We were about to renegotiate but had to read belated application * data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* * We might had to delay a close_notify alert because of reordered * app data. If there was an alert and there is no message to read * anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #endif return (n); } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof(s->d1->handshake_fragment); dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return (-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* * Application data while renegotiating is allowed. Try again * reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data = 2; bio = SSL_get_rbio(s); s->rwstate = SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } /* Not certain if this is the right error handling */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* * XDTLS: In a pathalogical case, the Client Hello may be * fragmented--don't always expect dest_maxlen bytes */ if (rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate = SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for (k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /*- * s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } /* * no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } /* * If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO && s->s3->previous_client_finished_len != 0 && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) { s->d1->handshake_fragment_len = 0; rr->length = 0; ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; s->cert->alert_count++; if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); goto f_err; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* * With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this first so * that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority (frag->msg_header.seq, 0), frag_off, &found); if (!found && SSL_in_init(s)) { /* * fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* * requested a message not yet sent, send an alert * ourselves */ ssl3_send_alert(s, SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; rr->length = 0; return (0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* * 'Change Cipher Spec' is just a single byte, so we know exactly * what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ((rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } rr->length = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* * We can't process a CCS now, because previous handshake messages * are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec = 1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* * Remember that a CCS has been received, so that an old key of * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no * SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if (rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* * If we are server, we may have a repeated FINISHED of the client * here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state & SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences * are not as expected (and because this is * not really needed for clients except for * detecting protocol violations): */ s->state = SSL_ST_BEFORE | (s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not * happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (((s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ((s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return (-1); } Commit Message: CWE ID: CWE-200
int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return (-1); /* XXX: check what the second '&& type' is about */ if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* * check whether there's a handshake message (client hello?) waiting */ if ((ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* * Continue handshake if it had to be interrupted to read app data with * SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret = dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return (ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (rr->type != SSL3_RT_ALERT && rr->length != 0) s->cert->alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* * We now have application data between CCS and Finished. Most likely * the packets were reordered on their way, so buffer the application * data for later processing rather than dropping the connection. */ if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) < 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } rr->length = 0; goto start; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length = 0; s->rwstate = SSL_NOTHING; return (0); } if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return (len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf, &(rr->data[rr->off]), n); if (!peek) { rr->length -= n; rr->off += n; if (rr->length == 0) { s->rstate = SSL_ST_READ_HEADER; rr->off = 0; } } #ifndef OPENSSL_NO_SCTP /* * We were about to renegotiate but had to read belated application * data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* * We might had to delay a close_notify alert because of reordered * app data. If there was an alert and there is no message to read * anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #endif return (n); } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof(s->d1->handshake_fragment); dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return (-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* * Application data while renegotiating is allowed. Try again * reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data = 2; bio = SSL_get_rbio(s); s->rwstate = SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } /* Not certain if this is the right error handling */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* * XDTLS: In a pathalogical case, the Client Hello may be * fragmented--don't always expect dest_maxlen bytes */ if (rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate = SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for (k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /*- * s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } /* * no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } /* * If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO && s->s3->previous_client_finished_len != 0 && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) { s->d1->handshake_fragment_len = 0; rr->length = 0; ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; s->cert->alert_count++; if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); goto f_err; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* * With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this first so * that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority (frag->msg_header.seq, 0), frag_off, &found); if (!found && SSL_in_init(s)) { /* * fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* * requested a message not yet sent, send an alert * ourselves */ ssl3_send_alert(s, SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->session_ctx, s->session); s->state = SSL_ST_ERR; return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; rr->length = 0; return (0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* * 'Change Cipher Spec' is just a single byte, so we know exactly * what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ((rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } rr->length = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* * We can't process a CCS now, because previous handshake messages * are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec = 1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* * Remember that a CCS has been received, so that an old key of * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no * SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if (rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* * If we are server, we may have a repeated FINISHED of the client * here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state & SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences * are not as expected (and because this is * not really needed for clients except for * detecting protocol violations): */ s->state = SSL_ST_BEFORE | (s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not * happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (((s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ((s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return (-1); }
165,139
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: MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0) { } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0), new_window_routing_id_(0) { }
171,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: pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata, const uint8_t *cert, size_t cert_len, krb5_const_principal princ, const void *opts, const struct _krb5_db_entry_new *db_entry, char ***authinds_out) { krb5_error_code ret; int valid_eku; const struct certauth_req_opts *req_opts = opts; *authinds_out = NULL; /* Verify the client EKU. */ ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx, &valid_eku); if (ret) return ret; if (!valid_eku) { TRACE_PKINIT_SERVER_EKU_REJECT(context); return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; } return 0; } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 CWE ID: CWE-287
pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata, const uint8_t *cert, size_t cert_len, krb5_const_principal princ, const void *opts, const struct _krb5_db_entry_new *db_entry, char ***authinds_out) { krb5_error_code ret; int valid_eku; const struct certauth_req_opts *req_opts = opts; *authinds_out = NULL; /* Verify the client EKU. */ ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx, &valid_eku); if (ret) return ret; if (!valid_eku) { TRACE_PKINIT_SERVER_EKU_REJECT(context); return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; } return KRB5_PLUGIN_NO_HANDLE; }
170,174
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: LockContentsView::UserState::UserState(AccountId account_id) : account_id(account_id) {} Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
LockContentsView::UserState::UserState(AccountId account_id)
172,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: struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, np->opt, &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; } 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
struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; }
167,339
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: MirrorMockURLRequestJob(net::URLRequest* request, net::NetworkDelegate* network_delegate, const base::FilePath& file_path, ReportResponseHeadersOnUI report_on_ui) : net::URLRequestMockHTTPJob(request, network_delegate, file_path), report_on_ui_(report_on_ui) {} Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID:
MirrorMockURLRequestJob(net::URLRequest* request,
172,578
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 NormalPageArena::coalesce() { if (m_promptlyFreedSize < 1024 * 1024) return false; if (getThreadState()->sweepForbidden()) return false; ASSERT(!hasCurrentAllocationArea()); TRACE_EVENT0("blink_gc", "BaseArena::coalesce"); m_freeList.clear(); size_t freedSize = 0; for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page; page = static_cast<NormalPage*>(page->next())) { Address startOfGap = page->payload(); for (Address headerAddress = startOfGap; headerAddress < page->payloadEnd();) { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); size_t size = header->size(); ASSERT(size > 0); ASSERT(size < blinkPagePayloadSize()); if (header->isPromptlyFreed()) { ASSERT(size >= sizeof(HeapObjectHeader)); SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); freedSize += size; headerAddress += size; continue; } if (header->isFree()) { SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry) ? size : sizeof(FreeListEntry)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); headerAddress += size; continue; } ASSERT(header->checkHeader()); if (startOfGap != headerAddress) addToFreeList(startOfGap, headerAddress - startOfGap); headerAddress += size; startOfGap = headerAddress; } if (startOfGap != page->payloadEnd()) addToFreeList(startOfGap, page->payloadEnd() - startOfGap); } getThreadState()->decreaseAllocatedObjectSize(freedSize); ASSERT(m_promptlyFreedSize == freedSize); m_promptlyFreedSize = 0; return true; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool NormalPageArena::coalesce() { if (m_promptlyFreedSize < 1024 * 1024) return false; if (getThreadState()->sweepForbidden()) return false; ASSERT(!hasCurrentAllocationArea()); TRACE_EVENT0("blink_gc", "BaseArena::coalesce"); m_freeList.clear(); size_t freedSize = 0; for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page; page = static_cast<NormalPage*>(page->next())) { Address startOfGap = page->payload(); for (Address headerAddress = startOfGap; headerAddress < page->payloadEnd();) { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); size_t size = header->size(); ASSERT(size > 0); ASSERT(size < blinkPagePayloadSize()); if (header->isPromptlyFreed()) { ASSERT(size >= sizeof(HeapObjectHeader)); SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); freedSize += size; headerAddress += size; continue; } if (header->isFree()) { SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry) ? size : sizeof(FreeListEntry)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); headerAddress += size; continue; } header->checkHeader(); if (startOfGap != headerAddress) addToFreeList(startOfGap, headerAddress - startOfGap); headerAddress += size; startOfGap = headerAddress; } if (startOfGap != page->payloadEnd()) addToFreeList(startOfGap, page->payloadEnd() - startOfGap); } getThreadState()->decreaseAllocatedObjectSize(freedSize); ASSERT(m_promptlyFreedSize == freedSize); m_promptlyFreedSize = 0; return true; }
172,708
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 *etm_setup_aux(int event_cpu, void **pages, int nr_pages, bool overwrite) { int cpu; cpumask_t *mask; struct coresight_device *sink; struct etm_event_data *event_data = NULL; event_data = alloc_event_data(event_cpu); if (!event_data) return NULL; /* * In theory nothing prevent tracers in a trace session from being * associated with different sinks, nor having a sink per tracer. But * until we have HW with this kind of topology we need to assume tracers * in a trace session are using the same sink. Therefore go through * the coresight bus and pick the first enabled sink. * * When operated from sysFS users are responsible to enable the sink * while from perf, the perf tools will do it based on the choice made * on the cmd line. As such the "enable_sink" flag in sysFS is reset. */ sink = coresight_get_enabled_sink(true); if (!sink) goto err; INIT_WORK(&event_data->work, free_event_data); mask = &event_data->mask; /* Setup the path for each CPU in a trace session */ for_each_cpu(cpu, mask) { struct coresight_device *csdev; csdev = per_cpu(csdev_src, cpu); if (!csdev) goto err; /* * Building a path doesn't enable it, it simply builds a * list of devices from source to sink that can be * referenced later when the path is actually needed. */ event_data->path[cpu] = coresight_build_path(csdev, sink); if (IS_ERR(event_data->path[cpu])) goto err; } if (!sink_ops(sink)->alloc_buffer) goto err; /* Get the AUX specific data from the sink buffer */ event_data->snk_config = sink_ops(sink)->alloc_buffer(sink, cpu, pages, nr_pages, overwrite); if (!event_data->snk_config) goto err; out: return event_data; err: etm_free_aux(event_data); event_data = NULL; goto out; } Commit Message: coresight: fix kernel panic caused by invalid CPU Commit d52c9750f150 ("coresight: reset "enable_sink" flag when need be") caused a kernel panic because of the using of an invalid value: after 'for_each_cpu(cpu, mask)', value of local variable 'cpu' become invalid, causes following 'cpu_to_node' access invalid memory area. This patch brings the deleted 'cpu = cpumask_first(mask)' back. Panic log: $ perf record -e cs_etm// ls Unable to handle kernel paging request at virtual address fffe801804af4f10 pgd = ffff8017ce031600 [fffe801804af4f10] *pgd=0000000000000000, *pud=0000000000000000 Internal error: Oops: 96000004 [#1] SMP Modules linked in: CPU: 33 PID: 1619 Comm: perf Not tainted 4.7.1+ #16 Hardware name: Huawei Taishan 2280 /CH05TEVBA, BIOS 1.10 11/24/2016 task: ffff8017cb0c8400 ti: ffff8017cb154000 task.ti: ffff8017cb154000 PC is at tmc_alloc_etf_buffer+0x60/0xd4 LR is at tmc_alloc_etf_buffer+0x44/0xd4 pc : [<ffff000008633df8>] lr : [<ffff000008633ddc>] pstate: 60000145 sp : ffff8017cb157b40 x29: ffff8017cb157b40 x28: 0000000000000000 ...skip... 7a60: ffff000008c64dc8 0000000000000006 0000000000000253 ffffffffffffffff 7a80: 0000000000000000 0000000000000000 ffff0000080872cc 0000000000000001 [<ffff000008633df8>] tmc_alloc_etf_buffer+0x60/0xd4 [<ffff000008632b9c>] etm_setup_aux+0x1dc/0x1e8 [<ffff00000816eed4>] rb_alloc_aux+0x2b0/0x338 [<ffff00000816a5e4>] perf_mmap+0x414/0x568 [<ffff0000081ab694>] mmap_region+0x324/0x544 [<ffff0000081abbe8>] do_mmap+0x334/0x3e0 [<ffff000008191150>] vm_mmap_pgoff+0xa4/0xc8 [<ffff0000081a9a30>] SyS_mmap_pgoff+0xb0/0x22c [<ffff0000080872e4>] sys_mmap+0x18/0x28 [<ffff0000080843f0>] el0_svc_naked+0x24/0x28 Code: 912040a5 d0001c00 f873d821 911c6000 (b8656822) ---[ end trace 98933da8f92b0c9a ]--- Signed-off-by: Wang Nan <[email protected]> Cc: Xia Kaixu <[email protected]> Cc: Li Zefan <[email protected]> Cc: Mathieu Poirier <[email protected]> Cc: [email protected] Cc: [email protected] Fixes: d52c9750f150 ("coresight: reset "enable_sink" flag when need be") Signed-off-by: Mathieu Poirier <[email protected]> Cc: stable <[email protected]> # 4.10 Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-20
static void *etm_setup_aux(int event_cpu, void **pages, int nr_pages, bool overwrite) { int cpu; cpumask_t *mask; struct coresight_device *sink; struct etm_event_data *event_data = NULL; event_data = alloc_event_data(event_cpu); if (!event_data) return NULL; /* * In theory nothing prevent tracers in a trace session from being * associated with different sinks, nor having a sink per tracer. But * until we have HW with this kind of topology we need to assume tracers * in a trace session are using the same sink. Therefore go through * the coresight bus and pick the first enabled sink. * * When operated from sysFS users are responsible to enable the sink * while from perf, the perf tools will do it based on the choice made * on the cmd line. As such the "enable_sink" flag in sysFS is reset. */ sink = coresight_get_enabled_sink(true); if (!sink) goto err; INIT_WORK(&event_data->work, free_event_data); mask = &event_data->mask; /* Setup the path for each CPU in a trace session */ for_each_cpu(cpu, mask) { struct coresight_device *csdev; csdev = per_cpu(csdev_src, cpu); if (!csdev) goto err; /* * Building a path doesn't enable it, it simply builds a * list of devices from source to sink that can be * referenced later when the path is actually needed. */ event_data->path[cpu] = coresight_build_path(csdev, sink); if (IS_ERR(event_data->path[cpu])) goto err; } if (!sink_ops(sink)->alloc_buffer) goto err; cpu = cpumask_first(mask); /* Get the AUX specific data from the sink buffer */ event_data->snk_config = sink_ops(sink)->alloc_buffer(sink, cpu, pages, nr_pages, overwrite); if (!event_data->snk_config) goto err; out: return event_data; err: etm_free_aux(event_data); event_data = NULL; goto out; }
169,236
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void init_once(void *foo) { struct ext4_inode_info *ei = (struct ext4_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); init_rwsem(&ei->xattr_sem); init_rwsem(&ei->i_data_sem); inode_init_once(&ei->vfs_inode); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362
static void init_once(void *foo) { struct ext4_inode_info *ei = (struct ext4_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); init_rwsem(&ei->xattr_sem); init_rwsem(&ei->i_data_sem); init_rwsem(&ei->i_mmap_sem); inode_init_once(&ei->vfs_inode); }
167,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PageInfo::PresentSiteIdentity() { DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN); DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN); PageInfoUI::IdentityInfo info; if (site_identity_status_ == SITE_IDENTITY_STATUS_EV_CERT) info.site_identity = UTF16ToUTF8(organization_name()); else info.site_identity = UTF16ToUTF8(GetSimpleSiteName(site_url_)); info.connection_status = site_connection_status_; info.connection_status_description = UTF16ToUTF8(site_connection_details_); info.identity_status = site_identity_status_; info.safe_browsing_status = safe_browsing_status_; info.identity_status_description = UTF16ToUTF8(site_details_message_); info.certificate = certificate_; info.show_ssl_decision_revoke_button = show_ssl_decision_revoke_button_; info.show_change_password_buttons = show_change_password_buttons_; ui_->SetIdentityInfo(info); } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311
void PageInfo::PresentSiteIdentity() { DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN); DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN); PageInfoUI::IdentityInfo info; if (site_identity_status_ == SITE_IDENTITY_STATUS_EV_CERT) info.site_identity = UTF16ToUTF8(organization_name()); else info.site_identity = UTF16ToUTF8(GetSimpleSiteName(site_url_)); info.connection_status = site_connection_status_; info.connection_status_description = UTF16ToUTF8(site_connection_details_); info.identity_status = site_identity_status_; info.identity_status_description = UTF16ToUTF8(site_identity_details_); info.certificate = certificate_; info.show_ssl_decision_revoke_button = show_ssl_decision_revoke_button_; info.show_change_password_buttons = show_change_password_buttons_; ui_->SetIdentityInfo(info); }
172,438
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) // we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size + 1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success } 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
long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long UnserializeString(IMkvReader* pReader, long long pos, long long size, char*& str) { delete[] str; str = NULL; if (size >= LONG_MAX || size < 0) return E_FILE_FORMAT_INVALID; // +1 for '\0' terminator const long required_size = static_cast<long>(size) + 1; str = SafeArrayAlloc<char>(1, required_size); if (str == NULL) return E_FILE_FORMAT_INVALID; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[required_size - 1] = '\0'; return 0; }
173,867
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 inode_capable(const struct inode *inode, int cap) { struct user_namespace *ns = current_user_ns(); return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid); } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Dave Chinner <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
bool inode_capable(const struct inode *inode, int cap) bool capable_wrt_inode_uidgid(const struct inode *inode, int cap) { struct user_namespace *ns = current_user_ns(); return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid) && kgid_has_mapping(ns, inode->i_gid); }
166,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_destroy(png_structp png_ptr) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* Save jump buffer */ #endif png_error_ptr error_fn; png_error_ptr warning_fn; png_voidp error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_free_ptr free_fn; #endif png_debug(1, "in png_write_destroy"); /* Free any memory zlib uses */ deflateEnd(&png_ptr->zstream); /* Free our memory. png_free checks NULL for us. */ png_free(png_ptr, png_ptr->zbuf); png_free(png_ptr, png_ptr->row_buf); #ifdef PNG_WRITE_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_row); png_free(png_ptr, png_ptr->sub_row); png_free(png_ptr, png_ptr->up_row); png_free(png_ptr, png_ptr->avg_row); png_free(png_ptr, png_ptr->paeth_row); #endif #ifdef PNG_TIME_RFC1123_SUPPORTED png_free(png_ptr, png_ptr->time_buffer); #endif #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_filters); png_free(png_ptr, png_ptr->filter_weights); png_free(png_ptr, png_ptr->inv_filter_weights); png_free(png_ptr, png_ptr->filter_costs); png_free(png_ptr, png_ptr->inv_filter_costs); #endif #ifdef PNG_SETJMP_SUPPORTED /* Reset structure */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif error_fn = png_ptr->error_fn; warning_fn = png_ptr->warning_fn; error_ptr = png_ptr->error_ptr; #ifdef PNG_USER_MEM_SUPPORTED free_fn = png_ptr->free_fn; #endif png_memset(png_ptr, 0, png_sizeof(png_struct)); png_ptr->error_fn = error_fn; png_ptr->warning_fn = warning_fn; png_ptr->error_ptr = error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_ptr->free_fn = free_fn; #endif #ifdef PNG_SETJMP_SUPPORTED png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_destroy(png_structp png_ptr) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* Save jump buffer */ #endif png_error_ptr error_fn; png_error_ptr warning_fn; png_voidp error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_free_ptr free_fn; #endif png_debug(1, "in png_write_destroy"); /* Free any memory zlib uses */ deflateEnd(&png_ptr->zstream); /* Free our memory. png_free checks NULL for us. */ png_free(png_ptr, png_ptr->zbuf); png_free(png_ptr, png_ptr->row_buf); #ifdef PNG_WRITE_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_row); png_free(png_ptr, png_ptr->sub_row); png_free(png_ptr, png_ptr->up_row); png_free(png_ptr, png_ptr->avg_row); png_free(png_ptr, png_ptr->paeth_row); #endif #ifdef PNG_TIME_RFC1123_SUPPORTED png_free(png_ptr, png_ptr->time_buffer); #endif #ifdef PNG_SETJMP_SUPPORTED /* Reset structure */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif error_fn = png_ptr->error_fn; warning_fn = png_ptr->warning_fn; error_ptr = png_ptr->error_ptr; #ifdef PNG_USER_MEM_SUPPORTED free_fn = png_ptr->free_fn; #endif png_memset(png_ptr, 0, png_sizeof(png_struct)); png_ptr->error_fn = error_fn; png_ptr->warning_fn = warning_fn; png_ptr->error_ptr = error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_ptr->free_fn = free_fn; #endif #ifdef PNG_SETJMP_SUPPORTED png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif }
172,189
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: NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { jsvUnLock(jspeStatement()); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } } Commit Message: Fix stack overflow if void void void... is repeated many times (fix #1434) CWE ID: CWE-119
NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { jsvUnLock(jspeStatement()); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } }
169,214
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: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; } Commit Message: CWE ID: CWE-189
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmallocn(h, line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; }
164,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: static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *file; struct path path; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened); goto out; } error = path_init(dfd, pathname, flags, nd); if (unlikely(error)) goto out; error = do_last(nd, &path, file, op, &opened, pathname); while (unlikely(error > 0)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); error = -ELOOP; break; } error = may_follow_link(&link, nd); if (unlikely(error)) break; nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) break; error = do_last(nd, &path, file, op, &opened, pathname); put_link(nd, &link, cookie); } out: path_cleanup(nd); if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; } Commit Message: path_openat(): fix double fput() path_openat() jumps to the wrong place after do_tmpfile() - it has already done path_cleanup() (as part of path_lookupat() called by do_tmpfile()), so doing that again can lead to double fput(). Cc: [email protected] # v3.11+ Signed-off-by: Al Viro <[email protected]> CWE ID:
static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *file; struct path path; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened); goto out2; } error = path_init(dfd, pathname, flags, nd); if (unlikely(error)) goto out; error = do_last(nd, &path, file, op, &opened, pathname); while (unlikely(error > 0)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); error = -ELOOP; break; } error = may_follow_link(&link, nd); if (unlikely(error)) break; nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) break; error = do_last(nd, &path, file, op, &opened, pathname); put_link(nd, &link, cookie); } out: path_cleanup(nd); out2: if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; }
166,594
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[]) { char* name = argv[0]; bool applyColorCorrection = false; #if USE(QCMSLIB) if (argc >= 2 && strcmp(argv[1], "--color-correct") == 0) applyColorCorrection = (--argc, ++argv, true); if (argc < 2) { fprintf(stderr, "Usage: %s [--color-correct] file [iterations] [packetSize]\n", name); exit(1); } #else if (argc < 2) { fprintf(stderr, "Usage: %s file [iterations] [packetSize]\n", name); exit(1); } #endif size_t iterations = 1; if (argc >= 3) { char* end = 0; iterations = strtol(argv[2], &end, 10); if (*end != '\0' || !iterations) { fprintf(stderr, "Second argument should be number of iterations. " "The default is 1. You supplied %s\n", argv[2]); exit(1); } } size_t packetSize = 0; if (argc >= 4) { char* end = 0; packetSize = strtol(argv[3], &end, 10); if (*end != '\0') { fprintf(stderr, "Third argument should be packet size. Default is " "0, meaning to decode the entire image in one packet. You " "supplied %s\n", argv[3]); exit(1); } } class WebPlatform : public blink::Platform { public: const unsigned char* getTraceCategoryEnabledFlag(const char*) override { return reinterpret_cast<const unsigned char *>("nope-none-nada"); } void cryptographicallyRandomValues(unsigned char*, size_t) override { } void screenColorProfile(WebVector<char>* profile) override { getScreenColorProfile(profile); // Returns a whacked color profile. } }; blink::initializeWithoutV8(new WebPlatform()); #if USE(QCMSLIB) ImageDecoder::qcmsOutputDeviceProfile(); // Initialize screen colorProfile. #endif RefPtr<SharedBuffer> data = readFile(argv[1]); if (!data.get() || !data->size()) { fprintf(stderr, "Error reading image data from [%s]\n", argv[1]); exit(2); } data->data(); double totalTime = 0.0; for (size_t i = 0; i < iterations; ++i) { double startTime = getCurrentTime(); bool decoded = decodeImageData(data.get(), applyColorCorrection, packetSize); double elapsedTime = getCurrentTime() - startTime; totalTime += elapsedTime; if (!decoded) { fprintf(stderr, "Image decode failed [%s]\n", argv[1]); exit(3); } } double averageTime = totalTime / static_cast<double>(iterations); printf("%f %f\n", totalTime, averageTime); return 0; } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310
int main(int argc, char* argv[]) { char* name = argv[0]; bool applyColorCorrection = false; #if USE(QCMSLIB) if (argc >= 2 && strcmp(argv[1], "--color-correct") == 0) applyColorCorrection = (--argc, ++argv, true); if (argc < 2) { fprintf(stderr, "Usage: %s [--color-correct] file [iterations] [packetSize]\n", name); exit(1); } #else if (argc < 2) { fprintf(stderr, "Usage: %s file [iterations] [packetSize]\n", name); exit(1); } #endif size_t iterations = 1; if (argc >= 3) { char* end = 0; iterations = strtol(argv[2], &end, 10); if (*end != '\0' || !iterations) { fprintf(stderr, "Second argument should be number of iterations. " "The default is 1. You supplied %s\n", argv[2]); exit(1); } } size_t packetSize = 0; if (argc >= 4) { char* end = 0; packetSize = strtol(argv[3], &end, 10); if (*end != '\0') { fprintf(stderr, "Third argument should be packet size. Default is " "0, meaning to decode the entire image in one packet. You " "supplied %s\n", argv[3]); exit(1); } } class WebPlatform : public blink::Platform { public: const unsigned char* getTraceCategoryEnabledFlag(const char*) override { return reinterpret_cast<const unsigned char *>("nope-none-nada"); } void cryptographicallyRandomValues(unsigned char*, size_t) override { RELEASE_ASSERT_NOT_REACHED(); } void screenColorProfile(WebVector<char>* profile) override { getScreenColorProfile(profile); // Returns a whacked color profile. } }; blink::initializeWithoutV8(new WebPlatform()); #if USE(QCMSLIB) ImageDecoder::qcmsOutputDeviceProfile(); // Initialize screen colorProfile. #endif RefPtr<SharedBuffer> data = readFile(argv[1]); if (!data.get() || !data->size()) { fprintf(stderr, "Error reading image data from [%s]\n", argv[1]); exit(2); } data->data(); double totalTime = 0.0; for (size_t i = 0; i < iterations; ++i) { double startTime = getCurrentTime(); bool decoded = decodeImageData(data.get(), applyColorCorrection, packetSize); double elapsedTime = getCurrentTime() - startTime; totalTime += elapsedTime; if (!decoded) { fprintf(stderr, "Image decode failed [%s]\n", argv[1]); exit(3); } } double averageTime = totalTime / static_cast<double>(iterations); printf("%f %f\n", totalTime, averageTime); return 0; }
172,240
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 mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119
int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); if (!lua_checkstack(L, nargs)) return luaL_argerror(L, 0, "Too many arguments for MessagePack pack."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ luaL_checkstack(L, 1, "in function mp_check"); lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; }
169,241
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 IsValidSymbolicLink(const FilePath& file_path, GDataCache::CacheSubDirectoryType sub_dir_type, const std::vector<FilePath>& cache_paths, std::string* reason) { DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PINNED || sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING); FilePath destination; if (!file_util::ReadSymbolicLink(file_path, &destination)) { *reason = "failed to read the symlink (maybe not a symlink)"; return false; } if (!file_util::PathExists(destination)) { *reason = "pointing to a non-existent file"; return false; } if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED && destination == FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull)) { return true; } if (!cache_paths[GDataCache::CACHE_TYPE_PERSISTENT].IsParent(destination)) { *reason = "pointing to a file outside of persistent directory"; return false; } return true; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool IsValidSymbolicLink(const FilePath& file_path,
170,866
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: mux_session_confirm(int id, int success, void *arg) { struct mux_session_confirm_ctx *cctx = arg; const char *display; Channel *c, *cc; int i; Buffer reply; if (cctx == NULL) fatal("%s: cctx == NULL", __func__); if ((c = channel_by_id(id)) == NULL) fatal("%s: no channel for id %d", __func__, id); if ((cc = channel_by_id(c->ctl_chan)) == NULL) fatal("%s: channel %d lacks control channel %d", __func__, id, c->ctl_chan); if (!success) { debug3("%s: sending failure reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_FAILURE); buffer_put_int(&reply, cctx->rid); buffer_put_cstring(&reply, "Session open refused by peer"); goto done; } display = getenv("DISPLAY"); if (cctx->want_x_fwd && options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(id, display, proto, data, 1); client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); /* XXX exit_on_forward_failure */ } if (cctx->want_agent_fwd && options.forward_agent) { packet_send(); } client_session2_setup(id, cctx->want_tty, cctx->want_subsys, cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env); debug3("%s: sending success reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_SESSION_OPENED); buffer_put_int(&reply, cctx->rid); buffer_put_int(&reply, c->self); done: /* Send reply */ buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply)); buffer_free(&reply); if (cc->mux_pause <= 0) fatal("%s: mux_pause %d", __func__, cc->mux_pause); cc->mux_pause = 0; /* start processing messages again */ c->open_confirm_ctx = NULL; buffer_free(&cctx->cmd); free(cctx->term); if (cctx->env != NULL) { for (i = 0; cctx->env[i] != NULL; i++) free(cctx->env[i]); free(cctx->env); } free(cctx); } Commit Message: CWE ID: CWE-254
mux_session_confirm(int id, int success, void *arg) { struct mux_session_confirm_ctx *cctx = arg; const char *display; Channel *c, *cc; int i; Buffer reply; if (cctx == NULL) fatal("%s: cctx == NULL", __func__); if ((c = channel_by_id(id)) == NULL) fatal("%s: no channel for id %d", __func__, id); if ((cc = channel_by_id(c->ctl_chan)) == NULL) fatal("%s: channel %d lacks control channel %d", __func__, id, c->ctl_chan); if (!success) { debug3("%s: sending failure reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_FAILURE); buffer_put_int(&reply, cctx->rid); buffer_put_cstring(&reply, "Session open refused by peer"); goto done; } display = getenv("DISPLAY"); if (cctx->want_x_fwd && options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ if (client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data) == 0) { /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(id, display, proto, data, 1); /* XXX exit_on_forward_failure */ client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); } } if (cctx->want_agent_fwd && options.forward_agent) { packet_send(); } client_session2_setup(id, cctx->want_tty, cctx->want_subsys, cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env); debug3("%s: sending success reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_SESSION_OPENED); buffer_put_int(&reply, cctx->rid); buffer_put_int(&reply, c->self); done: /* Send reply */ buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply)); buffer_free(&reply); if (cc->mux_pause <= 0) fatal("%s: mux_pause %d", __func__, cc->mux_pause); cc->mux_pause = 0; /* start processing messages again */ c->open_confirm_ctx = NULL; buffer_free(&cctx->cmd); free(cctx->term); if (cctx->env != NULL) { for (i = 0; cctx->env[i] != NULL; i++) free(cctx->env[i]); free(cctx->env); } free(cctx); }
165,352
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 nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; } Commit Message: avformat/nsvdec: Fix DoS due to lack of eof check in nsvs_file_offset loop. Fixes: 20170829.nsv Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; } if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; }
167,764
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 ResourceDispatcherHostImpl::PauseRequest(int child_id, int request_id, bool pause) { GlobalRequestID global_id(child_id, request_id); PendingRequestList::iterator i = pending_requests_.find(global_id); if (i == pending_requests_.end()) { DVLOG(1) << "Pausing a request that wasn't found"; return; } ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(i->second); int pause_count = info->pause_count() + (pause ? 1 : -1); if (pause_count < 0) { NOTREACHED(); // Unbalanced call to pause. return; } info->set_pause_count(pause_count); VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec(); if (info->pause_count() == 0) { MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), global_id)); } } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ResourceDispatcherHostImpl::PauseRequest(int child_id, int request_id, bool pause) { GlobalRequestID global_id(child_id, request_id); PendingRequestList::iterator i = pending_requests_.find(global_id); if (i == pending_requests_.end()) { DVLOG(1) << "Pausing a request that wasn't found"; return; } ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(i->second); int pause_count = info->pause_count() + (pause ? 1 : -1); if (pause_count < 0) { NOTREACHED(); // Unbalanced call to pause. return; } info->set_pause_count(pause_count); VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec(); if (info->pause_count() == 0) { MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::ResumeRequest, AsWeakPtr(), global_id)); } }
170,990
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 SetManualFallbacks(bool enabled) { std::vector<std::string> features = { password_manager::features::kEnableManualFallbacksFilling.name, password_manager::features::kEnableManualFallbacksFillingStandalone .name, password_manager::features::kEnableManualFallbacksGeneration.name}; if (enabled) { scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","), std::string()); } else { scoped_feature_list_.InitFromCommandLine(std::string(), base::JoinString(features, ",")); } } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <[email protected]> Commit-Queue: NIKHIL SAHNI <[email protected]> Cr-Commit-Position: refs/heads/master@{#534923} CWE ID: CWE-264
void SetManualFallbacks(bool enabled) { std::vector<std::string> features = { password_manager::features::kManualFallbacksFilling.name, password_manager::features::kEnableManualFallbacksFillingStandalone .name, password_manager::features::kEnableManualFallbacksGeneration.name}; if (enabled) { scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","), std::string()); } else { scoped_feature_list_.InitFromCommandLine(std::string(), base::JoinString(features, ",")); } }
171,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: PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion()
165,058
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 char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; } Commit Message: base64: Rework base64decode to handle split encoded data correctly CWE ID: CWE-125
unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; int wv, w1, w2, w3, w4; int tmpval[4]; int tmpcnt = 0; do { while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) { ptr++; } if (*ptr == '\0' || ptr >= buf+len) { break; } if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) { continue; } tmpval[tmpcnt++] = wv; if (tmpcnt == 4) { tmpcnt = 0; w1 = tmpval[0]; w2 = tmpval[1]; w3 = tmpval[2]; w4 = tmpval[3]; if (w2 >= 0) { outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF); } if (w3 >= 0) { outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF); } if (w4 >= 0) { outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF); } } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
168,416
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: EBMLHeader::EBMLHeader() : m_docType(NULL) { Init(); } 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
EBMLHeader::EBMLHeader() :
174,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, "%s", _( "bad frame size" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); } Commit Message: fetch map after DGifGetImageDesc() Earlier refactoring broke GIF map fetch. CWE ID:
vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, "%s", _( "bad frame size" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); }
169,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btsock_thread_exit(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created"); return FALSE; } sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0}; if(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd)) { pthread_join(ts[h].thread_id, 0); pthread_mutex_lock(&thread_slot_lock); free_thread_slot(h); pthread_mutex_unlock(&thread_slot_lock); return TRUE; } return FALSE; } 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
int btsock_thread_exit(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created"); return FALSE; } sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0}; if(TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd)) { pthread_join(ts[h].thread_id, 0); pthread_mutex_lock(&thread_slot_lock); free_thread_slot(h); pthread_mutex_unlock(&thread_slot_lock); return TRUE; } return FALSE; }
173,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type, png_byte bit_depth, png_uint_32 x, store_palette palette) { PNG_CONST png_byte sample_depth = (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth); PNG_CONST unsigned int max = (1U<<sample_depth)-1; /* Initially just set everything to the same number and the alpha to opaque. * Note that this currently assumes a simple palette where entry x has colour * rgb(x,x,x)! */ this->palette_index = this->red = this->green = this->blue = sample(row, colour_type, bit_depth, x, 0); this->alpha = max; this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT = sample_depth; /* Then override as appropriate: */ if (colour_type == 3) /* palette */ { /* This permits the caller to default to the sample value. */ if (palette != 0) { PNG_CONST unsigned int i = this->palette_index; this->red = palette[i].red; this->green = palette[i].green; this->blue = palette[i].blue; this->alpha = palette[i].alpha; } } else /* not palette */ { unsigned int i = 0; if (colour_type & 2) { this->green = sample(row, colour_type, bit_depth, x, 1); this->blue = sample(row, colour_type, bit_depth, x, 2); i = 2; } if (colour_type & 4) this->alpha = sample(row, colour_type, bit_depth, x, ++i); } /* Calculate the scaled values, these are simply the values divided by * 'max' and the error is initialized to the double precision epsilon value * from the header file. */ image_pixel_setf(this, max); /* Store the input information for use in the transforms - these will * modify the information. */ this->colour_type = colour_type; this->bit_depth = bit_depth; this->sample_depth = sample_depth; this->have_tRNS = 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type, png_byte bit_depth, png_uint_32 x, store_palette palette, const image_pixel *format /*from pngvalid transform of input*/) { const png_byte sample_depth = (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth); const unsigned int max = (1U<<sample_depth)-1; const int swap16 = (format != 0 && format->swap16); const int littleendian = (format != 0 && format->littleendian); const int sig_bits = (format != 0 && format->sig_bits); /* Initially just set everything to the same number and the alpha to opaque. * Note that this currently assumes a simple palette where entry x has colour * rgb(x,x,x)! */ this->palette_index = this->red = this->green = this->blue = sample(row, colour_type, bit_depth, x, 0, swap16, littleendian); this->alpha = max; this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT = sample_depth; /* Then override as appropriate: */ if (colour_type == 3) /* palette */ { /* This permits the caller to default to the sample value. */ if (palette != 0) { const unsigned int i = this->palette_index; this->red = palette[i].red; this->green = palette[i].green; this->blue = palette[i].blue; this->alpha = palette[i].alpha; } } else /* not palette */ { unsigned int i = 0; if ((colour_type & 4) != 0 && format != 0 && format->alpha_first) { this->alpha = this->red; /* This handles the gray case for 'AG' pixels */ this->palette_index = this->red = this->green = this->blue = sample(row, colour_type, bit_depth, x, 1, swap16, littleendian); i = 1; } if (colour_type & 2) { /* Green is second for both BGR and RGB: */ this->green = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); if (format != 0 && format->swap_rgb) /* BGR */ this->red = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); else this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); } else /* grayscale */ if (format != 0 && format->mono_inverted) this->red = this->green = this->blue = this->red ^ max; if ((colour_type & 4) != 0) /* alpha */ { if (format == 0 || !format->alpha_first) this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16, littleendian); if (format != 0 && format->alpha_inverted) this->alpha ^= max; } } /* Calculate the scaled values, these are simply the values divided by * 'max' and the error is initialized to the double precision epsilon value * from the header file. */ image_pixel_setf(this, sig_bits ? (1U << format->red_sBIT)-1 : max, sig_bits ? (1U << format->green_sBIT)-1 : max, sig_bits ? (1U << format->blue_sBIT)-1 : max, sig_bits ? (1U << format->alpha_sBIT)-1 : max); /* Store the input information for use in the transforms - these will * modify the information. */ this->colour_type = colour_type; this->bit_depth = bit_depth; this->sample_depth = sample_depth; this->have_tRNS = 0; this->swap_rgb = 0; this->alpha_first = 0; this->alpha_inverted = 0; this->mono_inverted = 0; this->swap16 = 0; this->littleendian = 0; this->sig_bits = 0; }
173,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: static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) { AcpiPciHpState *s = opaque; uint32_t val = 0; int bsel = s->hotplug_select; if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) { return 0; } switch (addr) { case PCI_UP_BASE: val = s->acpi_pcihp_pci_status[bsel].up; if (!s->legacy_piix) { s->acpi_pcihp_pci_status[bsel].up = 0; } ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); break; case PCI_DOWN_BASE: val = s->acpi_pcihp_pci_status[bsel].down; ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); break; case PCI_EJ_BASE: /* No feature defined yet */ ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); break; case PCI_RMV_BASE: val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); break; case PCI_SEL_BASE: val = s->hotplug_select; ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); default: break; } return val; } Commit Message: CWE ID: CWE-119
static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) { AcpiPciHpState *s = opaque; uint32_t val = 0; int bsel = s->hotplug_select; if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { return 0; } switch (addr) { case PCI_UP_BASE: val = s->acpi_pcihp_pci_status[bsel].up; if (!s->legacy_piix) { s->acpi_pcihp_pci_status[bsel].up = 0; } ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); break; case PCI_DOWN_BASE: val = s->acpi_pcihp_pci_status[bsel].down; ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); break; case PCI_EJ_BASE: /* No feature defined yet */ ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); break; case PCI_RMV_BASE: val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); break; case PCI_SEL_BASE: val = s->hotplug_select; ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); default: break; } return val; }
165,019
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_put_super(struct super_block *sb) { mb_cache_shrink(sb->s_bdev); } 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_put_super(struct super_block *sb)
169,995
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController* ExtensionTtsController::GetInstance() { return Singleton<ExtensionTtsController>::get(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController* ExtensionTtsController::GetInstance() {
170,379
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: bqarr_in(PG_FUNCTION_ARGS) { char *buf = (char *) PG_GETARG_POINTER(0); WORKSTATE state; int32 i; QUERYTYPE *query; int32 commonlen; ITEM *ptr; NODE *tmp; int32 pos = 0; #ifdef BS_DEBUG StringInfoData pbuf; #endif state.buf = buf; state.state = WAITOPERAND; state.count = 0; state.num = 0; state.str = NULL; /* make polish notation (postfix, but in reverse order) */ makepol(&state); if (!state.num) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("empty query"))); commonlen = COMPUTESIZE(state.num); query = (QUERYTYPE *) palloc(commonlen); SET_VARSIZE(query, commonlen); query->size = state.num; ptr = GETQUERY(query); for (i = state.num - 1; i >= 0; i--) { ptr[i].type = state.str->type; ptr[i].val = state.str->val; tmp = state.str->next; pfree(state.str); state.str = tmp; } pos = query->size - 1; findoprnd(ptr, &pos); #ifdef BS_DEBUG initStringInfo(&pbuf); for (i = 0; i < query->size; i++) { if (ptr[i].type == OPR) appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left); else appendStringInfo(&pbuf, "%d ", ptr[i].val); } elog(DEBUG3, "POR: %s", pbuf.data); pfree(pbuf.data); #endif PG_RETURN_POINTER(query); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
bqarr_in(PG_FUNCTION_ARGS) { char *buf = (char *) PG_GETARG_POINTER(0); WORKSTATE state; int32 i; QUERYTYPE *query; int32 commonlen; ITEM *ptr; NODE *tmp; int32 pos = 0; #ifdef BS_DEBUG StringInfoData pbuf; #endif state.buf = buf; state.state = WAITOPERAND; state.count = 0; state.num = 0; state.str = NULL; /* make polish notation (postfix, but in reverse order) */ makepol(&state); if (!state.num) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("empty query"))); if (state.num > QUERYTYPEMAXITEMS) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("number of query items (%d) exceeds the maximum allowed (%d)", state.num, (int) QUERYTYPEMAXITEMS))); commonlen = COMPUTESIZE(state.num); query = (QUERYTYPE *) palloc(commonlen); SET_VARSIZE(query, commonlen); query->size = state.num; ptr = GETQUERY(query); for (i = state.num - 1; i >= 0; i--) { ptr[i].type = state.str->type; ptr[i].val = state.str->val; tmp = state.str->next; pfree(state.str); state.str = tmp; } pos = query->size - 1; findoprnd(ptr, &pos); #ifdef BS_DEBUG initStringInfo(&pbuf); for (i = 0; i < query->size; i++) { if (ptr[i].type == OPR) appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left); else appendStringInfo(&pbuf, "%d ", ptr[i].val); } elog(DEBUG3, "POR: %s", pbuf.data); pfree(pbuf.data); #endif PG_RETURN_POINTER(query); }
166,402
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_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = "\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i<r_size(permitlist); i++) { ref permitstring; const string_match_params win_filename_params = { '*', '?', '\\', true, true /* ignore case & '/' == '\\' */ }; const byte *permstr; uint permlen; int cwd_len = 0; if (array_get(imemory, permitlist, i, &permitstring) < 0 || r_type(&permitstring) != t_string ) break; /* any problem, just fail */ permstr = permitstring.value.bytes; permlen = r_size(&permitstring); /* * Check if any file name is permitted with "*". */ if (permlen == 1 && permstr[0] == '*') return 0; /* success */ /* * If the filename starts with parent references, * the permission element must start with same number of parent references. */ if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen)) continue; cwd_len = gp_file_name_cwds((const char *)permstr, permlen); /* * If the permission starts with "./", absolute paths * are not permitted. */ if (cwd_len > 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with "./", relative paths * with no "./" are allowed as well as with "./". * 'fname' has no "./" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; } Commit Message: CWE ID:
check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = "\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev && iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i<r_size(permitlist); i++) { ref permitstring; const string_match_params win_filename_params = { '*', '?', '\\', true, true /* ignore case & '/' == '\\' */ }; const byte *permstr; uint permlen; int cwd_len = 0; if (array_get(imemory, permitlist, i, &permitstring) < 0 || r_type(&permitstring) != t_string ) break; /* any problem, just fail */ permstr = permitstring.value.bytes; permlen = r_size(&permitstring); /* * Check if any file name is permitted with "*". */ if (permlen == 1 && permstr[0] == '*') return 0; /* success */ /* * If the filename starts with parent references, * the permission element must start with same number of parent references. */ if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen)) continue; cwd_len = gp_file_name_cwds((const char *)permstr, permlen); /* * If the permission starts with "./", absolute paths * are not permitted. */ if (cwd_len > 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with "./", relative paths * with no "./" are allowed as well as with "./". * 'fname' has no "./" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; }
164,708
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: perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if (palette_number == 0) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! * * CHANGED: now test two palettes and, as a side effect, images with and * without tRNS. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_threshold, pm->test_tRNS)) if (palette_number < 2) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } }
173,682
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 ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() { return GetBooleanParam( switches::kEnableContextualSearchNowOnTapBarIntegration, &is_now_on_tap_bar_integration_enabled_cached_, &is_now_on_tap_bar_integration_enabled_); } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() { bool ContextualSearchFieldTrial::IsContextualCardsBarIntegrationEnabled() { return GetBooleanParam( switches::kEnableContextualSearchContextualCardsBarIntegration, &is_contextual_cards_bar_integration_enabled_cached_, &is_contextual_cards_bar_integration_enabled_); }
171,644
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 MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26861 CWE ID: CWE-399
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
170,122
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 ff_h263_decode_picture_header(MpegEncContext *s) { int format, width, height, i; uint32_t startcode; align_get_bits(&s->gb); startcode= get_bits(&s->gb, 22-8); for(i= get_bits_left(&s->gb); i>24; i-=8) { startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF; if(startcode == 0x20) break; } if (startcode != 0x20) { av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n"); return -1; } /* temporal reference */ i = get_bits(&s->gb, 8); /* picture timestamp */ if( (s->picture_number&~0xFF)+i < s->picture_number) i+= 256; s->picture_number= (s->picture_number&~0xFF) + i; /* PTYPE starts here */ if (get_bits1(&s->gb) != 1) { /* marker */ av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n"); return -1; } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n"); return -1; /* h263 id */ } skip_bits1(&s->gb); /* split screen off */ skip_bits1(&s->gb); /* camera off */ skip_bits1(&s->gb); /* freeze picture release off */ format = get_bits(&s->gb, 3); /* 0 forbidden 1 sub-QCIF 10 QCIF 7 extended PTYPE (PLUSPTYPE) */ if (format != 7 && format != 6) { s->h263_plus = 0; /* H.263v1 */ /* H.263v1 */ width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; if (!width) return -1; s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb); s->h263_long_vectors = get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n"); return -1; /* SAC: off */ } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->unrestricted_mv = s->h263_long_vectors || s->obmc; s->pb_frame = get_bits1(&s->gb); s->chroma_qscale= s->qscale = get_bits(&s->gb, 5); skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */ s->width = width; s->height = height; s->avctx->sample_aspect_ratio= (AVRational){12,11}; s->avctx->framerate = (AVRational){ 30000, 1001 }; } else { int ufep; /* H.263v2 */ s->h263_plus = 1; ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */ /* ufep other than 0 and 1 are reserved */ if (ufep == 1) { /* OPPTYPE */ format = get_bits(&s->gb, 3); ff_dlog(s->avctx, "ufep=1, format: %d\n", format); s->custom_pcf= get_bits1(&s->gb); s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n"); } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */ s->loop_filter= get_bits1(&s->gb); s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter; s->h263_slice_structured= get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n"); } s->alt_inter_vlc= get_bits1(&s->gb); s->modified_quant= get_bits1(&s->gb); if(s->modified_quant) s->chroma_qscale_table= ff_h263_chroma_qscale_table; skip_bits(&s->gb, 1); /* Prevent start code emulation */ skip_bits(&s->gb, 3); /* Reserved */ } else if (ufep != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep); return -1; } /* MPPTYPE */ s->pict_type = get_bits(&s->gb, 3); switch(s->pict_type){ case 0: s->pict_type= AV_PICTURE_TYPE_I;break; case 1: s->pict_type= AV_PICTURE_TYPE_P;break; case 2: s->pict_type= AV_PICTURE_TYPE_P;s->pb_frame = 3;break; case 3: s->pict_type= AV_PICTURE_TYPE_B;break; case 7: s->pict_type= AV_PICTURE_TYPE_I;break; //ZYGO default: return -1; } skip_bits(&s->gb, 2); s->no_rounding = get_bits1(&s->gb); skip_bits(&s->gb, 4); /* Get the picture dimensions */ if (ufep) { if (format == 6) { /* Custom Picture Format (CPFMT) */ s->aspect_ratio_info = get_bits(&s->gb, 4); ff_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info); /* aspect ratios: 0 - forbidden 1 - 1:1 2 - 12:11 (CIF 4:3) 3 - 10:11 (525-type 4:3) 4 - 16:11 (CIF 16:9) 5 - 40:33 (525-type 16:9) 6-14 - reserved */ width = (get_bits(&s->gb, 9) + 1) * 4; skip_bits1(&s->gb); height = get_bits(&s->gb, 9) * 4; ff_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { /* aspected dimensions */ s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8); s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8); }else{ s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info]; } } else { width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; s->avctx->sample_aspect_ratio= (AVRational){12,11}; } if ((width == 0) || (height == 0)) return -1; s->width = width; s->height = height; if(s->custom_pcf){ int gcd; s->avctx->framerate.num = 1800000; s->avctx->framerate.den = 1000 + get_bits1(&s->gb); s->avctx->framerate.den *= get_bits(&s->gb, 7); if(s->avctx->framerate.den == 0){ av_log(s, AV_LOG_ERROR, "zero framerate\n"); return -1; } gcd= av_gcd(s->avctx->framerate.den, s->avctx->framerate.num); s->avctx->framerate.den /= gcd; s->avctx->framerate.num /= gcd; }else{ s->avctx->framerate = (AVRational){ 30000, 1001 }; } } if(s->custom_pcf){ skip_bits(&s->gb, 2); //extended Temporal reference } if (ufep) { if (s->umvplus) { if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */ skip_bits1(&s->gb); } if(s->h263_slice_structured){ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n"); } } } s->qscale = get_bits(&s->gb, 5); } s->mb_width = (s->width + 15) / 16; s->mb_height = (s->height + 15) / 16; s->mb_num = s->mb_width * s->mb_height; skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */ if (s->custom_pcf) skip_bits(&s->gb, 2); //extended Temporal reference skip_bits(&s->gb, 2); /* Quantization information for B-pictures */ } Commit Message: CWE ID: CWE-189
int ff_h263_decode_picture_header(MpegEncContext *s) { int format, width, height, i, ret; uint32_t startcode; align_get_bits(&s->gb); startcode= get_bits(&s->gb, 22-8); for(i= get_bits_left(&s->gb); i>24; i-=8) { startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF; if(startcode == 0x20) break; } if (startcode != 0x20) { av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n"); return -1; } /* temporal reference */ i = get_bits(&s->gb, 8); /* picture timestamp */ if( (s->picture_number&~0xFF)+i < s->picture_number) i+= 256; s->picture_number= (s->picture_number&~0xFF) + i; /* PTYPE starts here */ if (get_bits1(&s->gb) != 1) { /* marker */ av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n"); return -1; } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n"); return -1; /* h263 id */ } skip_bits1(&s->gb); /* split screen off */ skip_bits1(&s->gb); /* camera off */ skip_bits1(&s->gb); /* freeze picture release off */ format = get_bits(&s->gb, 3); /* 0 forbidden 1 sub-QCIF 10 QCIF 7 extended PTYPE (PLUSPTYPE) */ if (format != 7 && format != 6) { s->h263_plus = 0; /* H.263v1 */ /* H.263v1 */ width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb); s->h263_long_vectors = get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n"); return -1; /* SAC: off */ } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->unrestricted_mv = s->h263_long_vectors || s->obmc; s->pb_frame = get_bits1(&s->gb); s->chroma_qscale= s->qscale = get_bits(&s->gb, 5); skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */ s->width = width; s->height = height; s->avctx->sample_aspect_ratio= (AVRational){12,11}; s->avctx->framerate = (AVRational){ 30000, 1001 }; } else { int ufep; /* H.263v2 */ s->h263_plus = 1; ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */ /* ufep other than 0 and 1 are reserved */ if (ufep == 1) { /* OPPTYPE */ format = get_bits(&s->gb, 3); ff_dlog(s->avctx, "ufep=1, format: %d\n", format); s->custom_pcf= get_bits1(&s->gb); s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n"); } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */ s->loop_filter= get_bits1(&s->gb); s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter; s->h263_slice_structured= get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n"); } s->alt_inter_vlc= get_bits1(&s->gb); s->modified_quant= get_bits1(&s->gb); if(s->modified_quant) s->chroma_qscale_table= ff_h263_chroma_qscale_table; skip_bits(&s->gb, 1); /* Prevent start code emulation */ skip_bits(&s->gb, 3); /* Reserved */ } else if (ufep != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep); return -1; } /* MPPTYPE */ s->pict_type = get_bits(&s->gb, 3); switch(s->pict_type){ case 0: s->pict_type= AV_PICTURE_TYPE_I;break; case 1: s->pict_type= AV_PICTURE_TYPE_P;break; case 2: s->pict_type= AV_PICTURE_TYPE_P;s->pb_frame = 3;break; case 3: s->pict_type= AV_PICTURE_TYPE_B;break; case 7: s->pict_type= AV_PICTURE_TYPE_I;break; //ZYGO default: return -1; } skip_bits(&s->gb, 2); s->no_rounding = get_bits1(&s->gb); skip_bits(&s->gb, 4); /* Get the picture dimensions */ if (ufep) { if (format == 6) { /* Custom Picture Format (CPFMT) */ s->aspect_ratio_info = get_bits(&s->gb, 4); ff_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info); /* aspect ratios: 0 - forbidden 1 - 1:1 2 - 12:11 (CIF 4:3) 3 - 10:11 (525-type 4:3) 4 - 16:11 (CIF 16:9) 5 - 40:33 (525-type 16:9) 6-14 - reserved */ width = (get_bits(&s->gb, 9) + 1) * 4; skip_bits1(&s->gb); height = get_bits(&s->gb, 9) * 4; ff_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { /* aspected dimensions */ s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8); s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8); }else{ s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info]; } } else { width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; s->avctx->sample_aspect_ratio= (AVRational){12,11}; } if ((width == 0) || (height == 0)) return -1; s->width = width; s->height = height; if(s->custom_pcf){ int gcd; s->avctx->framerate.num = 1800000; s->avctx->framerate.den = 1000 + get_bits1(&s->gb); s->avctx->framerate.den *= get_bits(&s->gb, 7); if(s->avctx->framerate.den == 0){ av_log(s, AV_LOG_ERROR, "zero framerate\n"); return -1; } gcd= av_gcd(s->avctx->framerate.den, s->avctx->framerate.num); s->avctx->framerate.den /= gcd; s->avctx->framerate.num /= gcd; }else{ s->avctx->framerate = (AVRational){ 30000, 1001 }; } } if(s->custom_pcf){ skip_bits(&s->gb, 2); //extended Temporal reference } if (ufep) { if (s->umvplus) { if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */ skip_bits1(&s->gb); } if(s->h263_slice_structured){ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n"); } } } s->qscale = get_bits(&s->gb, 5); } if ((ret = av_image_check_size(s->width, s->height, 0, s)) < 0) return ret; s->mb_width = (s->width + 15) / 16; s->mb_height = (s->height + 15) / 16; s->mb_num = s->mb_width * s->mb_height; skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */ if (s->custom_pcf) skip_bits(&s->gb, 2); //extended Temporal reference skip_bits(&s->gb, 2); /* Quantization information for B-pictures */ }
165,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_slice(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_slice_vertical_position; UWORD32 u4_slice_vertical_position_extension; IMPEG2D_ERROR_CODES_T e_error; ps_stream = &ps_dec->s_bit_stream; /*------------------------------------------------------------------------*/ /* All the profiles supported require restricted slice structure. Hence */ /* there is no need to store slice_vertical_position. Note that max */ /* height supported does not exceed 2800 and scalablity is not supported */ /*------------------------------------------------------------------------*/ /* Remove the slice start code */ impeg2d_bit_stream_flush(ps_stream,START_CODE_PREFIX_LEN); u4_slice_vertical_position = impeg2d_bit_stream_get(ps_stream, 8); if(u4_slice_vertical_position > 2800) { u4_slice_vertical_position_extension = impeg2d_bit_stream_get(ps_stream, 3); u4_slice_vertical_position += (u4_slice_vertical_position_extension << 7); } if((u4_slice_vertical_position > ps_dec->u2_num_vert_mb) || (u4_slice_vertical_position == 0)) { return IMPEG2D_INVALID_VERT_SIZE; } u4_slice_vertical_position--; if (ps_dec->u2_mb_y != u4_slice_vertical_position) { ps_dec->u2_mb_y = u4_slice_vertical_position; ps_dec->u2_mb_x = 0; } ps_dec->u2_first_mb = 1; /*------------------------------------------------------------------------*/ /* Quant scale code decoding */ /*------------------------------------------------------------------------*/ { UWORD16 u2_quant_scale_code; u2_quant_scale_code = impeg2d_bit_stream_get(ps_stream,5); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); } if (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); /* Flush extra bit information */ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); } } impeg2d_bit_stream_get_bit(ps_stream); /* Reset the DC predictors to reset values given in Table 7.2 at the start*/ /* of slice data */ ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; /*------------------------------------------------------------------------*/ /* dec->DecMBsinSlice() implements the following psuedo code from standard*/ /* do */ /* { */ /* macroblock() */ /* } while (impeg2d_bit_stream_nxt() != '000 0000 0000 0000 0000 0000') */ /*------------------------------------------------------------------------*/ e_error = ps_dec->pf_decode_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } /* Check for the MBy index instead of number of MBs left, because the * number of MBs left in case of multi-thread decode is the number of MBs * in that row only */ if(ps_dec->u2_mb_y < ps_dec->u2_num_vert_mb) impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } 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
IMPEG2D_ERROR_CODES_T impeg2d_dec_slice(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_slice_vertical_position; UWORD32 u4_slice_vertical_position_extension; IMPEG2D_ERROR_CODES_T e_error; ps_stream = &ps_dec->s_bit_stream; /*------------------------------------------------------------------------*/ /* All the profiles supported require restricted slice structure. Hence */ /* there is no need to store slice_vertical_position. Note that max */ /* height supported does not exceed 2800 and scalablity is not supported */ /*------------------------------------------------------------------------*/ /* Remove the slice start code */ impeg2d_bit_stream_flush(ps_stream,START_CODE_PREFIX_LEN); u4_slice_vertical_position = impeg2d_bit_stream_get(ps_stream, 8); if(u4_slice_vertical_position > 2800) { u4_slice_vertical_position_extension = impeg2d_bit_stream_get(ps_stream, 3); u4_slice_vertical_position += (u4_slice_vertical_position_extension << 7); } if((u4_slice_vertical_position > ps_dec->u2_num_vert_mb) || (u4_slice_vertical_position == 0)) { return IMPEG2D_INVALID_VERT_SIZE; } u4_slice_vertical_position--; if (ps_dec->u2_mb_y != u4_slice_vertical_position) { ps_dec->u2_mb_y = u4_slice_vertical_position; ps_dec->u2_mb_x = 0; } ps_dec->u2_first_mb = 1; /*------------------------------------------------------------------------*/ /* Quant scale code decoding */ /*------------------------------------------------------------------------*/ { UWORD16 u2_quant_scale_code; u2_quant_scale_code = impeg2d_bit_stream_get(ps_stream,5); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); } if (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); /* Flush extra bit information */ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_flush(ps_stream,9); } } impeg2d_bit_stream_get_bit(ps_stream); /* Reset the DC predictors to reset values given in Table 7.2 at the start*/ /* of slice data */ ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; /*------------------------------------------------------------------------*/ /* dec->DecMBsinSlice() implements the following psuedo code from standard*/ /* do */ /* { */ /* macroblock() */ /* } while (impeg2d_bit_stream_nxt() != '000 0000 0000 0000 0000 0000') */ /*------------------------------------------------------------------------*/ e_error = ps_dec->pf_decode_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } /* Check for the MBy index instead of number of MBs left, because the * number of MBs left in case of multi-thread decode is the number of MBs * in that row only */ if(ps_dec->u2_mb_y < ps_dec->u2_num_vert_mb) impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
173,947
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 ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) frame_->Close(); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 [email protected] Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { DCHECK(!is_frameless_); if (sender == close_button_) frame_->Close(); }
170,709
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 MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { LOG(INFO) << "IBus connection is ready."; } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { VLOG(1) << "IBus connection is ready."; } }
170,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: void cipso_v4_sock_delattr(struct sock *sk) { int hdr_delta; struct ip_options *opt; struct inet_sock *sk_inet; sk_inet = inet_sk(sk); opt = sk_inet->opt; if (opt == NULL || opt->cipso == 0) return; hdr_delta = cipso_v4_delopt(&sk_inet->opt); if (sk_inet->is_icsk && hdr_delta > 0) { struct inet_connection_sock *sk_conn = inet_csk(sk); sk_conn->icsk_ext_hdr_len -= hdr_delta; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
void cipso_v4_sock_delattr(struct sock *sk) { int hdr_delta; struct ip_options_rcu *opt; struct inet_sock *sk_inet; sk_inet = inet_sk(sk); opt = rcu_dereference_protected(sk_inet->inet_opt, 1); if (opt == NULL || opt->opt.cipso == 0) return; hdr_delta = cipso_v4_delopt(&sk_inet->inet_opt); if (sk_inet->is_icsk && hdr_delta > 0) { struct inet_connection_sock *sk_conn = inet_csk(sk); sk_conn->icsk_ext_hdr_len -= hdr_delta; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } }
165,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::GetLast() const { if ((m_clusters == NULL) || (m_clusterCount <= 0)) return &m_eos; const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Cluster* Segment::GetLast() const const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; }
174,340
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 DataReductionProxyConfig::SecureProxyCheck( SecureProxyCheckerCallback fetcher_callback) { secure_proxy_checker_->CheckIfSecureProxyIsAllowed(fetcher_callback); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void DataReductionProxyConfig::SecureProxyCheck( SecureProxyCheckerCallback fetcher_callback) { if (params::IsIncludedInHoldbackFieldTrial()) return; secure_proxy_checker_->CheckIfSecureProxyIsAllowed(fetcher_callback); }
172,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: sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data) { SF_PRIVATE *psf ; /* Make sure we have a valid set ot virtual pointers. */ if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf->virtual_io = SF_TRUE ; psf->vio = *sfvirtual ; psf->vio_user_data = user_data ; psf->file.mode = mode ; return psf_open_file (psf, sfinfo) ; } /* sf_open_virtual */ 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
sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data) { SF_PRIVATE *psf ; /* Make sure we have a valid set ot virtual pointers. */ if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((psf = psf_allocate ()) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf->virtual_io = SF_TRUE ; psf->vio = *sfvirtual ; psf->vio_user_data = user_data ; psf->file.mode = mode ; return psf_open_file (psf, sfinfo) ; } /* sf_open_virtual */
170,069
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 install_user_keyrings(void) { struct user_struct *user; const struct cred *cred; struct key *uid_keyring, *session_keyring; key_perm_t user_keyring_perm; char buf[20]; int ret; uid_t uid; user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL; cred = current_cred(); user = cred->user; uid = from_kuid(cred->user_ns, user->uid); kenter("%p{%u}", user, uid); if (user->uid_keyring) { kleave(" = 0 [exist]"); return 0; } mutex_lock(&key_user_keyring_mutex); ret = 0; if (!user->uid_keyring) { /* get the UID-specific keyring * - there may be one in existence already as it may have been * pinned by a session, but the user_struct pointing to it * may have been destroyed by setuid */ sprintf(buf, "_uid.%u", uid); uid_keyring = find_keyring_by_name(buf, true); if (IS_ERR(uid_keyring)) { uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL); if (IS_ERR(uid_keyring)) { ret = PTR_ERR(uid_keyring); goto error; } } /* get a default session keyring (which might also exist * already) */ sprintf(buf, "_uid_ses.%u", uid); session_keyring = find_keyring_by_name(buf, true); if (IS_ERR(session_keyring)) { session_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL); if (IS_ERR(session_keyring)) { ret = PTR_ERR(session_keyring); goto error_release; } /* we install a link from the user session keyring to * the user keyring */ ret = key_link(session_keyring, uid_keyring); if (ret < 0) goto error_release_both; } /* install the keyrings */ user->uid_keyring = uid_keyring; user->session_keyring = session_keyring; } mutex_unlock(&key_user_keyring_mutex); kleave(" = 0"); return 0; error_release_both: key_put(session_keyring); error_release: key_put(uid_keyring); error: mutex_unlock(&key_user_keyring_mutex); kleave(" = %d", ret); return ret; } Commit Message: keys: fix race with concurrent install_user_keyrings() This fixes CVE-2013-1792. There is a race in install_user_keyrings() that can cause a NULL pointer dereference when called concurrently for the same user if the uid and uid-session keyrings are not yet created. It might be possible for an unprivileged user to trigger this by calling keyctl() from userspace in parallel immediately after logging in. Assume that we have two threads both executing lookup_user_key(), both looking for KEY_SPEC_USER_SESSION_KEYRING. THREAD A THREAD B =============================== =============================== ==>call install_user_keyrings(); if (!cred->user->session_keyring) ==>call install_user_keyrings() ... user->uid_keyring = uid_keyring; if (user->uid_keyring) return 0; <== key = cred->user->session_keyring [== NULL] user->session_keyring = session_keyring; atomic_inc(&key->usage); [oops] At the point thread A dereferences cred->user->session_keyring, thread B hasn't updated user->session_keyring yet, but thread A assumes it is populated because install_user_keyrings() returned ok. The race window is really small but can be exploited if, for example, thread B is interrupted or preempted after initializing uid_keyring, but before doing setting session_keyring. This couldn't be reproduced on a stock kernel. However, after placing systemtap probe on 'user->session_keyring = session_keyring;' that introduced some delay, the kernel could be crashed reliably. Fix this by checking both pointers before deciding whether to return. Alternatively, the test could be done away with entirely as it is checked inside the mutex - but since the mutex is global, that may not be the best way. Signed-off-by: David Howells <[email protected]> Reported-by: Mateusz Guzik <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-362
int install_user_keyrings(void) { struct user_struct *user; const struct cred *cred; struct key *uid_keyring, *session_keyring; key_perm_t user_keyring_perm; char buf[20]; int ret; uid_t uid; user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL; cred = current_cred(); user = cred->user; uid = from_kuid(cred->user_ns, user->uid); kenter("%p{%u}", user, uid); if (user->uid_keyring && user->session_keyring) { kleave(" = 0 [exist]"); return 0; } mutex_lock(&key_user_keyring_mutex); ret = 0; if (!user->uid_keyring) { /* get the UID-specific keyring * - there may be one in existence already as it may have been * pinned by a session, but the user_struct pointing to it * may have been destroyed by setuid */ sprintf(buf, "_uid.%u", uid); uid_keyring = find_keyring_by_name(buf, true); if (IS_ERR(uid_keyring)) { uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL); if (IS_ERR(uid_keyring)) { ret = PTR_ERR(uid_keyring); goto error; } } /* get a default session keyring (which might also exist * already) */ sprintf(buf, "_uid_ses.%u", uid); session_keyring = find_keyring_by_name(buf, true); if (IS_ERR(session_keyring)) { session_keyring = keyring_alloc(buf, user->uid, INVALID_GID, cred, user_keyring_perm, KEY_ALLOC_IN_QUOTA, NULL); if (IS_ERR(session_keyring)) { ret = PTR_ERR(session_keyring); goto error_release; } /* we install a link from the user session keyring to * the user keyring */ ret = key_link(session_keyring, uid_keyring); if (ret < 0) goto error_release_both; } /* install the keyrings */ user->uid_keyring = uid_keyring; user->session_keyring = session_keyring; } mutex_unlock(&key_user_keyring_mutex); kleave(" = 0"); return 0; error_release_both: key_put(session_keyring); error_release: key_put(uid_keyring); error: mutex_unlock(&key_user_keyring_mutex); kleave(" = %d", ret); return ret; }
166,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *unix_create1(struct net *net, struct socket *sock, int kern) { struct sock *sk = NULL; struct unix_sock *u; atomic_long_inc(&unix_nr_socks); if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) goto out; sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); lockdep_set_class(&sk->sk_receive_queue.lock, &af_unix_sk_receive_queue_lock_key); sk->sk_write_space = unix_write_space; sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen; sk->sk_destruct = unix_sock_destructor; u = unix_sk(sk); u->path.dentry = NULL; u->path.mnt = NULL; spin_lock_init(&u->lock); atomic_long_set(&u->inflight, 0); INIT_LIST_HEAD(&u->link); mutex_init(&u->readlock); /* single task reading lock */ init_waitqueue_head(&u->peer_wait); unix_insert_socket(unix_sockets_unbound(sk), sk); out: if (sk == NULL) atomic_long_dec(&unix_nr_socks); else { local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); } return sk; } Commit Message: unix: avoid use-after-free in ep_remove_wait_queue Rainer Weikusat <[email protected]> writes: An AF_UNIX datagram socket being the client in an n:1 association with some server socket is only allowed to send messages to the server if the receive queue of this socket contains at most sk_max_ack_backlog datagrams. This implies that prospective writers might be forced to go to sleep despite none of the message presently enqueued on the server receive queue were sent by them. In order to ensure that these will be woken up once space becomes again available, the present unix_dgram_poll routine does a second sock_poll_wait call with the peer_wait wait queue of the server socket as queue argument (unix_dgram_recvmsg does a wake up on this queue after a datagram was received). This is inherently problematic because the server socket is only guaranteed to remain alive for as long as the client still holds a reference to it. In case the connection is dissolved via connect or by the dead peer detection logic in unix_dgram_sendmsg, the server socket may be freed despite "the polling mechanism" (in particular, epoll) still has a pointer to the corresponding peer_wait queue. There's no way to forcibly deregister a wait queue with epoll. Based on an idea by Jason Baron, the patch below changes the code such that a wait_queue_t belonging to the client socket is enqueued on the peer_wait queue of the server whenever the peer receive queue full condition is detected by either a sendmsg or a poll. A wake up on the peer queue is then relayed to the ordinary wait queue of the client socket via wake function. The connection to the peer wait queue is again dissolved if either a wake up is about to be relayed or the client socket reconnects or a dead peer is detected or the client socket is itself closed. This enables removing the second sock_poll_wait from unix_dgram_poll, thus avoiding the use-after-free, while still ensuring that no blocked writer sleeps forever. Signed-off-by: Rainer Weikusat <[email protected]> Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets") Reviewed-by: Jason Baron <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static struct sock *unix_create1(struct net *net, struct socket *sock, int kern) { struct sock *sk = NULL; struct unix_sock *u; atomic_long_inc(&unix_nr_socks); if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) goto out; sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); lockdep_set_class(&sk->sk_receive_queue.lock, &af_unix_sk_receive_queue_lock_key); sk->sk_write_space = unix_write_space; sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen; sk->sk_destruct = unix_sock_destructor; u = unix_sk(sk); u->path.dentry = NULL; u->path.mnt = NULL; spin_lock_init(&u->lock); atomic_long_set(&u->inflight, 0); INIT_LIST_HEAD(&u->link); mutex_init(&u->readlock); /* single task reading lock */ init_waitqueue_head(&u->peer_wait); init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay); unix_insert_socket(unix_sockets_unbound(sk), sk); out: if (sk == NULL) atomic_long_dec(&unix_nr_socks); else { local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); } return sk; }
166,833
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* H264SwDecMalloc(u32 size) { return malloc(size); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
void* H264SwDecMalloc(u32 size) { void* H264SwDecMalloc(u32 size, u32 num) { if (size > UINT32_MAX / num) { ALOGE("can't allocate %u * %u bytes", size, num); android_errorWriteLog(0x534e4554, "27855419"); return NULL; } return malloc(size * num); }
173,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: static freelist_idx_t next_random_slot(union freelist_init_state *state) { return (state->list[state->pos++] + state->rand) % state->count; } Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries This patch fixes a bug in the freelist randomization code. When a high random number is used, the freelist will contain duplicate entries. It will result in different allocations sharing the same chunk. It will result in odd behaviours and crashes. It should be uncommon but it depends on the machines. We saw it happening more often on some machines (every few hours of running tests). Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: John Sperbeck <[email protected]> Signed-off-by: Thomas Garnier <[email protected]> Cc: Christoph Lameter <[email protected]> Cc: Pekka Enberg <[email protected]> Cc: David Rientjes <[email protected]> Cc: Joonsoo Kim <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID:
static freelist_idx_t next_random_slot(union freelist_init_state *state) { if (state->pos >= state->count) state->pos = 0; return state->list[state->pos++]; }
168,397
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787
static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } }
166,957
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* H264SwDecMalloc(u32 size) { #if defined(CHECK_MEMORY_USAGE) /* Note that if the decoder has to free and reallocate some of the buffers * the total value will be invalid */ static u32 numBytes = 0; numBytes += size; DEBUG(("Allocated %d bytes, total %d\n", size, numBytes)); #endif return malloc(size); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
void* H264SwDecMalloc(u32 size) void* H264SwDecMalloc(u32 size, u32 num) { if (size > UINT32_MAX / num) { return NULL; } #if defined(CHECK_MEMORY_USAGE) /* Note that if the decoder has to free and reallocate some of the buffers * the total value will be invalid */ static u32 numBytes = 0; numBytes += size * num; DEBUG(("Allocated %d bytes, total %d\n", size, numBytes)); #endif return malloc(size * num); }
173,871
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 RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/148 CWE ID: CWE-787
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { if ((q+PSDQuantum(count)+12) < (datum+length-16)) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); } break; } p+=count; if ((count & 0x01) != 0) p++; } }
168,789
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: base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response(std::move(protocol_versions), it->second.GetBytestring()); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22
base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response( std::move(protocol_versions), base::make_span<kAaguidLength>(it->second.GetBytestring())); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); }
172,275
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 rsRetVal initZMQ(instanceData* pData) { DEFiRet; /* create the context if necessary. */ if (NULL == s_context) { zsys_handler_set(NULL); s_context = zctx_new(); if (s_workerThreads > 0) zctx_set_iothreads(s_context, s_workerThreads); } pData->socket = zsocket_new(s_context, pData->type); if (NULL == pData->socket) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: zsocket_new failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } /* use czmq defaults for these, unless set to non-default values */ if(pData->identity) zsocket_set_identity(pData->socket, (char*)pData->identity); if(pData->sndBuf > -1) zsocket_set_sndbuf(pData->socket, pData->sndBuf); if(pData->rcvBuf > -1) zsocket_set_sndbuf(pData->socket, pData->rcvBuf); if(pData->linger > -1) zsocket_set_linger(pData->socket, pData->linger); if(pData->backlog > -1) zsocket_set_backlog(pData->socket, pData->backlog); if(pData->sndTimeout > -1) zsocket_set_sndtimeo(pData->socket, pData->sndTimeout); if(pData->rcvTimeout > -1) zsocket_set_rcvtimeo(pData->socket, pData->rcvTimeout); if(pData->maxMsgSize > -1) zsocket_set_maxmsgsize(pData->socket, pData->maxMsgSize); if(pData->rate > -1) zsocket_set_rate(pData->socket, pData->rate); if(pData->recoveryIVL > -1) zsocket_set_recovery_ivl(pData->socket, pData->recoveryIVL); if(pData->multicastHops > -1) zsocket_set_multicast_hops(pData->socket, pData->multicastHops); if(pData->reconnectIVL > -1) zsocket_set_reconnect_ivl(pData->socket, pData->reconnectIVL); if(pData->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(pData->socket, pData->reconnectIVLMax); if(pData->ipv4Only > -1) zsocket_set_ipv4only(pData->socket, pData->ipv4Only); if(pData->affinity != 1) zsocket_set_affinity(pData->socket, pData->affinity); if(pData->rcvHWM > -1) zsocket_set_rcvhwm(pData->socket, pData->rcvHWM); if(pData->sndHWM > -1) zsocket_set_sndhwm(pData->socket, pData->sndHWM); /* bind or connect to it */ if (pData->action == ACTION_BIND) { /* bind asserts, so no need to test return val here which isn't the greatest api -- oh well */ if(-1 == zsocket_bind(pData->socket, (char*)pData->description)) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: bind failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } DBGPRINTF("omzmq3: bind to %s successful\n",pData->description); } else { if(-1 == zsocket_connect(pData->socket, (char*)pData->description)) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: connect failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } DBGPRINTF("omzmq3: connect to %s successful", pData->description); } finalize_it: RETiRet; } Commit Message: Merge pull request #1565 from Whissi/fix-format-security-issue-in-zmq-modules Fix format security issue in zmq3 modules CWE ID: CWE-134
static rsRetVal initZMQ(instanceData* pData) { DEFiRet; /* create the context if necessary. */ if (NULL == s_context) { zsys_handler_set(NULL); s_context = zctx_new(); if (s_workerThreads > 0) zctx_set_iothreads(s_context, s_workerThreads); } pData->socket = zsocket_new(s_context, pData->type); if (NULL == pData->socket) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: zsocket_new failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } /* use czmq defaults for these, unless set to non-default values */ if(pData->identity) zsocket_set_identity(pData->socket, (char*)pData->identity); if(pData->sndBuf > -1) zsocket_set_sndbuf(pData->socket, pData->sndBuf); if(pData->rcvBuf > -1) zsocket_set_sndbuf(pData->socket, pData->rcvBuf); if(pData->linger > -1) zsocket_set_linger(pData->socket, pData->linger); if(pData->backlog > -1) zsocket_set_backlog(pData->socket, pData->backlog); if(pData->sndTimeout > -1) zsocket_set_sndtimeo(pData->socket, pData->sndTimeout); if(pData->rcvTimeout > -1) zsocket_set_rcvtimeo(pData->socket, pData->rcvTimeout); if(pData->maxMsgSize > -1) zsocket_set_maxmsgsize(pData->socket, pData->maxMsgSize); if(pData->rate > -1) zsocket_set_rate(pData->socket, pData->rate); if(pData->recoveryIVL > -1) zsocket_set_recovery_ivl(pData->socket, pData->recoveryIVL); if(pData->multicastHops > -1) zsocket_set_multicast_hops(pData->socket, pData->multicastHops); if(pData->reconnectIVL > -1) zsocket_set_reconnect_ivl(pData->socket, pData->reconnectIVL); if(pData->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(pData->socket, pData->reconnectIVLMax); if(pData->ipv4Only > -1) zsocket_set_ipv4only(pData->socket, pData->ipv4Only); if(pData->affinity != 1) zsocket_set_affinity(pData->socket, pData->affinity); if(pData->rcvHWM > -1) zsocket_set_rcvhwm(pData->socket, pData->rcvHWM); if(pData->sndHWM > -1) zsocket_set_sndhwm(pData->socket, pData->sndHWM); /* bind or connect to it */ if (pData->action == ACTION_BIND) { /* bind asserts, so no need to test return val here which isn't the greatest api -- oh well */ if(-1 == zsocket_bind(pData->socket, "%s", (char*)pData->description)) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: bind failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } DBGPRINTF("omzmq3: bind to %s successful\n",pData->description); } else { if(-1 == zsocket_connect(pData->socket, "%s", (char*)pData->description)) { errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: connect failed for %s: %s", pData->description, zmq_strerror(errno)); ABORT_FINALIZE(RS_RET_NO_ERRCODE); } DBGPRINTF("omzmq3: connect to %s successful", pData->description); } finalize_it: RETiRet; }
167,984
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 DeviceTokenFetcher::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DeviceTokenFetcher::StopAutoRetry() { void DeviceTokenFetcher::Reset() { SetState(STATE_INACTIVE); }
170,285
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: v8::Local<v8::Object> V8Console::createCommandLineAPI(InspectedContext* inspectedContext) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate); createBoundFunctionProperty(context, commandLineAPI, "dir", V8Console::dirCallback, "function dir(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "dirxml", V8Console::dirxmlCallback, "function dirxml(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profile", V8Console::profileCallback, "function profile(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, "function profileEnd(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "clear", V8Console::clearCallback, "function clear() { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "table", V8Console::tableCallback, "function table(data, [columns]) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "keys", V8Console::keysCallback, "function keys(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "values", V8Console::valuesCallback, "function values(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "debug", V8Console::debugFunctionCallback, "function debug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, "function undebug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, "function monitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "unmonitor", V8Console::unmonitorFunctionCallback, "function unmonitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "inspect", V8Console::inspectCallback, "function inspect(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "copy", V8Console::copyCallback, "function copy(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "$_", V8Console::lastEvaluationResultCallback); createBoundFunctionProperty(context, commandLineAPI, "$0", V8Console::inspectedObject0); createBoundFunctionProperty(context, commandLineAPI, "$1", V8Console::inspectedObject1); createBoundFunctionProperty(context, commandLineAPI, "$2", V8Console::inspectedObject2); createBoundFunctionProperty(context, commandLineAPI, "$3", V8Console::inspectedObject3); createBoundFunctionProperty(context, commandLineAPI, "$4", V8Console::inspectedObject4); inspectedContext->inspector()->client()->installAdditionalCommandLineAPI(context, commandLineAPI); commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return commandLineAPI; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Object> V8Console::createCommandLineAPI(InspectedContext* inspectedContext) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate); bool success = commandLineAPI->SetPrototype(context, v8::Null(isolate)).FromMaybe(false); DCHECK(success); createBoundFunctionProperty(context, commandLineAPI, "dir", V8Console::dirCallback, "function dir(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "dirxml", V8Console::dirxmlCallback, "function dirxml(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profile", V8Console::profileCallback, "function profile(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, "function profileEnd(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "clear", V8Console::clearCallback, "function clear() { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "table", V8Console::tableCallback, "function table(data, [columns]) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "keys", V8Console::keysCallback, "function keys(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "values", V8Console::valuesCallback, "function values(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "debug", V8Console::debugFunctionCallback, "function debug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, "function undebug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, "function monitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "unmonitor", V8Console::unmonitorFunctionCallback, "function unmonitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "inspect", V8Console::inspectCallback, "function inspect(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "copy", V8Console::copyCallback, "function copy(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "$_", V8Console::lastEvaluationResultCallback); createBoundFunctionProperty(context, commandLineAPI, "$0", V8Console::inspectedObject0); createBoundFunctionProperty(context, commandLineAPI, "$1", V8Console::inspectedObject1); createBoundFunctionProperty(context, commandLineAPI, "$2", V8Console::inspectedObject2); createBoundFunctionProperty(context, commandLineAPI, "$3", V8Console::inspectedObject3); createBoundFunctionProperty(context, commandLineAPI, "$4", V8Console::inspectedObject4); inspectedContext->inspector()->client()->installAdditionalCommandLineAPI(context, commandLineAPI); commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return commandLineAPI; }
172,062
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_process_intra_mb(dec_struct_t * ps_dec, dec_mb_info_t * ps_cur_mb_info, UWORD8 u1_mb_num) { UWORD8 u1_mb_type = ps_cur_mb_info->u1_mb_type; UWORD8 uc_temp = ps_cur_mb_info->u1_mb_ngbr_availablity; UWORD8 u1_top_available = BOOLEAN(uc_temp & TOP_MB_AVAILABLE_MASK); UWORD8 u1_left_available = BOOLEAN(uc_temp & LEFT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_right_mb = BOOLEAN(uc_temp & TOP_RIGHT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_left_mb = BOOLEAN(uc_temp & TOP_LEFT_MB_AVAILABLE_MASK); UWORD8 uc_useTopMB = u1_top_available; UWORD16 u2_use_left_mb = u1_left_available; UWORD16 u2_use_left_mb_pack; UWORD8 *pu1_luma_pred_buffer; /* CHANGED CODE */ UWORD8 *pu1_luma_rec_buffer; UWORD8 *puc_top; mb_neigbour_params_t *ps_left_mb; mb_neigbour_params_t *ps_top_mb; mb_neigbour_params_t *ps_top_right_mb; mb_neigbour_params_t *ps_curmb; UWORD16 u2_mbx = ps_cur_mb_info->u2_mbx; UWORD32 ui_pred_width, ui_rec_width; WORD16 *pi2_y_coeff; UWORD8 u1_mbaff, u1_topmb, u1_mb_field_decoding_flag; UWORD32 u4_num_pmbair; UWORD16 ui2_luma_csbp = ps_cur_mb_info->u2_luma_csbp; UWORD8 *pu1_yleft, *pu1_ytop_left; /* Chroma variables*/ UWORD8 *pu1_top_u; UWORD8 *pu1_uleft; UWORD8 *pu1_u_top_left; /* CHANGED CODE */ UWORD8 *pu1_mb_cb_rei1_buffer, *pu1_mb_cr_rei1_buffer; UWORD32 u4_recwidth_cr; /* CHANGED CODE */ tfr_ctxt_t *ps_frame_buf = ps_dec->ps_frame_buf_ip_recon; UWORD32 u4_luma_dc_only_csbp = 0; UWORD32 u4_luma_dc_only_cbp = 0; UWORD8 *pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; //Pointer to keep track of intra4x4_pred_mode data in pv_proc_tu_coeff_data buffer u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag; u1_topmb = ps_cur_mb_info->u1_topmb; u4_num_pmbair = (u1_mb_num >> u1_mbaff); /*--------------------------------------------------------------------*/ /* Find the current MB's mb params */ /*--------------------------------------------------------------------*/ u1_mb_field_decoding_flag = ps_cur_mb_info->u1_mb_field_decodingflag; ps_curmb = ps_cur_mb_info->ps_curmb; ps_top_mb = ps_cur_mb_info->ps_top_mb; ps_left_mb = ps_cur_mb_info->ps_left_mb; ps_top_right_mb = ps_cur_mb_info->ps_top_right_mb; /*--------------------------------------------------------------------*/ /* Check whether neighbouring MB is Inter MB and */ /* constrained intra pred is 1. */ /*--------------------------------------------------------------------*/ u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(ps_dec->ps_cur_pps->u1_constrained_intra_pred_flag) { UWORD8 u1_left = (UWORD8)u2_use_left_mb; uc_useTopMB = uc_useTopMB && ((ps_top_mb->u1_mb_type != P_MB) && (ps_top_mb->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && ((ps_left_mb->u1_mb_type != P_MB) && (ps_left_mb->u1_mb_type != B_MB)); u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(u1_mbaff) { if(u1_mb_field_decoding_flag ^ ps_left_mb->u1_mb_fld) { u1_left = u1_left && (((ps_left_mb + 1)->u1_mb_type != P_MB) && ((ps_left_mb + 1)->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && u1_left; if(u1_mb_field_decoding_flag) u2_use_left_mb_pack = (u1_left << 8) + (u2_use_left_mb_pack & 0xff); else u2_use_left_mb_pack = (u2_use_left_mb << 8) + (u2_use_left_mb); } } u1_use_top_right_mb = u1_use_top_right_mb && ((ps_top_right_mb->u1_mb_type != P_MB) && (ps_top_right_mb->u1_mb_type != B_MB)); u1_use_top_left_mb = u1_use_top_left_mb && ((ps_cur_mb_info->u1_topleft_mbtype != P_MB) && (ps_cur_mb_info->u1_topleft_mbtype != B_MB)); } /*********************Common pointer calculations *************************/ /* CHANGED CODE */ pu1_luma_pred_buffer = ps_dec->pu1_y; pu1_luma_rec_buffer = ps_frame_buf->pu1_dest_y + (u4_num_pmbair << 4); pu1_mb_cb_rei1_buffer = ps_frame_buf->pu1_dest_u + (u4_num_pmbair << 3) * YUV420SP_FACTOR; pu1_mb_cr_rei1_buffer = ps_frame_buf->pu1_dest_v + (u4_num_pmbair << 3); ui_pred_width = MB_SIZE; ui_rec_width = ps_dec->u2_frm_wd_y << u1_mb_field_decoding_flag; u4_recwidth_cr = ps_dec->u2_frm_wd_uv << u1_mb_field_decoding_flag; /************* Current and top luma pointer *****************/ if(u1_mbaff) { if(u1_topmb == 0) { pu1_luma_rec_buffer += ( u1_mb_field_decoding_flag ? (ui_rec_width >> 1) : (ui_rec_width << 4)); pu1_mb_cb_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); pu1_mb_cr_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); } } /* CHANGED CODE */ if(ps_dec->u4_use_intrapred_line_copy == 1) { puc_top = ps_dec->pu1_prev_y_intra_pred_line + (ps_cur_mb_info->u2_mbx << 4); pu1_top_u = ps_dec->pu1_prev_u_intra_pred_line + (ps_cur_mb_info->u2_mbx << 3) * YUV420SP_FACTOR; } else { puc_top = pu1_luma_rec_buffer - ui_rec_width; pu1_top_u = pu1_mb_cb_rei1_buffer - u4_recwidth_cr; } /* CHANGED CODE */ /************* Left pointer *****************/ pu1_yleft = pu1_luma_rec_buffer - 1; pu1_uleft = pu1_mb_cb_rei1_buffer - 1 * YUV420SP_FACTOR; /**************Top Left pointer calculation**********/ pu1_ytop_left = puc_top - 1; pu1_u_top_left = pu1_top_u - 1 * YUV420SP_FACTOR; /* CHANGED CODE */ PROFILE_DISABLE_INTRA_PRED() { pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; if(u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 0) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 32); } else if (u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 1) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 8); } } if(!ps_cur_mb_info->u1_tran_form8x8) { u4_luma_dc_only_csbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { if(!ps_dec->ps_cur_pps->u1_entropy_coding_mode) { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff8x8_mb(ps_dec, ps_cur_mb_info); } } pi2_y_coeff = ps_dec->pi2_coeff_data; if(u1_mb_type != I_4x4_MB) { UWORD8 u1_intrapred_mode = MB_TYPE_TO_INTRA_16x16_MODE(u1_mb_type); /*--------------------------------------------------------------------*/ /* 16x16 IntraPrediction */ /*--------------------------------------------------------------------*/ { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intrapred_mode & 1) ? u1_intrapred_mode : (u1_intrapred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intrapred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } { UWORD8 au1_ngbr_pels[33]; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb) { WORD32 i; for(i = 0; i < 16; i++) au1_ngbr_pels[16 - 1 - i] = pu1_yleft[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 16); } /* top left pels */ au1_ngbr_pels[16] = *pu1_ytop_left; /* top pels */ if(uc_useTopMB) { memcpy(au1_ngbr_pels + 16 + 1, puc_top, 16); } else { memset(au1_ngbr_pels + 16 + 1, 0, 16); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_16x16[u1_intrapred_mode]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((uc_useTopMB << 2) | u2_use_left_mb)); } { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 16; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_luma_rec_buffer + ((i & 0x3) * BLK_SIZE) + (i >> 2) * (ui_rec_width << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(ps_cur_mb_info->u2_luma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } else if((CHECKBIT(u4_luma_dc_only_csbp, i)) && pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } } } } } else if(!ps_cur_mb_info->u1_tran_form8x8) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left, *pu1_top_right; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 16; WORD16 *pi2_y_coeff1; UWORD8 u1_cur_sub_block; UWORD16 ui2_top_rt_mask; /*--------------------------------------------------------------------*/ /* 4x4 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /*--------------------------------------------------------------------*/ pu1_top = puc_top; ui2_top_rt_mask = (u1_use_top_right_mb << 3) | (0x5750); if(uc_useTopMB) ui2_top_rt_mask |= 0x7; /*Top Related initialisations*/ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /*-------------------------------------- if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; }*/ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; else *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_cur_pred_mode = NOT_VALID; /* CHANGED CODE */ /* CHANGED CODE */ /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) *(WORD32*)pi1_left_pred_mode = NOT_VALID; else *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; pu1_top_left = pu1_ytop_left; /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 16; u1_sub_mb_num++) { UWORD8 au1_ngbr_pels[13]; u1_sub_blk_x = u1_sub_mb_num & 0x3; u1_sub_blk_y = u1_sub_mb_num >> 2; i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y]; u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) u1_is_left_sub_block = 1; else u1_is_left_sub_block = (u1_sub_blk_y < 2) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); /* CHANGED CODE */ if(u1_sub_blk_y) u1_is_top_sub_block = 1; /* CHANGED CODE */ /***************** Top *********************/ if(ps_dec->u4_use_intrapred_line_copy == 1) { if(u1_sub_blk_y) pu1_top = pu1_luma_rec_buffer - ui_rec_width; else pu1_top = puc_top + (u1_sub_blk_x << 2); } else { pu1_top = pu1_luma_rec_buffer - ui_rec_width; } /***************** Top Right *********************/ pu1_top_right = pu1_top + 4; /***************** Top Left *********************/ pu1_top_left = pu1_top - 1; /***************** Left *********************/ pu1_left = pu1_luma_rec_buffer - 1; /* CHANGED CODE */ /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; UWORD8 uc_b2b0 = ((u1_sub_mb_num & 4) >> 1) | (u1_sub_mb_num & 1); UWORD8 uc_b3b1 = ((u1_sub_mb_num & 8) >> 2) | ((u1_sub_mb_num & 2) >> 1); u1_cur_sub_block = (uc_b3b1 << 2) + uc_b2b0; PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_cur_sub_block]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] + (pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] >= i1_intra_pred); } { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { /* Get neighbour pixels */ /* left pels */ if(u1_is_left_sub_block) { WORD32 i; for(i = 0; i < 4; i++) au1_ngbr_pels[4 - 1 - i] = pu1_left[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 4); } /* top left pels */ au1_ngbr_pels[4] = *pu1_top_left; /* top pels */ if(u1_is_top_sub_block) { memcpy(au1_ngbr_pels + 4 + 1, pu1_top, 4); } else { memset(au1_ngbr_pels + 4 + 1, 0, 4); } /* top right pels */ if(u1_use_top_right_mb) { memcpy(au1_ngbr_pels + 4 * 2 + 1, pu1_top_right, 4); } else if(u1_is_top_sub_block) { memset(au1_ngbr_pels + 4 * 2 + 1, au1_ngbr_pels[4 * 2], 4); } } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_4x4[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); /* CHANGED CODE */ if(CHECKBIT(ui2_luma_csbp, u1_sub_mb_num)) { WORD16 ai2_tmp[16]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_csbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 16; pu1_luma_rec_buffer += (u1_sub_blk_x == 3) ? (ui_rec_width << 2) - 12 : 4; pu1_luma_pred_buffer += (u1_sub_blk_x == 3) ? (ui_pred_width << 2) - 12 : 4; /* CHANGED CODE */ pi1_cur_pred_mode[u1_sub_blk_x] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y] = i1_intra_pred; } } else if((u1_mb_type == I_4x4_MB) && (ps_cur_mb_info->u1_tran_form8x8 == 1)) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 4; WORD16 *pi2_y_coeff1; UWORD16 ui2_top_rt_mask; UWORD32 u4_4x4_left_offset = 0; /*--------------------------------------------------------------------*/ /* 8x8 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /* */ /* ui2_top_rt_mask: marks availibility of top right(neighbour) */ /* in the 8x8 Block ordering */ /* */ /* tr0 tr1 */ /* 0 1 tr3 */ /* 2 3 */ /* */ /* Top rights for 0 is in top MB */ /* top right of 1 will be in top right MB */ /* top right of 3 in right MB and hence not available */ /* This corresponds to ui2_top_rt_mask having default value 0x4 */ /*--------------------------------------------------------------------*/ ui2_top_rt_mask = (u1_use_top_right_mb << 1) | (0x4); if(uc_useTopMB) { ui2_top_rt_mask |= 0x1; } /* Top Related initialisations */ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /* if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; } */ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) { *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; } else { *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_cur_pred_mode = NOT_VALID; } pu1_top = puc_top - 8; /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if((!u1_curMbfld) && (u1_leftMbfld)) { u4_4x4_left_offset = 1; } if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) { *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; if(u1_use_top_left_mb) { pu1_top_left = pu1_ytop_left; } else { pu1_top_left = NULL; } /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 4; u1_sub_mb_num++) { u1_sub_blk_x = (u1_sub_mb_num & 0x1); u1_sub_blk_y = (u1_sub_mb_num >> 1); i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x << 1]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y << 1]; if(2 == u1_sub_mb_num) { i1_left_pred_mode = pi1_left_pred_mode[(u1_sub_blk_y << 1) + u4_4x4_left_offset]; } u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) { u1_is_left_sub_block = 1; } else { u1_is_left_sub_block = (u1_sub_blk_y < 1) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); } /***************** Top *********************/ if(u1_sub_blk_y) { u1_is_top_sub_block = 1; pu1_top = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - ui_rec_width; } else { pu1_top += 8; } /***************** Left *********************/ if((u1_sub_blk_x) | (u4_num_pmbair != 0)) { pu1_left = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - 1; ui2_left_pred_buf_width = ui_rec_width; } else { pu1_left = pu1_yleft; pu1_yleft += (ui_rec_width << 3); ui2_left_pred_buf_width = ui_rec_width; } /***************** Top Left *********************/ if(u1_sub_mb_num) { pu1_top_left = (u1_sub_blk_x) ? pu1_top - 1 : pu1_left - ui_rec_width; if((u1_sub_blk_x && (!u1_is_top_sub_block)) || ((!u1_sub_blk_x) && (!u1_is_left_sub_block))) { pu1_top_left = NULL; } } /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; /********************************************************************/ /* Same intra4x4_pred_mode array is filled with intra4x4_pred_mode */ /* for a MB with 8x8 intrapredicition */ /********************************************************************/ PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_sub_mb_num]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] + (pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] >= i1_intra_pred); } { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { UWORD8 au1_ngbr_pels[25]; WORD32 ngbr_avail; ngbr_avail = u1_is_left_sub_block << 0; ngbr_avail |= u1_is_top_sub_block << 2; if(pu1_top_left) ngbr_avail |= 1 << 1; ngbr_avail |= u1_use_top_right_mb << 3; PROFILE_DISABLE_INTRA_PRED() { ps_dec->pf_intra_pred_ref_filtering(pu1_left, pu1_top_left, pu1_top, au1_ngbr_pels, ui2_left_pred_buf_width, ngbr_avail); ps_dec->apf_intra_pred_luma_8x8[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); } } /* Inverse Transform and Reconstruction */ if(CHECKBIT(ps_cur_mb_info->u1_cbp, u1_sub_mb_num)) { WORD16 *pi2_scale_matrix_ptr; WORD16 ai2_tmp[64]; pi2_scale_matrix_ptr = ps_dec->s_high_profile.i2_scalinglist8x8[0]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_cbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_8x8_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_8x8( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 64; pu1_luma_rec_buffer += (u1_sub_blk_x == 1) ? (ui_rec_width << 3) - (8 * 1) : 8; /*---------------------------------------------------------------*/ /* Pred mode filled in terms of 4x4 block so replicated in 2 */ /* locations. */ /*---------------------------------------------------------------*/ pi1_cur_pred_mode[u1_sub_blk_x << 1] = i1_intra_pred; pi1_cur_pred_mode[(u1_sub_blk_x << 1) + 1] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y << 1] = i1_intra_pred; pi1_left_pred_mode[(u1_sub_blk_y << 1) + 1] = i1_intra_pred; } } /* Decode Chroma Block */ ih264d_unpack_chroma_coeff4x4_mb(ps_dec, ps_cur_mb_info); /*--------------------------------------------------------------------*/ /* Chroma Blocks decoding */ /*--------------------------------------------------------------------*/ { UWORD8 u1_intra_chrom_pred_mode; UWORD8 u1_chroma_cbp = (UWORD8)(ps_cur_mb_info->u1_cbp >> 4); /*--------------------------------------------------------------------*/ /* Perform Chroma intra prediction */ /*--------------------------------------------------------------------*/ u1_intra_chrom_pred_mode = CHROMA_TO_LUMA_INTRA_MODE( ps_cur_mb_info->u1_chroma_pred_mode); { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intra_chrom_pred_mode & 1) ? u1_intra_chrom_pred_mode : (u1_intra_chrom_pred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intra_chrom_pred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } /* CHANGED CODE */ if(u1_chroma_cbp != CBPC_ALLZERO) { UWORD16 u2_chroma_csbp = (u1_chroma_cbp == CBPC_ACZERO) ? 0 : ps_cur_mb_info->u2_chroma_csbp; UWORD32 u4_scale_u; UWORD32 u4_scale_v; { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_left_uv = (UWORD16 *)pu1_uleft; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } u4_scale_u = ps_cur_mb_info->u1_qpc_div6; u4_scale_v = ps_cur_mb_info->u1_qpcr_div6; pi2_y_coeff = ps_dec->pi2_coeff_data; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } } } } pi2_y_coeff += MB_CHROM_SIZE; u2_chroma_csbp = u2_chroma_csbp >> 4; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + 1 + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } } } } } else { /* If no inverse transform is needed, pass recon buffer pointer */ /* to Intraprediction module instead of pred buffer pointer */ { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; pu2_left_uv = (UWORD16 *)pu1_uleft; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } } } return OK; } Commit Message: Decoder: Fix for handling invalid intra mode Bug: 28165659 Change-Id: I2291a287c27291695f4f3d6e753b6bbd7dfd9e42 CWE ID: CWE-20
WORD32 ih264d_process_intra_mb(dec_struct_t * ps_dec, dec_mb_info_t * ps_cur_mb_info, UWORD8 u1_mb_num) { UWORD8 u1_mb_type = ps_cur_mb_info->u1_mb_type; UWORD8 uc_temp = ps_cur_mb_info->u1_mb_ngbr_availablity; UWORD8 u1_top_available = BOOLEAN(uc_temp & TOP_MB_AVAILABLE_MASK); UWORD8 u1_left_available = BOOLEAN(uc_temp & LEFT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_right_mb = BOOLEAN(uc_temp & TOP_RIGHT_MB_AVAILABLE_MASK); UWORD8 u1_use_top_left_mb = BOOLEAN(uc_temp & TOP_LEFT_MB_AVAILABLE_MASK); UWORD8 uc_useTopMB = u1_top_available; UWORD16 u2_use_left_mb = u1_left_available; UWORD16 u2_use_left_mb_pack; UWORD8 *pu1_luma_pred_buffer; /* CHANGED CODE */ UWORD8 *pu1_luma_rec_buffer; UWORD8 *puc_top; mb_neigbour_params_t *ps_left_mb; mb_neigbour_params_t *ps_top_mb; mb_neigbour_params_t *ps_top_right_mb; mb_neigbour_params_t *ps_curmb; UWORD16 u2_mbx = ps_cur_mb_info->u2_mbx; UWORD32 ui_pred_width, ui_rec_width; WORD16 *pi2_y_coeff; UWORD8 u1_mbaff, u1_topmb, u1_mb_field_decoding_flag; UWORD32 u4_num_pmbair; UWORD16 ui2_luma_csbp = ps_cur_mb_info->u2_luma_csbp; UWORD8 *pu1_yleft, *pu1_ytop_left; /* Chroma variables*/ UWORD8 *pu1_top_u; UWORD8 *pu1_uleft; UWORD8 *pu1_u_top_left; /* CHANGED CODE */ UWORD8 *pu1_mb_cb_rei1_buffer, *pu1_mb_cr_rei1_buffer; UWORD32 u4_recwidth_cr; /* CHANGED CODE */ tfr_ctxt_t *ps_frame_buf = ps_dec->ps_frame_buf_ip_recon; UWORD32 u4_luma_dc_only_csbp = 0; UWORD32 u4_luma_dc_only_cbp = 0; UWORD8 *pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; //Pointer to keep track of intra4x4_pred_mode data in pv_proc_tu_coeff_data buffer u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag; u1_topmb = ps_cur_mb_info->u1_topmb; u4_num_pmbair = (u1_mb_num >> u1_mbaff); /*--------------------------------------------------------------------*/ /* Find the current MB's mb params */ /*--------------------------------------------------------------------*/ u1_mb_field_decoding_flag = ps_cur_mb_info->u1_mb_field_decodingflag; ps_curmb = ps_cur_mb_info->ps_curmb; ps_top_mb = ps_cur_mb_info->ps_top_mb; ps_left_mb = ps_cur_mb_info->ps_left_mb; ps_top_right_mb = ps_cur_mb_info->ps_top_right_mb; /*--------------------------------------------------------------------*/ /* Check whether neighbouring MB is Inter MB and */ /* constrained intra pred is 1. */ /*--------------------------------------------------------------------*/ u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(ps_dec->ps_cur_pps->u1_constrained_intra_pred_flag) { UWORD8 u1_left = (UWORD8)u2_use_left_mb; uc_useTopMB = uc_useTopMB && ((ps_top_mb->u1_mb_type != P_MB) && (ps_top_mb->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && ((ps_left_mb->u1_mb_type != P_MB) && (ps_left_mb->u1_mb_type != B_MB)); u2_use_left_mb_pack = (u2_use_left_mb << 8) + u2_use_left_mb; if(u1_mbaff) { if(u1_mb_field_decoding_flag ^ ps_left_mb->u1_mb_fld) { u1_left = u1_left && (((ps_left_mb + 1)->u1_mb_type != P_MB) && ((ps_left_mb + 1)->u1_mb_type != B_MB)); u2_use_left_mb = u2_use_left_mb && u1_left; if(u1_mb_field_decoding_flag) u2_use_left_mb_pack = (u1_left << 8) + (u2_use_left_mb_pack & 0xff); else u2_use_left_mb_pack = (u2_use_left_mb << 8) + (u2_use_left_mb); } } u1_use_top_right_mb = u1_use_top_right_mb && ((ps_top_right_mb->u1_mb_type != P_MB) && (ps_top_right_mb->u1_mb_type != B_MB)); u1_use_top_left_mb = u1_use_top_left_mb && ((ps_cur_mb_info->u1_topleft_mbtype != P_MB) && (ps_cur_mb_info->u1_topleft_mbtype != B_MB)); } /*********************Common pointer calculations *************************/ /* CHANGED CODE */ pu1_luma_pred_buffer = ps_dec->pu1_y; pu1_luma_rec_buffer = ps_frame_buf->pu1_dest_y + (u4_num_pmbair << 4); pu1_mb_cb_rei1_buffer = ps_frame_buf->pu1_dest_u + (u4_num_pmbair << 3) * YUV420SP_FACTOR; pu1_mb_cr_rei1_buffer = ps_frame_buf->pu1_dest_v + (u4_num_pmbair << 3); ui_pred_width = MB_SIZE; ui_rec_width = ps_dec->u2_frm_wd_y << u1_mb_field_decoding_flag; u4_recwidth_cr = ps_dec->u2_frm_wd_uv << u1_mb_field_decoding_flag; /************* Current and top luma pointer *****************/ if(u1_mbaff) { if(u1_topmb == 0) { pu1_luma_rec_buffer += ( u1_mb_field_decoding_flag ? (ui_rec_width >> 1) : (ui_rec_width << 4)); pu1_mb_cb_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); pu1_mb_cr_rei1_buffer += ( u1_mb_field_decoding_flag ? (u4_recwidth_cr >> 1) : (u4_recwidth_cr << 3)); } } /* CHANGED CODE */ if(ps_dec->u4_use_intrapred_line_copy == 1) { puc_top = ps_dec->pu1_prev_y_intra_pred_line + (ps_cur_mb_info->u2_mbx << 4); pu1_top_u = ps_dec->pu1_prev_u_intra_pred_line + (ps_cur_mb_info->u2_mbx << 3) * YUV420SP_FACTOR; } else { puc_top = pu1_luma_rec_buffer - ui_rec_width; pu1_top_u = pu1_mb_cb_rei1_buffer - u4_recwidth_cr; } /* CHANGED CODE */ /************* Left pointer *****************/ pu1_yleft = pu1_luma_rec_buffer - 1; pu1_uleft = pu1_mb_cb_rei1_buffer - 1 * YUV420SP_FACTOR; /**************Top Left pointer calculation**********/ pu1_ytop_left = puc_top - 1; pu1_u_top_left = pu1_top_u - 1 * YUV420SP_FACTOR; /* CHANGED CODE */ PROFILE_DISABLE_INTRA_PRED() { pu1_prev_intra4x4_pred_mode_data = (UWORD8 *)ps_dec->pv_proc_tu_coeff_data; if(u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 0) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 32); } else if (u1_mb_type == I_4x4_MB && ps_cur_mb_info->u1_tran_form8x8 == 1) { ps_dec->pv_proc_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_proc_tu_coeff_data + 8); } } if(!ps_cur_mb_info->u1_tran_form8x8) { u4_luma_dc_only_csbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { if(!ps_dec->ps_cur_pps->u1_entropy_coding_mode) { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff4x4_mb(ps_dec, ps_cur_mb_info, 1); } else { u4_luma_dc_only_cbp = ih264d_unpack_luma_coeff8x8_mb(ps_dec, ps_cur_mb_info); } } pi2_y_coeff = ps_dec->pi2_coeff_data; if(u1_mb_type != I_4x4_MB) { UWORD8 u1_intrapred_mode = MB_TYPE_TO_INTRA_16x16_MODE(u1_mb_type); /*--------------------------------------------------------------------*/ /* 16x16 IntraPrediction */ /*--------------------------------------------------------------------*/ { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intrapred_mode & 1) ? u1_intrapred_mode : (u1_intrapred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intrapred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } { UWORD8 au1_ngbr_pels[33]; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb) { WORD32 i; for(i = 0; i < 16; i++) au1_ngbr_pels[16 - 1 - i] = pu1_yleft[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 16); } /* top left pels */ au1_ngbr_pels[16] = *pu1_ytop_left; /* top pels */ if(uc_useTopMB) { memcpy(au1_ngbr_pels + 16 + 1, puc_top, 16); } else { memset(au1_ngbr_pels + 16 + 1, 0, 16); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_16x16[u1_intrapred_mode]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((uc_useTopMB << 2) | u2_use_left_mb)); } { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 16; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_luma_rec_buffer + ((i & 0x3) * BLK_SIZE) + (i >> 2) * (ui_rec_width << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(ps_cur_mb_info->u2_luma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } else if((CHECKBIT(u4_luma_dc_only_csbp, i)) && pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 1, pi2_level); } } } } } else if(!ps_cur_mb_info->u1_tran_form8x8) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left, *pu1_top_right; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 16; WORD16 *pi2_y_coeff1; UWORD8 u1_cur_sub_block; UWORD16 ui2_top_rt_mask; /*--------------------------------------------------------------------*/ /* 4x4 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /*--------------------------------------------------------------------*/ pu1_top = puc_top; ui2_top_rt_mask = (u1_use_top_right_mb << 3) | (0x5750); if(uc_useTopMB) ui2_top_rt_mask |= 0x7; /*Top Related initialisations*/ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /*-------------------------------------- if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; }*/ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; else *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_cur_pred_mode = NOT_VALID; /* CHANGED CODE */ /* CHANGED CODE */ /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) *(WORD32*)pi1_left_pred_mode = NOT_VALID; else *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } else *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } else *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; pu1_top_left = pu1_ytop_left; /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 16; u1_sub_mb_num++) { UWORD8 au1_ngbr_pels[13]; u1_sub_blk_x = u1_sub_mb_num & 0x3; u1_sub_blk_y = u1_sub_mb_num >> 2; i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y]; u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) u1_is_left_sub_block = 1; else u1_is_left_sub_block = (u1_sub_blk_y < 2) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); /* CHANGED CODE */ if(u1_sub_blk_y) u1_is_top_sub_block = 1; /* CHANGED CODE */ /***************** Top *********************/ if(ps_dec->u4_use_intrapred_line_copy == 1) { if(u1_sub_blk_y) pu1_top = pu1_luma_rec_buffer - ui_rec_width; else pu1_top = puc_top + (u1_sub_blk_x << 2); } else { pu1_top = pu1_luma_rec_buffer - ui_rec_width; } /***************** Top Right *********************/ pu1_top_right = pu1_top + 4; /***************** Top Left *********************/ pu1_top_left = pu1_top - 1; /***************** Left *********************/ pu1_left = pu1_luma_rec_buffer - 1; /* CHANGED CODE */ /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; UWORD8 uc_b2b0 = ((u1_sub_mb_num & 4) >> 1) | (u1_sub_mb_num & 1); UWORD8 uc_b3b1 = ((u1_sub_mb_num & 8) >> 2) | ((u1_sub_mb_num & 2) >> 1); u1_cur_sub_block = (uc_b3b1 << 2) + uc_b2b0; PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_cur_sub_block]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] + (pu1_rem_intra4x4_pred_mode[u1_cur_sub_block] >= i1_intra_pred); } i1_intra_pred = CLIP3(0, 8, i1_intra_pred); { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { /* Get neighbour pixels */ /* left pels */ if(u1_is_left_sub_block) { WORD32 i; for(i = 0; i < 4; i++) au1_ngbr_pels[4 - 1 - i] = pu1_left[i * ui_rec_width]; } else { memset(au1_ngbr_pels, 0, 4); } /* top left pels */ au1_ngbr_pels[4] = *pu1_top_left; /* top pels */ if(u1_is_top_sub_block) { memcpy(au1_ngbr_pels + 4 + 1, pu1_top, 4); } else { memset(au1_ngbr_pels + 4 + 1, 0, 4); } /* top right pels */ if(u1_use_top_right_mb) { memcpy(au1_ngbr_pels + 4 * 2 + 1, pu1_top_right, 4); } else if(u1_is_top_sub_block) { memset(au1_ngbr_pels + 4 * 2 + 1, au1_ngbr_pels[4 * 2], 4); } } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_luma_4x4[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); /* CHANGED CODE */ if(CHECKBIT(ui2_luma_csbp, u1_sub_mb_num)) { WORD16 ai2_tmp[16]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_csbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_4x4_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_4x4( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[0], ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 16; pu1_luma_rec_buffer += (u1_sub_blk_x == 3) ? (ui_rec_width << 2) - 12 : 4; pu1_luma_pred_buffer += (u1_sub_blk_x == 3) ? (ui_pred_width << 2) - 12 : 4; /* CHANGED CODE */ pi1_cur_pred_mode[u1_sub_blk_x] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y] = i1_intra_pred; } } else if((u1_mb_type == I_4x4_MB) && (ps_cur_mb_info->u1_tran_form8x8 == 1)) { UWORD8 u1_is_left_sub_block, u1_is_top_sub_block = uc_useTopMB; UWORD8 u1_sub_blk_x, u1_sub_blk_y, u1_sub_mb_num; WORD8 i1_top_pred_mode; WORD8 i1_left_pred_mode; UWORD8 *pu1_top, *pu1_left, *pu1_top_left; WORD8 *pi1_cur_pred_mode, *pi1_left_pred_mode, *pc_topPredMode; UWORD16 ui2_left_pred_buf_width = 0xffff; WORD8 i1_intra_pred; UWORD8 *pu1_prev_intra4x4_pred_mode_flag = pu1_prev_intra4x4_pred_mode_data; UWORD8 *pu1_rem_intra4x4_pred_mode = pu1_prev_intra4x4_pred_mode_data + 4; WORD16 *pi2_y_coeff1; UWORD16 ui2_top_rt_mask; UWORD32 u4_4x4_left_offset = 0; /*--------------------------------------------------------------------*/ /* 8x8 IntraPrediction */ /*--------------------------------------------------------------------*/ /* Calculation of Top Right subblock mask */ /* */ /* (a) Set it to default mask */ /* [It has 0 for sublocks which will never have top-right sub block] */ /* */ /* (b) If top MB is not available */ /* Clear the bits of the first row sub blocks */ /* */ /* (c) Set/Clear bit for top-right sublock of MB */ /* [5 sub-block in decoding order] based on TOP RIGHT MB availablity */ /* */ /* ui2_top_rt_mask: marks availibility of top right(neighbour) */ /* in the 8x8 Block ordering */ /* */ /* tr0 tr1 */ /* 0 1 tr3 */ /* 2 3 */ /* */ /* Top rights for 0 is in top MB */ /* top right of 1 will be in top right MB */ /* top right of 3 in right MB and hence not available */ /* This corresponds to ui2_top_rt_mask having default value 0x4 */ /*--------------------------------------------------------------------*/ ui2_top_rt_mask = (u1_use_top_right_mb << 1) | (0x4); if(uc_useTopMB) { ui2_top_rt_mask |= 0x1; } /* Top Related initialisations */ pi1_cur_pred_mode = ps_cur_mb_info->ps_curmb->pi1_intrapredmodes; pc_topPredMode = ps_cur_mb_info->ps_top_mb->pi1_intrapredmodes; /* if(u1_mbaff) { pi1_cur_pred_mode += (u2_mbx << 2); pc_topPredMode = pi1_cur_pred_mode + ps_cur_mb_info->i1_offset; pi1_cur_pred_mode += (u1_topmb) ? 0: 4; } */ if(u1_top_available) { if(ps_top_mb->u1_mb_type == I_4x4_MB) { *(WORD32*)pi1_cur_pred_mode = *(WORD32*)pc_topPredMode; } else { *(WORD32*)pi1_cur_pred_mode = (uc_useTopMB) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_cur_pred_mode = NOT_VALID; } pu1_top = puc_top - 8; /*Left Related initialisations*/ pi1_left_pred_mode = ps_dec->pi1_left_pred_mode; if(!u1_mbaff) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } else { UWORD8 u1_curMbfld = ps_cur_mb_info->u1_mb_field_decodingflag; UWORD8 u1_leftMbfld = ps_left_mb->u1_mb_fld; if((!u1_curMbfld) && (u1_leftMbfld)) { u4_4x4_left_offset = 1; } if(u1_curMbfld ^ u1_leftMbfld) { if(u1_topmb | ((u1_topmb == 0) && ((ps_curmb - 1)->u1_mb_type != I_4x4_MB))) { if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { if(CHECKBIT(u2_use_left_mb_pack,0) == 0) { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } else { *(WORD32*)pi1_left_pred_mode = DC_DC_DC_DC; } } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } if(u1_curMbfld) { if(u1_left_available) { if((ps_left_mb + 1)->u1_mb_type != I_4x4_MB) { if(u2_use_left_mb_pack >> 8) { *(WORD32*)(pi1_left_pred_mode + 4) = DC_DC_DC_DC; } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } } } else { *(WORD32*)(pi1_left_pred_mode + 4) = NOT_VALID; } pi1_left_pred_mode[1] = pi1_left_pred_mode[2]; pi1_left_pred_mode[2] = pi1_left_pred_mode[4]; pi1_left_pred_mode[3] = pi1_left_pred_mode[6]; *(WORD32*)(pi1_left_pred_mode + 4) = *(WORD32*)pi1_left_pred_mode; } else { pi1_left_pred_mode[7] = pi1_left_pred_mode[3]; pi1_left_pred_mode[6] = pi1_left_pred_mode[3]; pi1_left_pred_mode[5] = pi1_left_pred_mode[2]; pi1_left_pred_mode[4] = pi1_left_pred_mode[2]; pi1_left_pred_mode[3] = pi1_left_pred_mode[1]; pi1_left_pred_mode[2] = pi1_left_pred_mode[1]; pi1_left_pred_mode[1] = pi1_left_pred_mode[0]; } } pi1_left_pred_mode += (u1_topmb) ? 0 : 4; } else { pi1_left_pred_mode += (u1_topmb) ? 0 : 4; if(u1_left_available) { if(ps_left_mb->u1_mb_type != I_4x4_MB) { *(WORD32*)pi1_left_pred_mode = (u2_use_left_mb_pack) ? DC_DC_DC_DC : NOT_VALID; } } else { *(WORD32*)pi1_left_pred_mode = NOT_VALID; } } } /* One time pointer initialisations*/ pi2_y_coeff1 = pi2_y_coeff; if(u1_use_top_left_mb) { pu1_top_left = pu1_ytop_left; } else { pu1_top_left = NULL; } /* Scan the sub-blocks in Raster Scan Order */ for(u1_sub_mb_num = 0; u1_sub_mb_num < 4; u1_sub_mb_num++) { u1_sub_blk_x = (u1_sub_mb_num & 0x1); u1_sub_blk_y = (u1_sub_mb_num >> 1); i1_top_pred_mode = pi1_cur_pred_mode[u1_sub_blk_x << 1]; i1_left_pred_mode = pi1_left_pred_mode[u1_sub_blk_y << 1]; if(2 == u1_sub_mb_num) { i1_left_pred_mode = pi1_left_pred_mode[(u1_sub_blk_y << 1) + u4_4x4_left_offset]; } u1_use_top_right_mb = (!!CHECKBIT(ui2_top_rt_mask, u1_sub_mb_num)); /*********** left subblock availability**********/ if(u1_sub_blk_x) { u1_is_left_sub_block = 1; } else { u1_is_left_sub_block = (u1_sub_blk_y < 1) ? (CHECKBIT(u2_use_left_mb_pack, 0)) : (u2_use_left_mb_pack >> 8); } /***************** Top *********************/ if(u1_sub_blk_y) { u1_is_top_sub_block = 1; pu1_top = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - ui_rec_width; } else { pu1_top += 8; } /***************** Left *********************/ if((u1_sub_blk_x) | (u4_num_pmbair != 0)) { pu1_left = /*pu1_luma_pred_buffer*/pu1_luma_rec_buffer - 1; ui2_left_pred_buf_width = ui_rec_width; } else { pu1_left = pu1_yleft; pu1_yleft += (ui_rec_width << 3); ui2_left_pred_buf_width = ui_rec_width; } /***************** Top Left *********************/ if(u1_sub_mb_num) { pu1_top_left = (u1_sub_blk_x) ? pu1_top - 1 : pu1_left - ui_rec_width; if((u1_sub_blk_x && (!u1_is_top_sub_block)) || ((!u1_sub_blk_x) && (!u1_is_left_sub_block))) { pu1_top_left = NULL; } } /*---------------------------------------------------------------*/ /* Calculation of Intra prediction mode */ /*---------------------------------------------------------------*/ i1_intra_pred = ((i1_left_pred_mode < 0) | (i1_top_pred_mode < 0)) ? DC : MIN(i1_left_pred_mode, i1_top_pred_mode); { UWORD8 u1_packed_modes = (u1_is_top_sub_block << 1) + u1_is_left_sub_block; UWORD8 *pu1_intra_err_codes = (UWORD8 *)gau1_ih264d_intra_pred_err_code; /********************************************************************/ /* Same intra4x4_pred_mode array is filled with intra4x4_pred_mode */ /* for a MB with 8x8 intrapredicition */ /********************************************************************/ PROFILE_DISABLE_INTRA_PRED() if(!pu1_prev_intra4x4_pred_mode_flag[u1_sub_mb_num]) { i1_intra_pred = pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] + (pu1_rem_intra4x4_pred_mode[u1_sub_mb_num] >= i1_intra_pred); } i1_intra_pred = CLIP3(0, 8, i1_intra_pred); { UWORD8 u1_err_code = pu1_intra_err_codes[i1_intra_pred]; if((u1_err_code & u1_packed_modes) ^ u1_err_code) { i1_intra_pred = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } } { UWORD8 au1_ngbr_pels[25]; WORD32 ngbr_avail; ngbr_avail = u1_is_left_sub_block << 0; ngbr_avail |= u1_is_top_sub_block << 2; if(pu1_top_left) ngbr_avail |= 1 << 1; ngbr_avail |= u1_use_top_right_mb << 3; PROFILE_DISABLE_INTRA_PRED() { ps_dec->pf_intra_pred_ref_filtering(pu1_left, pu1_top_left, pu1_top, au1_ngbr_pels, ui2_left_pred_buf_width, ngbr_avail); ps_dec->apf_intra_pred_luma_8x8[i1_intra_pred]( au1_ngbr_pels, pu1_luma_rec_buffer, 1, ui_rec_width, ((u1_is_top_sub_block << 2) | u1_is_left_sub_block)); } } /* Inverse Transform and Reconstruction */ if(CHECKBIT(ps_cur_mb_info->u1_cbp, u1_sub_mb_num)) { WORD16 *pi2_scale_matrix_ptr; WORD16 ai2_tmp[64]; pi2_scale_matrix_ptr = ps_dec->s_high_profile.i2_scalinglist8x8[0]; PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u4_luma_dc_only_cbp, u1_sub_mb_num)) { ps_dec->pf_iquant_itrans_recon_luma_8x8_dc( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } else { ps_dec->pf_iquant_itrans_recon_luma_8x8( pi2_y_coeff1, pu1_luma_rec_buffer, pu1_luma_rec_buffer, ui_rec_width, ui_rec_width, gau1_ih264d_dequant8x8_cavlc[ps_cur_mb_info->u1_qp_rem6], (UWORD16 *)pi2_scale_matrix_ptr, ps_cur_mb_info->u1_qp_div6, ai2_tmp, 0, NULL); } } } /*---------------------------------------------------------------*/ /* Update sub block number */ /*---------------------------------------------------------------*/ pi2_y_coeff1 += 64; pu1_luma_rec_buffer += (u1_sub_blk_x == 1) ? (ui_rec_width << 3) - (8 * 1) : 8; /*---------------------------------------------------------------*/ /* Pred mode filled in terms of 4x4 block so replicated in 2 */ /* locations. */ /*---------------------------------------------------------------*/ pi1_cur_pred_mode[u1_sub_blk_x << 1] = i1_intra_pred; pi1_cur_pred_mode[(u1_sub_blk_x << 1) + 1] = i1_intra_pred; pi1_left_pred_mode[u1_sub_blk_y << 1] = i1_intra_pred; pi1_left_pred_mode[(u1_sub_blk_y << 1) + 1] = i1_intra_pred; } } /* Decode Chroma Block */ ih264d_unpack_chroma_coeff4x4_mb(ps_dec, ps_cur_mb_info); /*--------------------------------------------------------------------*/ /* Chroma Blocks decoding */ /*--------------------------------------------------------------------*/ { UWORD8 u1_intra_chrom_pred_mode; UWORD8 u1_chroma_cbp = (UWORD8)(ps_cur_mb_info->u1_cbp >> 4); /*--------------------------------------------------------------------*/ /* Perform Chroma intra prediction */ /*--------------------------------------------------------------------*/ u1_intra_chrom_pred_mode = CHROMA_TO_LUMA_INTRA_MODE( ps_cur_mb_info->u1_chroma_pred_mode); { UWORD8 u1_packed_modes = (u1_top_available << 1) + u1_left_available; UWORD8 u1_err_code = (u1_intra_chrom_pred_mode & 1) ? u1_intra_chrom_pred_mode : (u1_intra_chrom_pred_mode ^ 2); if((u1_err_code & u1_packed_modes) ^ u1_err_code) { u1_intra_chrom_pred_mode = 0; ps_dec->i4_error_code = ERROR_INTRAPRED; } } /* CHANGED CODE */ if(u1_chroma_cbp != CBPC_ALLZERO) { UWORD16 u2_chroma_csbp = (u1_chroma_cbp == CBPC_ACZERO) ? 0 : ps_cur_mb_info->u2_chroma_csbp; UWORD32 u4_scale_u; UWORD32 u4_scale_v; { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_left_uv = (UWORD16 *)pu1_uleft; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } u4_scale_u = ps_cur_mb_info->u1_qpc_div6; u4_scale_v = ps_cur_mb_info->u1_qpcr_div6; pi2_y_coeff = ps_dec->pi2_coeff_data; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpc_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[1], u4_scale_u, ai2_tmp, pi2_level); } } } } pi2_y_coeff += MB_CHROM_SIZE; u2_chroma_csbp = u2_chroma_csbp >> 4; { UWORD32 i; WORD16 ai2_tmp[16]; for(i = 0; i < 4; i++) { WORD16 *pi2_level = pi2_y_coeff + (i << 4); UWORD8 *pu1_pred_sblk = pu1_mb_cb_rei1_buffer + 1 + ((i & 0x1) * BLK_SIZE * YUV420SP_FACTOR) + (i >> 1) * (u4_recwidth_cr << 2); PROFILE_DISABLE_IQ_IT_RECON() { if(CHECKBIT(u2_chroma_csbp, i)) { ps_dec->pf_iquant_itrans_recon_chroma_4x4( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } else if(pi2_level[0] != 0) { ps_dec->pf_iquant_itrans_recon_chroma_4x4_dc( pi2_level, pu1_pred_sblk, pu1_pred_sblk, u4_recwidth_cr, u4_recwidth_cr, gau2_ih264_iquant_scale_4x4[ps_cur_mb_info->u1_qpcr_rem6], (UWORD16 *)ps_dec->s_high_profile.i2_scalinglist4x4[2], u4_scale_v, ai2_tmp, pi2_level); } } } } } else { /* If no inverse transform is needed, pass recon buffer pointer */ /* to Intraprediction module instead of pred buffer pointer */ { UWORD16 au2_ngbr_pels[33]; UWORD8 *pu1_ngbr_pels = (UWORD8 *)au2_ngbr_pels; UWORD16 *pu2_left_uv; UWORD16 *pu2_topleft_uv; WORD32 use_left1 = (u2_use_left_mb_pack & 0x0ff); WORD32 use_left2 = (u2_use_left_mb_pack & 0xff00) >> 8; pu2_topleft_uv = (UWORD16 *)pu1_u_top_left; pu2_left_uv = (UWORD16 *)pu1_uleft; /* Get neighbour pixels */ /* left pels */ if(u2_use_left_mb_pack) { WORD32 i; if(use_left1) { for(i = 0; i < 4; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels + 4, 0, 4 * sizeof(UWORD16)); } if(use_left2) { for(i = 4; i < 8; i++) au2_ngbr_pels[8 - 1 - i] = pu2_left_uv[i * u4_recwidth_cr / YUV420SP_FACTOR]; } else { memset(au2_ngbr_pels, 0, 4 * sizeof(UWORD16)); } } else { memset(au2_ngbr_pels, 0, 8 * sizeof(UWORD16)); } /* top left pels */ au2_ngbr_pels[8] = *pu2_topleft_uv; /* top pels */ if(uc_useTopMB) { memcpy(au2_ngbr_pels + 8 + 1, pu1_top_u, 8 * sizeof(UWORD16)); } else { memset(au2_ngbr_pels + 8 + 1, 0, 8 * sizeof(UWORD16)); } PROFILE_DISABLE_INTRA_PRED() ps_dec->apf_intra_pred_chroma[u1_intra_chrom_pred_mode]( pu1_ngbr_pels, pu1_mb_cb_rei1_buffer, 1, u4_recwidth_cr, ((uc_useTopMB << 2) | (use_left2 << 4) | use_left1)); } } } return OK; }
173,759
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 timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); }
170,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnSoundTriggerHwService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case LIST_MODULES: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); unsigned int numModulesReq = data.readInt32(); unsigned int numModules = numModulesReq; struct sound_trigger_module_descriptor *modules = (struct sound_trigger_module_descriptor *)calloc(numModulesReq, sizeof(struct sound_trigger_module_descriptor)); status_t status = listModules(modules, &numModules); reply->writeInt32(status); reply->writeInt32(numModules); ALOGV("LIST_MODULES status %d got numModules %d", status, numModules); if (status == NO_ERROR) { if (numModulesReq > numModules) { numModulesReq = numModules; } reply->write(modules, numModulesReq * sizeof(struct sound_trigger_module_descriptor)); } free(modules); return NO_ERROR; } case ATTACH: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); sound_trigger_module_handle_t handle; data.read(&handle, sizeof(sound_trigger_module_handle_t)); sp<ISoundTriggerClient> client = interface_cast<ISoundTriggerClient>(data.readStrongBinder()); sp<ISoundTrigger> module; status_t status = attach(handle, client, module); reply->writeInt32(status); if (module != 0) { reply->writeInt32(1); reply->writeStrongBinder(IInterface::asBinder(module)); } else { reply->writeInt32(0); } return NO_ERROR; } break; case SET_CAPTURE_STATE: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); reply->writeInt32(setCaptureState((bool)data.readInt32())); return NO_ERROR; } break; default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: Check memory allocation in ISoundTriggerHwService Add memory allocation check in ISoundTriggerHwService::listModules(). Bug: 19385640. Change-Id: Iaf74b6f154c3437e1bfc9da78b773d64b16a7604 CWE ID: CWE-190
status_t BnSoundTriggerHwService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case LIST_MODULES: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); unsigned int numModulesReq = data.readInt32(); if (numModulesReq > MAX_ITEMS_PER_LIST) { numModulesReq = MAX_ITEMS_PER_LIST; } unsigned int numModules = numModulesReq; struct sound_trigger_module_descriptor *modules = (struct sound_trigger_module_descriptor *)calloc(numModulesReq, sizeof(struct sound_trigger_module_descriptor)); if (modules == NULL) { reply->writeInt32(NO_MEMORY); reply->writeInt32(0); return NO_ERROR; } status_t status = listModules(modules, &numModules); reply->writeInt32(status); reply->writeInt32(numModules); ALOGV("LIST_MODULES status %d got numModules %d", status, numModules); if (status == NO_ERROR) { if (numModulesReq > numModules) { numModulesReq = numModules; } reply->write(modules, numModulesReq * sizeof(struct sound_trigger_module_descriptor)); } free(modules); return NO_ERROR; } case ATTACH: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); sound_trigger_module_handle_t handle; data.read(&handle, sizeof(sound_trigger_module_handle_t)); sp<ISoundTriggerClient> client = interface_cast<ISoundTriggerClient>(data.readStrongBinder()); sp<ISoundTrigger> module; status_t status = attach(handle, client, module); reply->writeInt32(status); if (module != 0) { reply->writeInt32(1); reply->writeStrongBinder(IInterface::asBinder(module)); } else { reply->writeInt32(0); } return NO_ERROR; } break; case SET_CAPTURE_STATE: { CHECK_INTERFACE(ISoundTriggerHwService, data, reply); reply->writeInt32(setCaptureState((bool)data.readInt32())); return NO_ERROR; } break; default: return BBinder::onTransact(code, data, reply, flags); } }
174,072
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 install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; } 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
int install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; if (new->thread_keyring) return 0; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; }
168,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 libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code, const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data-structure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count)); /* init column idx */ for ( l_i = 0; l_i <= *o_row_count; ++l_i ) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC ); fclose( l_csr_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN ); return; } if ( l_row_idx_id != NULL ) { /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ free( l_row_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
void libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code, const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC data-structure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count)); /* init column idx */ for ( l_i = 0; l_i <= *o_row_count; ++l_i ) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC ); fclose( l_csr_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS ); return; } /* adjust numbers to zero termination */ LIBXSMM_ASSERT(0 != l_row && 0 != l_column); l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN ); return; } if ( l_row_idx_id != NULL ) { /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ free( l_row_idx_id ); } }
168,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: bool GrabWindowSnapshot(gfx::NativeWindow window, std::vector<unsigned char>* png_representation, const gfx::Rect& snapshot_bounds) { ui::Compositor* compositor = window->layer()->GetCompositor(); gfx::Rect read_pixels_bounds = snapshot_bounds; read_pixels_bounds.set_origin( snapshot_bounds.origin().Add(window->bounds().origin())); gfx::Rect read_pixels_bounds_in_pixel = ui::ConvertRectToPixel(window->layer(), read_pixels_bounds); DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right()); DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom()); DCHECK_LE(0, read_pixels_bounds.x()); DCHECK_LE(0, read_pixels_bounds.y()); SkBitmap bitmap; if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel)) return false; unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels()); gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA, read_pixels_bounds_in_pixel.size(), bitmap.rowBytes(), true, std::vector<gfx::PNGCodec::Comment>(), png_representation); return true; } Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS. BUG=119492 TEST=manually done Review URL: https://chromiumcodereview.appspot.com/10386124 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GrabWindowSnapshot(gfx::NativeWindow window, std::vector<unsigned char>* png_representation, const gfx::Rect& snapshot_bounds) { #if defined(OS_LINUX) // We use XGetImage() for Linux/ChromeOS for performance reasons. // See crbug.com/122720 if (window->GetRootWindow()->GrabSnapshot( snapshot_bounds, png_representation)) return true; #endif // OS_LINUX ui::Compositor* compositor = window->layer()->GetCompositor(); gfx::Rect read_pixels_bounds = snapshot_bounds; read_pixels_bounds.set_origin( snapshot_bounds.origin().Add(window->bounds().origin())); gfx::Rect read_pixels_bounds_in_pixel = ui::ConvertRectToPixel(window->layer(), read_pixels_bounds); DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right()); DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom()); DCHECK_LE(0, read_pixels_bounds.x()); DCHECK_LE(0, read_pixels_bounds.y()); SkBitmap bitmap; if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel)) return false; unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels()); gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA, read_pixels_bounds_in_pixel.size(), bitmap.rowBytes(), true, std::vector<gfx::PNGCodec::Comment>(), png_representation); return true; }
170,760
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: sp<VBRISeeker> VBRISeeker::CreateFromSource( const sp<DataSource> &source, off64_t post_id3_pos) { off64_t pos = post_id3_pos; uint8_t header[4]; ssize_t n = source->readAt(pos, header, sizeof(header)); if (n < (ssize_t)sizeof(header)) { return NULL; } uint32_t tmp = U32_AT(&header[0]); size_t frameSize; int sampleRate; if (!GetMPEGAudioFrameSize(tmp, &frameSize, &sampleRate)) { return NULL; } pos += sizeof(header) + 32; uint8_t vbriHeader[26]; n = source->readAt(pos, vbriHeader, sizeof(vbriHeader)); if (n < (ssize_t)sizeof(vbriHeader)) { return NULL; } if (memcmp(vbriHeader, "VBRI", 4)) { return NULL; } size_t numFrames = U32_AT(&vbriHeader[14]); int64_t durationUs = numFrames * 1000000ll * (sampleRate >= 32000 ? 1152 : 576) / sampleRate; ALOGV("duration = %.2f secs", durationUs / 1E6); size_t numEntries = U16_AT(&vbriHeader[18]); size_t entrySize = U16_AT(&vbriHeader[22]); size_t scale = U16_AT(&vbriHeader[20]); ALOGV("%zu entries, scale=%zu, size_per_entry=%zu", numEntries, scale, entrySize); size_t totalEntrySize = numEntries * entrySize; uint8_t *buffer = new uint8_t[totalEntrySize]; n = source->readAt(pos + sizeof(vbriHeader), buffer, totalEntrySize); if (n < (ssize_t)totalEntrySize) { delete[] buffer; buffer = NULL; return NULL; } sp<VBRISeeker> seeker = new VBRISeeker; seeker->mBasePos = post_id3_pos + frameSize; if (durationUs) { seeker->mDurationUs = durationUs; } off64_t offset = post_id3_pos; for (size_t i = 0; i < numEntries; ++i) { uint32_t numBytes; switch (entrySize) { case 1: numBytes = buffer[i]; break; case 2: numBytes = U16_AT(buffer + 2 * i); break; case 3: numBytes = U24_AT(buffer + 3 * i); break; default: { CHECK_EQ(entrySize, 4u); numBytes = U32_AT(buffer + 4 * i); break; } } numBytes *= scale; seeker->mSegments.push(numBytes); ALOGV("entry #%zu: %u offset %#016llx", i, numBytes, (long long)offset); offset += numBytes; } delete[] buffer; buffer = NULL; ALOGI("Found VBRI header."); return seeker; } Commit Message: Make VBRISeeker more robust Bug: 32577290 Change-Id: I9bcc9422ae7dd3ae4a38df330c9dcd7ac4941ec8 (cherry picked from commit 7fdd36418e945cf6a500018632dfb0ed8cb1a343) CWE ID:
sp<VBRISeeker> VBRISeeker::CreateFromSource( const sp<DataSource> &source, off64_t post_id3_pos) { off64_t pos = post_id3_pos; uint8_t header[4]; ssize_t n = source->readAt(pos, header, sizeof(header)); if (n < (ssize_t)sizeof(header)) { return NULL; } uint32_t tmp = U32_AT(&header[0]); size_t frameSize; int sampleRate; if (!GetMPEGAudioFrameSize(tmp, &frameSize, &sampleRate)) { return NULL; } pos += sizeof(header) + 32; uint8_t vbriHeader[26]; n = source->readAt(pos, vbriHeader, sizeof(vbriHeader)); if (n < (ssize_t)sizeof(vbriHeader)) { return NULL; } if (memcmp(vbriHeader, "VBRI", 4)) { return NULL; } size_t numFrames = U32_AT(&vbriHeader[14]); int64_t durationUs = numFrames * 1000000ll * (sampleRate >= 32000 ? 1152 : 576) / sampleRate; ALOGV("duration = %.2f secs", durationUs / 1E6); size_t numEntries = U16_AT(&vbriHeader[18]); size_t entrySize = U16_AT(&vbriHeader[22]); size_t scale = U16_AT(&vbriHeader[20]); ALOGV("%zu entries, scale=%zu, size_per_entry=%zu", numEntries, scale, entrySize); if (entrySize > 4) { ALOGE("invalid VBRI entry size: %zu", entrySize); return NULL; } sp<VBRISeeker> seeker = new (std::nothrow) VBRISeeker; if (seeker == NULL) { ALOGW("Couldn't allocate VBRISeeker"); return NULL; } size_t totalEntrySize = numEntries * entrySize; uint8_t *buffer = new (std::nothrow) uint8_t[totalEntrySize]; if (!buffer) { ALOGW("Couldn't allocate %zu bytes", totalEntrySize); return NULL; } n = source->readAt(pos + sizeof(vbriHeader), buffer, totalEntrySize); if (n < (ssize_t)totalEntrySize) { delete[] buffer; buffer = NULL; return NULL; } seeker->mBasePos = post_id3_pos + frameSize; if (durationUs) { seeker->mDurationUs = durationUs; } off64_t offset = post_id3_pos; for (size_t i = 0; i < numEntries; ++i) { uint32_t numBytes; switch (entrySize) { case 1: numBytes = buffer[i]; break; case 2: numBytes = U16_AT(buffer + 2 * i); break; case 3: numBytes = U24_AT(buffer + 3 * i); break; default: { CHECK_EQ(entrySize, 4u); numBytes = U32_AT(buffer + 4 * i); break; } } numBytes *= scale; seeker->mSegments.push(numBytes); ALOGV("entry #%zu: %u offset %#016llx", i, numBytes, (long long)offset); offset += numBytes; } delete[] buffer; buffer = NULL; ALOGI("Found VBRI header."); return seeker; }
174,069
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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader == NULL) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; continue; } PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); ++mInputBufferCount; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } return; } uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; uint32_t *start_code = (uint32_t *)bitstream; bool volHeader = *start_code == 0xB0010000; if (volHeader) { PVCleanUpVideoDecoder(mHandle); mInitialized = false; } if (!mInitialized) { uint8_t *vol_data[1]; int32_t vol_size = 0; vol_data[0] = NULL; if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { vol_data[0] = bitstream; vol_size = inHeader->nFilledLen; } MP4DecodingMode mode = (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; Bool success = PVInitVideoDecoder( mHandle, vol_data, &vol_size, 1, outputBufferWidth(), outputBufferHeight(), mode); if (!success) { ALOGW("PVInitVideoDecoder failed. Unsupported content?"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); if (mode != actualMode) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetPostProcType((VideoDecControls *) mHandle, 0); bool hasFrameData = false; if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } else if (volHeader) { hasFrameData = true; } mInitialized = true; if (mode == MPEG4_MODE && handlePortSettingsChange()) { return; } if (!hasFrameData) { continue; } } if (!mFramesConfigured) { PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; OMX_U32 yFrameSize = sizeof(uint8) * mHandle->size; if ((outHeader->nAllocLen < yFrameSize) || (outHeader->nAllocLen - yFrameSize < yFrameSize / 2)) { ALOGE("Too small output buffer for reference frame: %zu bytes", outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "30033990"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetReferenceYUV(mHandle, outHeader->pBuffer); mFramesConfigured = true; } uint32_t useExtTimestamp = (inHeader->nOffset == 0); uint32_t timestamp = 0xFFFFFFFF; if (useExtTimestamp) { mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); timestamp = mPvTime; mPvTime++; } int32_t bufferSize = inHeader->nFilledLen; int32_t tmp = bufferSize; OMX_U32 frameSize; OMX_U64 yFrameSize = (OMX_U64)mWidth * (OMX_U64)mHeight; if (yFrameSize > ((OMX_U64)UINT32_MAX / 3) * 2) { ALOGE("Frame size too large"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } frameSize = (OMX_U32)(yFrameSize + (yFrameSize / 2)); if (outHeader->nAllocLen < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); ALOGE("Insufficient output buffer size"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (PVDecodeVideoFrame( mHandle, &bitstream, &timestamp, &tmp, &useExtTimestamp, outHeader->pBuffer) != PV_TRUE) { ALOGE("failed to decode video frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (handlePortSettingsChange()) { return; } outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); mPvToOmxTimeMap.removeItem(timestamp); inHeader->nOffset += bufferSize; inHeader->nFilledLen = 0; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } else { outHeader->nFlags = 0; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } ++mInputBufferCount; outHeader->nOffset = 0; outHeader->nFilledLen = frameSize; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mNumSamplesOutput; } } Commit Message: Fix build breakage caused by commit 940829f69b52d6038db66a9c727534636ecc456d. Change-Id: I4776db4a26fb3c31bb994d48788373fe569c812a (cherry picked from commit baa9146401e28c5acf54dea21ddd197f0d3a8fcd) CWE ID: CWE-264
void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader == NULL) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; continue; } PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); ++mInputBufferCount; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } return; } uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; uint32_t *start_code = (uint32_t *)bitstream; bool volHeader = *start_code == 0xB0010000; if (volHeader) { PVCleanUpVideoDecoder(mHandle); mInitialized = false; } if (!mInitialized) { uint8_t *vol_data[1]; int32_t vol_size = 0; vol_data[0] = NULL; if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { vol_data[0] = bitstream; vol_size = inHeader->nFilledLen; } MP4DecodingMode mode = (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; Bool success = PVInitVideoDecoder( mHandle, vol_data, &vol_size, 1, outputBufferWidth(), outputBufferHeight(), mode); if (!success) { ALOGW("PVInitVideoDecoder failed. Unsupported content?"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); if (mode != actualMode) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetPostProcType((VideoDecControls *) mHandle, 0); bool hasFrameData = false; if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } else if (volHeader) { hasFrameData = true; } mInitialized = true; if (mode == MPEG4_MODE && handlePortSettingsChange()) { return; } if (!hasFrameData) { continue; } } if (!mFramesConfigured) { PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; OMX_U32 yFrameSize = sizeof(uint8) * mHandle->size; if ((outHeader->nAllocLen < yFrameSize) || (outHeader->nAllocLen - yFrameSize < yFrameSize / 2)) { ALOGE("Too small output buffer for reference frame: %lu bytes", (unsigned long)outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "30033990"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetReferenceYUV(mHandle, outHeader->pBuffer); mFramesConfigured = true; } uint32_t useExtTimestamp = (inHeader->nOffset == 0); uint32_t timestamp = 0xFFFFFFFF; if (useExtTimestamp) { mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); timestamp = mPvTime; mPvTime++; } int32_t bufferSize = inHeader->nFilledLen; int32_t tmp = bufferSize; OMX_U32 frameSize; OMX_U64 yFrameSize = (OMX_U64)mWidth * (OMX_U64)mHeight; if (yFrameSize > ((OMX_U64)UINT32_MAX / 3) * 2) { ALOGE("Frame size too large"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } frameSize = (OMX_U32)(yFrameSize + (yFrameSize / 2)); if (outHeader->nAllocLen < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); ALOGE("Insufficient output buffer size"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (PVDecodeVideoFrame( mHandle, &bitstream, &timestamp, &tmp, &useExtTimestamp, outHeader->pBuffer) != PV_TRUE) { ALOGE("failed to decode video frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (handlePortSettingsChange()) { return; } outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); mPvToOmxTimeMap.removeItem(timestamp); inHeader->nOffset += bufferSize; inHeader->nFilledLen = 0; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } else { outHeader->nFlags = 0; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } ++mInputBufferCount; outHeader->nOffset = 0; outHeader->nFilledLen = frameSize; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mNumSamplesOutput; } }
174,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: static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } Commit Message: tun: allow positive return values on dev_get_valid_name() call If the name argument of dev_get_valid_name() contains "%d", it will try to assign it a unit number in __dev__alloc_name() and return either the unit number (>= 0) or an error code (< 0). Considering positive values as error values prevent tun device creations relying this mechanism, therefor we should only consider negative values as errors here. Signed-off-by: Julien Gomes <[email protected]> Acked-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476
static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err < 0) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; }
170,247
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: TransformPaintPropertyNode* TransformPaintPropertyNode::Root() { DEFINE_STATIC_REF( TransformPaintPropertyNode, root, base::AdoptRef(new TransformPaintPropertyNode( nullptr, State{TransformationMatrix(), FloatPoint3D(), false, BackfaceVisibility::kVisible, 0, CompositingReason::kNone, CompositorElementId(), ScrollPaintPropertyNode::Root()}))); return root; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
TransformPaintPropertyNode* TransformPaintPropertyNode::Root() { const TransformPaintPropertyNode& TransformPaintPropertyNode::Root() { DEFINE_STATIC_LOCAL( TransformPaintPropertyNode, root, (nullptr, State{TransformationMatrix(), FloatPoint3D(), false, BackfaceVisibility::kVisible, 0, CompositingReason::kNone, CompositorElementId(), &ScrollPaintPropertyNode::Root()})); return root; }
171,844
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 em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel; memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS); if (rc != X86EMUL_CONTINUE) return rc; ctxt->_eip = 0; memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Handle errors when RIP is set during far jumps Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not handle this case, and may result in failed vm-entry once the assignment is done. The tricky part of doing so is that loading the new CS affects the VMCS/VMCB state, so if we fail during loading the new RIP, we are left in unconsistent state. Therefore, this patch saves on 64-bit the old CS descriptor and restores it if loading RIP failed. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel, old_sel; struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; u8 cpl = ctxt->ops->cpl(ctxt); /* Assignment of RIP may only fail in 64-bit mode */ if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_sel, &old_desc, NULL, VCPU_SREG_CS); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l); if (rc != X86EMUL_CONTINUE) { WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64); /* assigning eip failed; restore the old cs */ ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS); return rc; } return rc; }
166,339
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 RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy, int64 https_length_with_data_reduction_enabled, int64 short_bypass_length_with_data_reduction_enabled, int64 long_bypass_length_with_data_reduction_enabled, int64 unknown_length_with_data_reduction_enabled) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (https_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_Https", https_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_Https", (100 * https_length_with_data_reduction_enabled) / received_length); } if (short_bypass_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_ShortBypass", short_bypass_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_ShortBypass", ((100 * short_bypass_length_with_data_reduction_enabled) / received_length)); } if (long_bypass_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_LongBypass", long_bypass_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_LongBypass", ((100 * long_bypass_length_with_data_reduction_enabled) / received_length)); } if (unknown_length_with_data_reduction_enabled > 0) { UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled_Unknown", unknown_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled_Unknown", ((100 * unknown_length_with_data_reduction_enabled) / received_length)); } if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); }
171,326
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_binheader_writef (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; sf_count_t countdata ; unsigned long longdata ; unsigned int data ; float floatdata ; double doubledata ; void *bindata ; size_t size ; char c, *strptr ; int count = 0, trunc_8to4 ; trunc_8to4 = SF_FALSE ; va_start (argptr, format) ; while ((c = *format++)) { switch (c) { case ' ' : /* Do nothing. Just used to space out format string. */ break ; case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 't' : /* All 8 byte values now get written as 4 bytes. */ trunc_8to4 = SF_TRUE ; break ; case 'T' : /* All 8 byte values now get written as 8 bytes. */ trunc_8to4 = SF_FALSE ; break ; case 'm' : data = va_arg (argptr, unsigned int) ; header_put_marker (psf, data) ; count += 4 ; break ; case '1' : data = va_arg (argptr, unsigned int) ; header_put_byte (psf, data) ; count += 1 ; break ; case '2' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_short (psf, data) ; } else { header_put_le_short (psf, data) ; } ; count += 2 ; break ; case '3' : /* tribyte */ data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_3byte (psf, data) ; } else { header_put_le_3byte (psf, data) ; } ; count += 3 ; break ; case '4' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_int (psf, data) ; } else { header_put_le_int (psf, data) ; } ; count += 4 ; break ; case '8' : countdata = va_arg (argptr, sf_count_t) ; if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_FALSE) { header_put_be_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_FALSE) { header_put_le_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_be_int (psf, longdata) ; count += 4 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_le_int (psf, longdata) ; count += 4 ; } break ; case 'f' : /* Floats are passed as doubles. Is this always true? */ floatdata = (float) va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) float32_be_write (floatdata, psf->header + psf->headindex) ; else float32_le_write (floatdata, psf->header + psf->headindex) ; psf->headindex += 4 ; count += 4 ; break ; case 'd' : doubledata = va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) double64_be_write (doubledata, psf->header + psf->headindex) ; else double64_le_write (doubledata, psf->header + psf->headindex) ; psf->headindex += 8 ; count += 8 ; break ; case 's' : /* Write a C string (guaranteed to have a zero terminator). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; psf->header [psf->headindex - 1] = 0 ; count += 4 + size ; break ; case 'S' : /* ** Write an AIFF style string (no zero terminator but possibly ** an extra pad byte if the string length is odd). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size + 1) ; size += (size & 1) ; psf->headindex += size ; psf->header [psf->headindex] = 0 ; count += 4 + size ; break ; case 'p' : /* Write a PASCAL string (as used by AIFF files). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; size = (size & 1) ? size : size + 1 ; size = (size > 254) ? 254 : size ; header_put_byte (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; count += 1 + size ; break ; case 'b' : bindata = va_arg (argptr, void *) ; size = va_arg (argptr, size_t) ; if (psf->headindex + size < sizeof (psf->header)) { memcpy (&(psf->header [psf->headindex]), bindata, size) ; psf->headindex += size ; count += size ; } ; break ; case 'z' : size = va_arg (argptr, size_t) ; count += size ; while (size) { psf->header [psf->headindex] = 0 ; psf->headindex ++ ; size -- ; } ; break ; case 'h' : bindata = va_arg (argptr, void *) ; memcpy (&(psf->header [psf->headindex]), bindata, 16) ; psf->headindex += 16 ; count += 16 ; break ; case 'j' : /* Jump forwards/backwards by specified amount. */ size = va_arg (argptr, size_t) ; psf->headindex += size ; count += size ; break ; case 'o' : /* Jump to specified offset. */ size = va_arg (argptr, size_t) ; if (size < sizeof (psf->header)) { psf->headindex = size ; count = 0 ; } ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return count ; } /* psf_binheader_writef */ 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
psf_binheader_writef (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; sf_count_t countdata ; unsigned long longdata ; unsigned int data ; float floatdata ; double doubledata ; void *bindata ; size_t size ; char c, *strptr ; int count = 0, trunc_8to4 ; trunc_8to4 = SF_FALSE ; va_start (argptr, format) ; while ((c = *format++)) { if (psf->header.indx + 16 >= psf->header.len && psf_bump_header_allocation (psf, 16)) return count ; switch (c) { case ' ' : /* Do nothing. Just used to space out format string. */ break ; case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 't' : /* All 8 byte values now get written as 4 bytes. */ trunc_8to4 = SF_TRUE ; break ; case 'T' : /* All 8 byte values now get written as 8 bytes. */ trunc_8to4 = SF_FALSE ; break ; case 'm' : data = va_arg (argptr, unsigned int) ; header_put_marker (psf, data) ; count += 4 ; break ; case '1' : data = va_arg (argptr, unsigned int) ; header_put_byte (psf, data) ; count += 1 ; break ; case '2' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_short (psf, data) ; } else { header_put_le_short (psf, data) ; } ; count += 2 ; break ; case '3' : /* tribyte */ data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_3byte (psf, data) ; } else { header_put_le_3byte (psf, data) ; } ; count += 3 ; break ; case '4' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_int (psf, data) ; } else { header_put_le_int (psf, data) ; } ; count += 4 ; break ; case '8' : countdata = va_arg (argptr, sf_count_t) ; if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_FALSE) { header_put_be_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_FALSE) { header_put_le_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_be_int (psf, longdata) ; count += 4 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_le_int (psf, longdata) ; count += 4 ; } break ; case 'f' : /* Floats are passed as doubles. Is this always true? */ floatdata = (float) va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) float32_be_write (floatdata, psf->header.ptr + psf->header.indx) ; else float32_le_write (floatdata, psf->header.ptr + psf->header.indx) ; psf->header.indx += 4 ; count += 4 ; break ; case 'd' : doubledata = va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) double64_be_write (doubledata, psf->header.ptr + psf->header.indx) ; else double64_le_write (doubledata, psf->header.ptr + psf->header.indx) ; psf->header.indx += 8 ; count += 8 ; break ; case 's' : /* Write a C string (guaranteed to have a zero terminator). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; if (psf->header.indx + (sf_count_t) size >= psf->header.len && psf_bump_header_allocation (psf, 16)) return count ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ; psf->header.indx += size ; psf->header.ptr [psf->header.indx - 1] = 0 ; count += 4 + size ; break ; case 'S' : /* ** Write an AIFF style string (no zero terminator but possibly ** an extra pad byte if the string length is odd). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size)) return count ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size + 1) ; size += (size & 1) ; psf->header.indx += size ; psf->header.ptr [psf->header.indx] = 0 ; count += 4 + size ; break ; case 'p' : /* Write a PASCAL string (as used by AIFF files). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; size = (size & 1) ? size : size + 1 ; size = (size > 254) ? 254 : size ; if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size)) return count ; header_put_byte (psf, size) ; memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ; psf->header.indx += size ; count += 1 + size ; break ; case 'b' : bindata = va_arg (argptr, void *) ; size = va_arg (argptr, size_t) ; if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size)) return count ; memcpy (&(psf->header.ptr [psf->header.indx]), bindata, size) ; psf->header.indx += size ; count += size ; break ; case 'z' : size = va_arg (argptr, size_t) ; if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size)) return count ; count += size ; while (size) { psf->header.ptr [psf->header.indx] = 0 ; psf->header.indx ++ ; size -- ; } ; break ; case 'h' : bindata = va_arg (argptr, void *) ; memcpy (&(psf->header.ptr [psf->header.indx]), bindata, 16) ; psf->header.indx += 16 ; count += 16 ; break ; case 'j' : /* Jump forwards/backwards by specified amount. */ size = va_arg (argptr, size_t) ; if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size)) return count ; psf->header.indx += size ; count += size ; break ; case 'o' : /* Jump to specified offset. */ size = va_arg (argptr, size_t) ; if ((sf_count_t) size >= psf->header.len && psf_bump_header_allocation (psf, size)) return count ; psf->header.indx = size ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return count ; } /* psf_binheader_writef */
170,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> uniformHelperi(const v8::Arguments& args, FunctionToCall functionToCall) { if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(); WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } bool ok = false; WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok); if (V8Int32Array::HasInstance(args[1])) { Int32Array* array = V8Int32Array::toNative(args[1]->ToObject()); ASSERT(array != NULL); ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1iv(location, array, ec); break; case kUniform2v: context->uniform2iv(location, array, ec); break; case kUniform3v: context->uniform3iv(location, array, ec); break; case kUniform4v: context->uniform4iv(location, array, ec); break; default: ASSERT_NOT_REACHED(); break; } if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } if (args[1].IsEmpty() || !args[1]->IsArray()) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } v8::Handle<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); uint32_t len = array->Length(); int* data = jsArrayToIntArray(array, len); if (!data) { V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate()); return notHandledByInterceptor(); } ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1iv(location, data, len, ec); break; case kUniform2v: context->uniform2iv(location, data, len, ec); break; case kUniform3v: context->uniform3iv(location, data, len, ec); break; case kUniform4v: context->uniform4iv(location, data, len, ec); break; default: ASSERT_NOT_REACHED(); break; } fastFree(data); if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> uniformHelperi(const v8::Arguments& args, FunctionToCall functionToCall) { if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } bool ok = false; WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok); if (V8Int32Array::HasInstance(args[1])) { Int32Array* array = V8Int32Array::toNative(args[1]->ToObject()); ASSERT(array != NULL); ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1iv(location, array, ec); break; case kUniform2v: context->uniform2iv(location, array, ec); break; case kUniform3v: context->uniform3iv(location, array, ec); break; case kUniform4v: context->uniform4iv(location, array, ec); break; default: ASSERT_NOT_REACHED(); break; } if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } if (args[1].IsEmpty() || !args[1]->IsArray()) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } v8::Handle<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); uint32_t len = array->Length(); int* data = jsArrayToIntArray(array, len); if (!data) { V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate()); return notHandledByInterceptor(); } ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1iv(location, data, len, ec); break; case kUniform2v: context->uniform2iv(location, data, len, ec); break; case kUniform3v: context->uniform3iv(location, data, len, ec); break; case kUniform4v: context->uniform4iv(location, data, len, ec); break; default: ASSERT_NOT_REACHED(); break; } fastFree(data); if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); }
171,128
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 TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } Commit Message: Allow origin lock for WebUI pages. Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps to keep enforcing a SiteInstance swap during chrome://foo -> chrome://bar navigation, even after relaxing BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost (see https://crrev.com/c/783470 for that fixes process sharing in isolated(b(c),d(c)) scenario). I've manually tested this CL by visiting the following URLs: - chrome://welcome/ - chrome://settings - chrome://extensions - chrome://history - chrome://help and chrome://chrome (both redirect to chrome://settings/help) Bug: 510588, 847127 Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971 Reviewed-on: https://chromium-review.googlesource.com/1237392 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: François Doray <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#595259} CWE ID: CWE-119
void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); // Create another WebUI tab. Each WebUI tab should get a separate process // because of origin locking. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); }
173,280
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 __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *done_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(done_key); return true; } Commit Message: net: avoid dependency of net_get_random_once on nop patching net_get_random_once depends on the static keys infrastructure to patch up the branch to the slow path during boot. This was realized by abusing the static keys api and defining a new initializer to not enable the call site while still indicating that the branch point should get patched up. This was needed to have the fast path considered likely by gcc. The static key initialization during boot up normally walks through all the registered keys and either patches in ideal nops or enables the jump site but omitted that step on x86 if ideal nops where already placed at static_key branch points. Thus net_get_random_once branches not always became active. This patch switches net_get_random_once to the ordinary static_key api and thus places the kernel fast path in the - by gcc considered - unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that the unlikely path actually beats the likely path in terms of cycle cost and that different nop patterns did not make much difference, thus this switch should not be noticeable. Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once") Reported-by: Tuomas Räsänen <[email protected]> Cc: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
bool __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *once_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(once_key); return true; }
166,258
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 asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { asn1_write(data, s->data, s->length); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { return asn1_write(data, s->data, s->length); }
164,588
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) { const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } 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() == 0) encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
174,515
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: FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, chromium::web::FrameObserverPtr observer) : web_contents_(std::move(web_contents)), observer_(std::move(observer)) { Observe(web_contents.get()); } 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
FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, ContextImpl* context, fidl::InterfaceRequest<chromium::web::Frame> frame_request) : web_contents_(std::move(web_contents)), context_(context), binding_(this, std::move(frame_request)) { binding_.set_error_handler([this]() { context_->DestroyFrame(this); }); Observe(web_contents_.get()); }
172,152
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 PageRequestSummary::UpdateOrAddToOrigins( const GURL& url, const content::mojom::CommonNetworkInfoPtr& network_info) { GURL origin = url.GetOrigin(); if (!origin.is_valid()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PageRequestSummary::UpdateOrAddToOrigins( const url::Origin& origin, const content::mojom::CommonNetworkInfoPtr& network_info) { if (origin.opaque()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; }
172,368
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 sas_discover_end_dev(struct domain_device *dev) { int res; res = sas_notify_lldd_dev_found(dev); if (res) return res; sas_discover_event(dev->port, DISCE_PROBE); return 0; } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID:
int sas_discover_end_dev(struct domain_device *dev) { int res; res = sas_notify_lldd_dev_found(dev); if (res) return res; return 0; }
169,386
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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width); } } else { if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; return SET_IVD_FATAL_ERROR(e_error); } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Fix in handling header decode errors If header decode was unsuccessful, do not try decoding a frame Also, initialize pic_wd, pic_ht for reinitialization when decoder is created with smaller dimensions Bug: 28886651 Bug: 35219737 Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50 (cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27) (cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4) CWE ID: CWE-119
IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width); } } else { if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size; ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size; return e_error; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
174,033
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 testRandomDecodeAfterClearFrameBufferCache(const char* gifFile) { SCOPED_TRACE(gifFile); RefPtr<SharedBuffer> data = readFile(gifFile); ASSERT_TRUE(data.get()); Vector<unsigned> baselineHashes; createDecodingBaseline(data.get(), &baselineHashes); size_t frameCount = baselineHashes.size(); OwnPtr<GIFImageDecoder> decoder = createDecoder(); decoder->setData(data.get(), true); for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) { decoder->clearCacheExceptFrame(clearExceptFrame); const size_t skippingStep = 5; for (size_t i = 0; i < skippingStep; ++i) { for (size_t j = 0; j < frameCount; j += skippingStep) { SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j); ImageFrame* frame = decoder->frameBufferAtIndex(j); EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap())); } } } } Commit Message: Fix handling of broken GIFs with weird frame sizes Code didn't handle well if a GIF frame has dimension greater than the "screen" dimension. This will break deferred image decoding. This change reports the size as final only when the first frame is encountered. Added a test to verify this behavior. Frame size reported by the decoder should be constant. BUG=437651 [email protected], [email protected] Review URL: https://codereview.chromium.org/813943003 git-svn-id: svn://svn.chromium.org/blink/trunk@188423 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void testRandomDecodeAfterClearFrameBufferCache(const char* gifFile) void testRandomDecodeAfterClearFrameBufferCache(const char* dir, const char* gifFile) { SCOPED_TRACE(gifFile); RefPtr<SharedBuffer> data = readFile(dir, gifFile); ASSERT_TRUE(data.get()); Vector<unsigned> baselineHashes; createDecodingBaseline(data.get(), &baselineHashes); size_t frameCount = baselineHashes.size(); OwnPtr<GIFImageDecoder> decoder = createDecoder(); decoder->setData(data.get(), true); for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) { decoder->clearCacheExceptFrame(clearExceptFrame); const size_t skippingStep = 5; for (size_t i = 0; i < skippingStep; ++i) { for (size_t j = 0; j < frameCount; j += skippingStep) { SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j); ImageFrame* frame = decoder->frameBufferAtIndex(j); EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap())); } } } }
172,027
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_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */
167,112
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: main(int argc, char **argv) { int i, gn; int test = 0; char *action = NULL, *cmd; char *output = NULL; #ifdef HAVE_EEZE_MOUNT Eina_Bool mnt = EINA_FALSE; const char *act; #endif gid_t gid, gl[65536], egid; for (i = 1; i < argc; i++) { if ((!strcmp(argv[i], "-h")) || (!strcmp(argv[i], "-help")) || (!strcmp(argv[i], "--help"))) { printf( "This is an internal tool for Enlightenment.\n" "do not use it.\n" ); exit(0); } } if (argc >= 3) { if ((argc == 3) && (!strcmp(argv[1], "-t"))) { test = 1; action = argv[2]; } else if (!strcmp(argv[1], "l2ping")) { action = argv[1]; output = argv[2]; } #ifdef HAVE_EEZE_MOUNT else { const char *s; s = strrchr(argv[1], '/'); if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */ s++; if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1); mnt = EINA_TRUE; act = s; action = argv[1]; } #endif } else if (argc == 2) { action = argv[1]; } else { exit(1); } if (!action) exit(1); fprintf(stderr, "action %s %i\n", action, argc); uid = getuid(); gid = getgid(); egid = getegid(); gn = getgroups(65536, gl); if (gn < 0) { printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n"); exit(3); } if (setuid(0) != 0) { printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n"); exit(5); } if (setgid(0) != 0) { printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n"); exit(7); } eina_init(); if (!auth_action_ok(action, gid, gl, gn, egid)) { printf("ERROR: ACTION NOT ALLOWED: %s\n", action); exit(10); } /* we can add more levels of auth here */ /* when mounting, this will match the exact path to the exe, * as required in sysactions.conf * this is intentionally pedantic for security */ cmd = eina_hash_find(actions, action); if (!cmd) { printf("ERROR: UNDEFINED ACTION: %s\n", action); exit(20); } if (!test && !strcmp(action, "l2ping")) { char tmp[128]; double latency; latency = e_sys_l2ping(output); eina_convert_dtoa(latency, tmp); fputs(tmp, stdout); return (latency < 0) ? 1 : 0; } /* sanitize environment */ #ifdef HAVE_UNSETENV # define NOENV(x) unsetenv(x) #else # define NOENV(x) #endif NOENV("IFS"); /* sanitize environment */ #ifdef HAVE_UNSETENV # define NOENV(x) unsetenv(x) #else # define NOENV(x) #endif NOENV("IFS"); NOENV("LD_PRELOAD"); NOENV("PYTHONPATH"); NOENV("LD_LIBRARY_PATH"); #ifdef HAVE_CLEARENV clearenv(); #endif /* set path and ifs to minimal defaults */ putenv("PATH=/bin:/usr/bin"); putenv("IFS= \t\n"); const char *p; char *end; unsigned long muid; Eina_Bool nosuid, nodev, noexec, nuid; nosuid = nodev = noexec = nuid = EINA_FALSE; /* these are the only possible options which can be present here; check them strictly */ if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE; for (p = buf; p && p[1]; p = strchr(p + 1, ',')) { if (p[0] == ',') p++; #define CMP(OPT) \ if (!strncmp(p, OPT, sizeof(OPT) - 1)) CMP("nosuid,") { nosuid = EINA_TRUE; continue; } CMP("nodev,") { nodev = EINA_TRUE; continue; } CMP("noexec,") { noexec = EINA_TRUE; continue; } CMP("utf8,") continue; CMP("utf8=0,") continue; CMP("utf8=1,") continue; CMP("iocharset=utf8,") continue; CMP("uid=") { p += 4; errno = 0; muid = strtoul(p, &end, 10); if (muid == ULONG_MAX) return EINA_FALSE; if (errno) return EINA_FALSE; if (end[0] != ',') return EINA_FALSE; if (muid != uid) return EINA_FALSE; nuid = EINA_TRUE; continue; } return EINA_FALSE; } if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE; return EINA_TRUE; } Commit Message: CWE ID: CWE-264
main(int argc, char **argv) { int i, gn; int test = 0; char *action = NULL, *cmd; char *output = NULL; #ifdef HAVE_EEZE_MOUNT Eina_Bool mnt = EINA_FALSE; const char *act; #endif gid_t gid, gl[65536], egid; for (i = 1; i < argc; i++) { if ((!strcmp(argv[i], "-h")) || (!strcmp(argv[i], "-help")) || (!strcmp(argv[i], "--help"))) { printf( "This is an internal tool for Enlightenment.\n" "do not use it.\n" ); exit(0); } } if (argc >= 3) { if ((argc == 3) && (!strcmp(argv[1], "-t"))) { test = 1; action = argv[2]; } else if (!strcmp(argv[1], "l2ping")) { action = argv[1]; output = argv[2]; } #ifdef HAVE_EEZE_MOUNT else { const char *s; s = strrchr(argv[1], '/'); if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */ s++; if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1); mnt = EINA_TRUE; act = s; action = argv[1]; } #endif } else if (argc == 2) { action = argv[1]; } else { exit(1); } if (!action) exit(1); fprintf(stderr, "action %s %i\n", action, argc); uid = getuid(); gid = getgid(); egid = getegid(); gn = getgroups(65536, gl); if (gn < 0) { printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n"); exit(3); } if (setuid(0) != 0) { printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n"); exit(5); } if (setgid(0) != 0) { printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n"); exit(7); } eina_init(); if (!auth_action_ok(action, gid, gl, gn, egid)) { printf("ERROR: ACTION NOT ALLOWED: %s\n", action); exit(10); } /* we can add more levels of auth here */ /* when mounting, this will match the exact path to the exe, * as required in sysactions.conf * this is intentionally pedantic for security */ cmd = eina_hash_find(actions, action); if (!cmd) { printf("ERROR: UNDEFINED ACTION: %s\n", action); exit(20); } if (!test && !strcmp(action, "l2ping")) { char tmp[128]; double latency; latency = e_sys_l2ping(output); eina_convert_dtoa(latency, tmp); fputs(tmp, stdout); return (latency < 0) ? 1 : 0; } /* sanitize environment */ #ifdef HAVE_UNSETENV # define NOENV(x) unsetenv(x) #else # define NOENV(x) #endif NOENV("IFS"); /* sanitize environment */ #ifdef HAVE_UNSETENV # define NOENV(x) unsetenv(x) /* pass 1 - just nuke known dangerous env vars brutally if possible via * unsetenv(). if you don't have unsetenv... there's pass 2 and 3 */ NOENV("IFS"); NOENV("CDPATH"); NOENV("LOCALDOMAIN"); NOENV("RES_OPTIONS"); NOENV("HOSTALIASES"); NOENV("NLSPATH"); NOENV("PATH_LOCALE"); NOENV("COLORTERM"); NOENV("LANG"); NOENV("LANGUAGE"); NOENV("LINGUAS"); NOENV("TERM"); NOENV("LD_PRELOAD"); NOENV("LD_LIBRARY_PATH"); NOENV("SHLIB_PATH"); NOENV("LIBPATH"); NOENV("AUTHSTATE"); NOENV("DYLD_*"); NOENV("KRB_CONF*"); NOENV("KRBCONFDIR"); NOENV("KRBTKFILE"); NOENV("KRB5_CONFIG*"); NOENV("KRB5_KTNAME"); NOENV("VAR_ACE"); NOENV("USR_ACE"); NOENV("DLC_ACE"); NOENV("TERMINFO"); NOENV("TERMINFO_DIRS"); NOENV("TERMPATH"); NOENV("TERMCAP"); NOENV("ENV"); NOENV("BASH_ENV"); NOENV("PS4"); NOENV("GLOBIGNORE"); NOENV("SHELLOPTS"); NOENV("JAVA_TOOL_OPTIONS"); NOENV("PERLIO_DEBUG"); NOENV("PERLLIB"); NOENV("PERL5LIB"); NOENV("PERL5OPT"); NOENV("PERL5DB"); NOENV("FPATH"); NOENV("NULLCMD"); NOENV("READNULLCMD"); NOENV("ZDOTDIR"); NOENV("TMPPREFIX"); NOENV("PYTHONPATH"); NOENV("PYTHONHOME"); NOENV("PYTHONINSPECT"); NOENV("RUBYLIB"); NOENV("RUBYOPT"); # ifdef HAVE_ENVIRON if (environ) { int again; char *tmp, *p; /* go over environment array again and again... safely */ do { again = 0; /* walk through and find first entry that we don't like */ for (i = 0; environ[i]; i++) { /* if it begins with any of these, it's possibly nasty */ if ((!strncmp(environ[i], "LD_", 3)) || (!strncmp(environ[i], "_RLD_", 5)) || (!strncmp(environ[i], "LC_", 3)) || (!strncmp(environ[i], "LDR_", 3))) { /* unset it */ tmp = strdup(environ[i]); if (!tmp) abort(); p = strchr(tmp, '='); if (!p) abort(); *p = 0; NOENV(p); free(tmp); /* and mark our do to try again from the start in case * unsetenv changes environ ptr */ again = 1; break; } } } while (again); } # endif #endif /* pass 2 - clear entire environment so it doesn't exist at all. if you * can't do this... you're possibly in trouble... but the worst is still * fixed in pass 3 */ #ifdef HAVE_CLEARENV clearenv(); #else # ifdef HAVE_ENVIRON environ = NULL; # endif #endif /* pass 3 - set path and ifs to minimal defaults */ putenv("PATH=/bin:/usr/bin"); putenv("IFS= \t\n"); const char *p; char *end; unsigned long muid; Eina_Bool nosuid, nodev, noexec, nuid; nosuid = nodev = noexec = nuid = EINA_FALSE; /* these are the only possible options which can be present here; check them strictly */ if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE; for (p = buf; p && p[1]; p = strchr(p + 1, ',')) { if (p[0] == ',') p++; #define CMP(OPT) \ if (!strncmp(p, OPT, sizeof(OPT) - 1)) CMP("nosuid,") { nosuid = EINA_TRUE; continue; } CMP("nodev,") { nodev = EINA_TRUE; continue; } CMP("noexec,") { noexec = EINA_TRUE; continue; } CMP("utf8,") continue; CMP("utf8=0,") continue; CMP("utf8=1,") continue; CMP("iocharset=utf8,") continue; CMP("uid=") { p += 4; errno = 0; muid = strtoul(p, &end, 10); if (muid == ULONG_MAX) return EINA_FALSE; if (errno) return EINA_FALSE; if (end[0] != ',') return EINA_FALSE; if (muid != uid) return EINA_FALSE; nuid = EINA_TRUE; continue; } return EINA_FALSE; } if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE; return EINA_TRUE; }
165,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 long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd) { struct socket *sock, *oldsock; struct vhost_virtqueue *vq; struct vhost_net_virtqueue *nvq; struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL; int r; mutex_lock(&n->dev.mutex); r = vhost_dev_check_owner(&n->dev); if (r) goto err; if (index >= VHOST_NET_VQ_MAX) { r = -ENOBUFS; goto err; } vq = &n->vqs[index].vq; nvq = &n->vqs[index]; mutex_lock(&vq->mutex); /* Verify that ring has been setup correctly. */ if (!vhost_vq_access_ok(vq)) { r = -EFAULT; goto err_vq; } sock = get_socket(fd); if (IS_ERR(sock)) { r = PTR_ERR(sock); goto err_vq; } /* start polling new socket */ oldsock = rcu_dereference_protected(vq->private_data, lockdep_is_held(&vq->mutex)); if (sock != oldsock) { ubufs = vhost_net_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock)); if (IS_ERR(ubufs)) { r = PTR_ERR(ubufs); goto err_ubufs; } vhost_net_disable_vq(n, vq); rcu_assign_pointer(vq->private_data, sock); r = vhost_init_used(vq); if (r) goto err_used; r = vhost_net_enable_vq(n, vq); if (r) goto err_used; oldubufs = nvq->ubufs; nvq->ubufs = ubufs; n->tx_packets = 0; n->tx_zcopy_err = 0; n->tx_flush = false; } mutex_unlock(&vq->mutex); if (oldubufs) { vhost_net_ubuf_put_and_wait(oldubufs); mutex_lock(&vq->mutex); vhost_zerocopy_signal_used(n, vq); mutex_unlock(&vq->mutex); } if (oldsock) { vhost_net_flush_vq(n, index); fput(oldsock->file); } mutex_unlock(&n->dev.mutex); return 0; err_used: rcu_assign_pointer(vq->private_data, oldsock); vhost_net_enable_vq(n, vq); if (ubufs) vhost_net_ubuf_put_and_wait(ubufs); err_ubufs: fput(sock->file); err_vq: mutex_unlock(&vq->mutex); err: mutex_unlock(&n->dev.mutex); return r; } Commit Message: vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd) { struct socket *sock, *oldsock; struct vhost_virtqueue *vq; struct vhost_net_virtqueue *nvq; struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL; int r; mutex_lock(&n->dev.mutex); r = vhost_dev_check_owner(&n->dev); if (r) goto err; if (index >= VHOST_NET_VQ_MAX) { r = -ENOBUFS; goto err; } vq = &n->vqs[index].vq; nvq = &n->vqs[index]; mutex_lock(&vq->mutex); /* Verify that ring has been setup correctly. */ if (!vhost_vq_access_ok(vq)) { r = -EFAULT; goto err_vq; } sock = get_socket(fd); if (IS_ERR(sock)) { r = PTR_ERR(sock); goto err_vq; } /* start polling new socket */ oldsock = rcu_dereference_protected(vq->private_data, lockdep_is_held(&vq->mutex)); if (sock != oldsock) { ubufs = vhost_net_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock)); if (IS_ERR(ubufs)) { r = PTR_ERR(ubufs); goto err_ubufs; } vhost_net_disable_vq(n, vq); rcu_assign_pointer(vq->private_data, sock); r = vhost_init_used(vq); if (r) goto err_used; r = vhost_net_enable_vq(n, vq); if (r) goto err_used; oldubufs = nvq->ubufs; nvq->ubufs = ubufs; n->tx_packets = 0; n->tx_zcopy_err = 0; n->tx_flush = false; } mutex_unlock(&vq->mutex); if (oldubufs) { vhost_net_ubuf_put_wait_and_free(oldubufs); mutex_lock(&vq->mutex); vhost_zerocopy_signal_used(n, vq); mutex_unlock(&vq->mutex); } if (oldsock) { vhost_net_flush_vq(n, index); fput(oldsock->file); } mutex_unlock(&n->dev.mutex); return 0; err_used: rcu_assign_pointer(vq->private_data, oldsock); vhost_net_enable_vq(n, vq); if (ubufs) vhost_net_ubuf_put_wait_and_free(ubufs); err_ubufs: fput(sock->file); err_vq: mutex_unlock(&vq->mutex); err: mutex_unlock(&n->dev.mutex); return r; }
166,020
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 CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert, BIO *dcont, BIO *out, unsigned int flags) { int r; BIO *cont; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) { CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA); return 0; } if (!dcont && !check_content(cms)) return 0; if (flags & CMS_DEBUG_DECRYPT) cms->d.envelopedData->encryptedContentInfo->debug = 1; else cms->d.envelopedData->encryptedContentInfo->debug = 0; if (!pk && !cert && !dcont && !out) return 1; if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert)) r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; } Commit Message: CWE ID: CWE-311
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert, BIO *dcont, BIO *out, unsigned int flags) { int r; BIO *cont; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) { CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA); return 0; } if (!dcont && !check_content(cms)) return 0; if (flags & CMS_DEBUG_DECRYPT) cms->d.envelopedData->encryptedContentInfo->debug = 1; else cms->d.envelopedData->encryptedContentInfo->debug = 0; if (!cert) cms->d.envelopedData->encryptedContentInfo->havenocert = 1; else cms->d.envelopedData->encryptedContentInfo->havenocert = 0; if (!pk && !cert && !dcont && !out) return 1; if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert)) r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; }
165,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata) { struct nfs4_state *state = opendata->state; struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *delegation; int open_mode = opendata->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL); nfs4_stateid stateid; int ret = -EAGAIN; for (;;) { if (can_open_cached(state, open_mode)) { spin_lock(&state->owner->so_lock); if (can_open_cached(state, open_mode)) { update_open_stateflags(state, open_mode); spin_unlock(&state->owner->so_lock); goto out_return_state; } spin_unlock(&state->owner->so_lock); } rcu_read_lock(); delegation = rcu_dereference(nfsi->delegation); if (delegation == NULL || !can_open_delegated(delegation, open_mode)) { rcu_read_unlock(); break; } /* Save the delegation */ memcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data)); rcu_read_unlock(); ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode); if (ret != 0) goto out; ret = -EAGAIN; /* Try to update the stateid using the delegation */ if (update_open_stateid(state, NULL, &stateid, open_mode)) goto out_return_state; } out: return ERR_PTR(ret); out_return_state: atomic_inc(&state->count); return state; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata) { struct nfs4_state *state = opendata->state; struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *delegation; int open_mode = opendata->o_arg.open_flags & O_EXCL; fmode_t fmode = opendata->o_arg.fmode; nfs4_stateid stateid; int ret = -EAGAIN; for (;;) { if (can_open_cached(state, fmode, open_mode)) { spin_lock(&state->owner->so_lock); if (can_open_cached(state, fmode, open_mode)) { update_open_stateflags(state, fmode); spin_unlock(&state->owner->so_lock); goto out_return_state; } spin_unlock(&state->owner->so_lock); } rcu_read_lock(); delegation = rcu_dereference(nfsi->delegation); if (delegation == NULL || !can_open_delegated(delegation, fmode)) { rcu_read_unlock(); break; } /* Save the delegation */ memcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data)); rcu_read_unlock(); ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode); if (ret != 0) goto out; ret = -EAGAIN; /* Try to update the stateid using the delegation */ if (update_open_stateid(state, NULL, &stateid, fmode)) goto out_return_state; } out: return ERR_PTR(ret); out_return_state: atomic_inc(&state->count); return state; }
165,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS err = parseVps(data + 2, size - 2); break; case 33: // SPS err = parseSps(data + 2, size - 2); break; case 34: // PPS err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; } Commit Message: Validate lengths in HEVC metadata parsing Add code to validate the size parameter passed to HecvParameterSets::addNalUnit(). Previously vulnerable to decrementing an unsigned past 0, yielding a huge result value. Bug: 35467107 Test: ran POC, no crash, emitted new "bad length" log entry Change-Id: Ia169b9edc1e0f7c5302e3c68aa90a54e8863d79e (cherry picked from commit e0dcf097cc029d056926029a29419e1650cbdf1b) CWE ID: CWE-476
status_t HevcParameterSets::addNalUnit(const uint8_t* data, size_t size) { if (size < 1) { ALOGE("empty NAL b/35467107"); return ERROR_MALFORMED; } uint8_t nalUnitType = (data[0] >> 1) & 0x3f; status_t err = OK; switch (nalUnitType) { case 32: // VPS if (size < 2) { ALOGE("invalid NAL/VPS size b/35467107"); return ERROR_MALFORMED; } err = parseVps(data + 2, size - 2); break; case 33: // SPS if (size < 2) { ALOGE("invalid NAL/SPS size b/35467107"); return ERROR_MALFORMED; } err = parseSps(data + 2, size - 2); break; case 34: // PPS if (size < 2) { ALOGE("invalid NAL/PPS size b/35467107"); return ERROR_MALFORMED; } err = parsePps(data + 2, size - 2); break; case 39: // Prefix SEI case 40: // Suffix SEI break; default: ALOGE("Unrecognized NAL unit type."); return ERROR_MALFORMED; } if (err != OK) { return err; } sp<ABuffer> buffer = ABuffer::CreateAsCopy(data, size); buffer->setInt32Data(nalUnitType); mNalUnits.push(buffer); return OK; }
174,001
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 DebuggerAttachFunction::RunAsync() { scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitAgentHost()) return false; if (!DevToolsHttpHandler::IsSupportedProtocolVersion( params->required_version)) { error_ = ErrorUtils::FormatErrorMessage( keys::kProtocolVersionNotSupportedError, params->required_version); return false; } if (agent_host_->IsAttached()) { FormatErrorMessage(keys::kAlreadyAttachedError); return false; } infobars::InfoBar* infobar = NULL; if (!CommandLine::ForCurrentProcess()-> HasSwitch(switches::kSilentDebuggerExtensionAPI)) { infobar = ExtensionDevToolsInfoBarDelegate::Create( agent_host_->GetRenderViewHost(), GetExtension()->name()); if (!infobar) { error_ = ErrorUtils::FormatErrorMessage( keys::kSilentDebuggingRequired, switches::kSilentDebuggerExtensionAPI); return false; } } new ExtensionDevToolsClientHost(GetProfile(), agent_host_.get(), GetExtension()->id(), GetExtension()->name(), debuggee_, infobar); SendResponse(true); return true; } Commit Message: Have the Debugger extension api check that it has access to the tab Check PermissionsData::CanAccessTab() prior to attaching the debugger. BUG=367567 Review URL: https://codereview.chromium.org/352523003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool DebuggerAttachFunction::RunAsync() { scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitAgentHost()) return false; if (!DevToolsHttpHandler::IsSupportedProtocolVersion( params->required_version)) { error_ = ErrorUtils::FormatErrorMessage( keys::kProtocolVersionNotSupportedError, params->required_version); return false; } if (agent_host_->IsAttached()) { FormatErrorMessage(keys::kAlreadyAttachedError); return false; } const Extension* extension = GetExtension(); infobars::InfoBar* infobar = NULL; if (!CommandLine::ForCurrentProcess()-> HasSwitch(::switches::kSilentDebuggerExtensionAPI)) { infobar = ExtensionDevToolsInfoBarDelegate::Create( agent_host_->GetRenderViewHost(), extension->name()); if (!infobar) { error_ = ErrorUtils::FormatErrorMessage( keys::kSilentDebuggingRequired, ::switches::kSilentDebuggerExtensionAPI); return false; } } new ExtensionDevToolsClientHost(GetProfile(), agent_host_.get(), extension->id(), extension->name(), debuggee_, infobar); SendResponse(true); return true; }
171,654
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: ImageTransportClientTexture( WebKit::WebGraphicsContext3D* host_context, const gfx::Size& size, float device_scale_factor, uint64 surface_id) : ui::Texture(true, size, device_scale_factor), host_context_(host_context), texture_id_(surface_id) { } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
ImageTransportClientTexture(
171,362
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: NetworkHandler::NetworkHandler(const std::string& host_id) : DevToolsDomainHandler(Network::Metainfo::domainName), process_(nullptr), host_(nullptr), enabled_(false), host_id_(host_id), bypass_service_worker_(false), cache_disabled_(false), weak_factory_(this) { static bool have_configured_service_worker_context = false; if (have_configured_service_worker_context) return; have_configured_service_worker_context = true; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&ConfigureServiceWorkerContextOnIO)); } 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
NetworkHandler::NetworkHandler(const std::string& host_id) : DevToolsDomainHandler(Network::Metainfo::domainName), browser_context_(nullptr), storage_partition_(nullptr), host_(nullptr), enabled_(false), host_id_(host_id), bypass_service_worker_(false), cache_disabled_(false), weak_factory_(this) { static bool have_configured_service_worker_context = false; if (have_configured_service_worker_context) return; have_configured_service_worker_context = true; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&ConfigureServiceWorkerContextOnIO)); }
172,759
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 *ReadPSDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers, status; MagickOffsetType offset; MagickSizeType length; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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 image header. */ count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length+16, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } (void) ParseImageResourceBlocks(image,blocks,(size_t) length, &has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image,&psd_info, exception); if (has_merged_image == MagickFalse && GetImageListLength(image) == 1 && length != 0) { SeekBlob(image,offset,SEEK_SET); if (ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception) != MagickTrue) { (void) CloseBlob(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse && GetImageListLength(image) > 1) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadPSDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers, status; MagickOffsetType offset; MagickSizeType length; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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 image header. */ count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length+16, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } (void) ParseImageResourceBlocks(image,blocks,(size_t) length, &has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image,&psd_info, exception); if (has_merged_image == MagickFalse && GetImageListLength(image) == 1 && length != 0) { SeekBlob(image,offset,SEEK_SET); if (ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception) != MagickTrue) { (void) CloseBlob(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse && GetImageListLength(image) > 1) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) { struct import_t *imports; int i, j, idx, stridx; const char *symstr; if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) return NULL; if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) { return NULL; } if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) { return NULL; } for (i = j = 0; i < bin->dysymtab.nundefsym; i++) { idx = bin->dysymtab.iundefsym + i; if (idx < 0 || idx >= bin->nsymtab) { bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n"); free (imports); return NULL; } stridx = bin->symtab[idx].n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char *)bin->symstr + stridx; } else { symstr = ""; } if (!*symstr) { continue; } { int i = 0; int len = 0; char *symstr_dup = NULL; len = bin->symstrlen - stridx; imports[j].name[0] = 0; if (len > 0) { for (i = 0; i < len; i++) { if ((unsigned char)symstr[i] == 0xff || !symstr[i]) { len = i; break; } } symstr_dup = r_str_ndup (symstr, len); if (symstr_dup) { r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH); r_str_filter (imports[j].name, - 1); imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0; free (symstr_dup); } } } imports[j].ord = i; imports[j++].last = 0; } imports[j].last = 1; if (!bin->imports_by_ord_size) { if (j > 0) { bin->imports_by_ord_size = j; bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*)); } else { bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; } } return imports; } Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026) CWE ID: CWE-125
struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) { struct import_t *imports; int i, j, idx, stridx; const char *symstr; if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) { return NULL; } if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) { return NULL; } if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) { return NULL; } for (i = j = 0; i < bin->dysymtab.nundefsym; i++) { idx = bin->dysymtab.iundefsym + i; if (idx < 0 || idx >= bin->nsymtab) { bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n"); free (imports); return NULL; } stridx = bin->symtab[idx].n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char *)bin->symstr + stridx; } else { symstr = ""; } if (!*symstr) { continue; } { int i = 0; int len = 0; char *symstr_dup = NULL; len = bin->symstrlen - stridx; imports[j].name[0] = 0; if (len > 0) { for (i = 0; i < len; i++) { if ((unsigned char)symstr[i] == 0xff || !symstr[i]) { len = i; break; } } symstr_dup = r_str_ndup (symstr, len); if (symstr_dup) { r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH); r_str_filter (imports[j].name, - 1); imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0; free (symstr_dup); } } } imports[j].ord = i; imports[j++].last = 0; } imports[j].last = 1; if (!bin->imports_by_ord_size) { if (j > 0) { bin->imports_by_ord_size = j; bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*)); } else { bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; } } return imports; }
169,225
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: exsltCryptoRc4EncryptFunction (xmlXPathParserContextPtr ctxt, int nargs) { int key_len = 0, key_size = 0; int str_len = 0, bin_len = 0, hex_len = 0; xmlChar *key = NULL, *str = NULL, *padkey = NULL; xmlChar *bin = NULL, *hex = NULL; xsltTransformContextPtr tctxt = NULL; if (nargs != 2) { xmlXPathSetArityError (ctxt); return; } tctxt = xsltXPathGetTransformContext(ctxt); str = xmlXPathPopString (ctxt); str_len = xmlUTF8Strlen (str); if (str_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (str); return; } key = xmlXPathPopString (ctxt); key_len = xmlUTF8Strlen (key); if (key_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (key); xmlFree (str); return; } padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1); if (padkey == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memset(padkey, 0, RC4_KEY_LENGTH + 1); key_size = xmlUTF8Strsize (key, key_len); if ((key_size > RC4_KEY_LENGTH) || (key_size < 0)) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: key size too long or key broken\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memcpy (padkey, key, key_size); /* encrypt it */ bin_len = str_len; bin = xmlStrdup (str); if (bin == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate string\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } PLATFORM_RC4_ENCRYPT (ctxt, padkey, str, str_len, bin, bin_len); /* encode it */ hex_len = str_len * 2 + 1; hex = xmlMallocAtomic (hex_len); if (hex == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate result\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } exsltCryptoBin2Hex (bin, str_len, hex, hex_len); xmlXPathReturnString (ctxt, hex); done: if (key != NULL) xmlFree (key); if (str != NULL) xmlFree (str); if (padkey != NULL) xmlFree (padkey); if (bin != NULL) xmlFree (bin); } 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
exsltCryptoRc4EncryptFunction (xmlXPathParserContextPtr ctxt, int nargs) { int key_len = 0; int str_len = 0, bin_len = 0, hex_len = 0; xmlChar *key = NULL, *str = NULL, *padkey = NULL; xmlChar *bin = NULL, *hex = NULL; xsltTransformContextPtr tctxt = NULL; if (nargs != 2) { xmlXPathSetArityError (ctxt); return; } tctxt = xsltXPathGetTransformContext(ctxt); str = xmlXPathPopString (ctxt); str_len = xmlStrlen (str); if (str_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (str); return; } key = xmlXPathPopString (ctxt); key_len = xmlStrlen (key); if (key_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (key); xmlFree (str); return; } padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1); if (padkey == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memset(padkey, 0, RC4_KEY_LENGTH + 1); if ((key_len > RC4_KEY_LENGTH) || (key_len < 0)) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: key size too long or key broken\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memcpy (padkey, key, key_len); /* encrypt it */ bin_len = str_len; bin = xmlStrdup (str); if (bin == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate string\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } PLATFORM_RC4_ENCRYPT (ctxt, padkey, str, str_len, bin, bin_len); /* encode it */ hex_len = str_len * 2 + 1; hex = xmlMallocAtomic (hex_len); if (hex == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate result\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } exsltCryptoBin2Hex (bin, str_len, hex, hex_len); xmlXPathReturnString (ctxt, hex); done: if (key != NULL) xmlFree (key); if (str != NULL) xmlFree (str); if (padkey != NULL) xmlFree (padkey); if (bin != NULL) xmlFree (bin); }
173,288
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 BluetoothDeviceChromeOS::OnPair( const base::Closure& callback, const ConnectErrorCallback& error_callback) { VLOG(1) << object_path_.value() << ": Paired"; if (!pairing_delegate_used_) UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_NONE, UMA_PAIRING_METHOD_COUNT); UnregisterAgent(); SetTrusted(); ConnectInternal(true, callback, error_callback); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::OnPair( const base::Closure& callback, const ConnectErrorCallback& error_callback) { VLOG(1) << object_path_.value() << ": Paired"; pairing_context_.reset(); SetTrusted(); ConnectInternal(true, callback, error_callback); }
171,227
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 dev_load(struct net *net, const char *name) { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, name); rcu_read_unlock(); if (!dev && capable(CAP_NET_ADMIN)) request_module("%s", name); } Commit Message: net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules Since a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with CAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean that CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are limited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't allow anybody load any module not related to networking. This patch restricts an ability of autoloading modules to netdev modules with explicit aliases. This fixes CVE-2011-1019. Arnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior of loading netdev modules by name (without any prefix) for processes with CAP_SYS_MODULE to maintain the compatibility with network scripts that use autoloading netdev modules by aliases like "eth0", "wlan0". Currently there are only three users of the feature in the upstream kernel: ipip, ip_gre and sit. root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) -- root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: fffffff800001000 CapEff: fffffff800001000 CapBnd: fffffff800001000 root@albatros:~# modprobe xfs FATAL: Error inserting xfs (/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted root@albatros:~# lsmod | grep xfs root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit sit: error fetching interface information: Device not found root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit0 sit0 Link encap:IPv6-in-IPv4 NOARP MTU:1480 Metric:1 root@albatros:~# lsmod | grep sit sit 10457 0 tunnel4 2957 1 sit For CAP_SYS_MODULE module loading is still relaxed: root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: ffffffffffffffff CapEff: ffffffffffffffff CapBnd: ffffffffffffffff root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs xfs 745319 0 Reference: https://lkml.org/lkml/2011/2/24/203 Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Michael Tokarev <[email protected]> Acked-by: David S. Miller <[email protected]> Acked-by: Kees Cook <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264
void dev_load(struct net *net, const char *name) { struct net_device *dev; int no_module; rcu_read_lock(); dev = dev_get_by_name_rcu(net, name); rcu_read_unlock(); no_module = !dev; if (no_module && capable(CAP_NET_ADMIN)) no_module = request_module("netdev-%s", name); if (no_module && capable(CAP_SYS_MODULE)) { if (!request_module("%s", name)) pr_err("Loading kernel module for a network device " "with CAP_SYS_MODULE (deprecated). Use CAP_NET_ADMIN and alias netdev-%s " "instead\n", name); } }
166,234
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 CreatePersistentMemoryAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
void CreatePersistentMemoryAllocator() { GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); }
172,138
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 StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } // b/28466701 payload->pBuffer = (ANativeWindowBuffer*)(((uint8_t*)payload->pBuffer) + ICameraRecordingProxy::getCommonBaseAddress()); size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); }
173,512