prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check(FILE *fp, int argc, const char **argv, png_uint_32p flags/*out*/, display *d, int set_callback) { int i, npasses, ipass; png_uint_32 height; d->keep = PNG_HANDLE_CHUNK_AS_DEFAULT; d->before_IDAT = 0; d->after_IDAT = 0; /* Some of these errors are permanently fatal and cause an exit here, others * are per-test and cause an error return. */ d->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, d, error, warning); if (d->png_ptr == NULL) { fprintf(stderr, "%s(%s): could not allocate png struct\n", d->file, d->test); /* Terminate here, this error is not test specific. */ exit(1); } d->info_ptr = png_create_info_struct(d->png_ptr); d->end_ptr = png_create_info_struct(d->png_ptr); if (d->info_ptr == NULL || d->end_ptr == NULL) { fprintf(stderr, "%s(%s): could not allocate png info\n", d->file, d->test); clean_display(d); exit(1); } png_init_io(d->png_ptr, fp); # ifdef PNG_READ_USER_CHUNKS_SUPPORTED /* This is only done if requested by the caller; it interferes with the * standard store/save mechanism. */ if (set_callback) png_set_read_user_chunk_fn(d->png_ptr, d, read_callback); # else UNUSED(set_callback) # endif /* Handle each argument in turn; multiple settings are possible for the same * chunk and multiple calls will occur (the last one should override all * preceding ones). */ for (i=0; i<argc; ++i) { const char *equals = strchr(argv[i], '='); if (equals != NULL) { int chunk, option; if (strcmp(equals+1, "default") == 0) option = PNG_HANDLE_CHUNK_AS_DEFAULT; else if (strcmp(equals+1, "discard") == 0) option = PNG_HANDLE_CHUNK_NEVER; else if (strcmp(equals+1, "if-safe") == 0) option = PNG_HANDLE_CHUNK_IF_SAFE; else if (strcmp(equals+1, "save") == 0) option = PNG_HANDLE_CHUNK_ALWAYS; else { fprintf(stderr, "%s(%s): %s: unrecognized chunk option\n", d->file, d->test, argv[i]); display_exit(d); } switch (equals - argv[i]) { case 4: /* chunk name */ chunk = find(argv[i]); if (chunk >= 0) { /* These #if tests have the effect of skipping the arguments * if SAVE support is unavailable - we can't do a useful test * in this case, so we just check the arguments! This could * be improved in the future by using the read callback. */ png_byte name[5]; memcpy(name, chunk_info[chunk].name, 5); png_set_keep_unknown_chunks(d->png_ptr, option, name, 1); chunk_info[chunk].keep = option; continue; } break; case 7: /* default */ if (memcmp(argv[i], "default", 7) == 0) { png_set_keep_unknown_chunks(d->png_ptr, option, NULL, 0); d->keep = option; continue; } break; case 3: /* all */ if (memcmp(argv[i], "all", 3) == 0) { png_set_keep_unknown_chunks(d->png_ptr, option, NULL, -1); d->keep = option; for (chunk = 0; chunk < NINFO; ++chunk) if (chunk_info[chunk].all) chunk_info[chunk].keep = option; continue; } break; default: /* some misplaced = */ break; } } fprintf(stderr, "%s(%s): %s: unrecognized chunk argument\n", d->file, d->test, argv[i]); display_exit(d); } png_read_info(d->png_ptr, d->info_ptr); switch (png_get_interlace_type(d->png_ptr, d->info_ptr)) { case PNG_INTERLACE_NONE: npasses = 1; break; case PNG_INTERLACE_ADAM7: npasses = PNG_INTERLACE_ADAM7_PASSES; break; default: /* Hard error because it is not test specific */ fprintf(stderr, "%s(%s): invalid interlace type\n", d->file, d->test); clean_display(d); exit(1); } /* Skip the image data, if IDAT is not being handled then don't do this * because it will cause a CRC error. */ if (chunk_info[0/*IDAT*/].keep == PNG_HANDLE_CHUNK_AS_DEFAULT) { png_start_read_image(d->png_ptr); height = png_get_image_height(d->png_ptr, d->info_ptr); if (npasses > 1) { png_uint_32 width = png_get_image_width(d->png_ptr, d->info_ptr); for (ipass=0; ipass<npasses; ++ipass) { png_uint_32 wPass = PNG_PASS_COLS(width, ipass); if (wPass > 0) { png_uint_32 y; for (y=0; y<height; ++y) if (PNG_ROW_IN_INTERLACE_PASS(y, ipass)) png_read_row(d->png_ptr, NULL, NULL); } } } /* interlaced */ else /* not interlaced */ { png_uint_32 y; for (y=0; y<height; ++y) png_read_row(d->png_ptr, NULL, NULL); } } png_read_end(d->png_ptr, d->end_ptr); flags[0] = get_valid(d, d->info_ptr); flags[1] = get_unknown(d, d->info_ptr, 0/*before IDAT*/); /* Only png_read_png sets PNG_INFO_IDAT! */ flags[chunk_info[0/*IDAT*/].keep != PNG_HANDLE_CHUNK_AS_DEFAULT] |= PNG_INFO_IDAT; flags[2] = get_valid(d, d->end_ptr); flags[3] = get_unknown(d, d->end_ptr, 1/*after IDAT*/); clean_display(d); return d->keep; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: ScriptPromise ImageCapture::grabFrame(ScriptState* script_state) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); if (TrackIsInactive(*stream_track_)) { resolver->Reject(DOMException::Create( kInvalidStateError, "The associated Track is in an invalid state.")); return promise; } if (!frame_grabber_) { frame_grabber_ = Platform::Current()->CreateImageCaptureFrameGrabber(); } if (!frame_grabber_) { resolver->Reject(DOMException::Create( kUnknownError, "Couldn't create platform resources")); return promise; } WebMediaStreamTrack track(stream_track_->Component()); frame_grabber_->GrabFrame( &track, new CallbackPromiseAdapter<ImageBitmap, void>(resolver)); return promise; } Commit Message: Convert MediaTrackConstraints to a ScriptValue IDLDictionaries such as MediaTrackConstraints should not be stored on the heap which would happen when binding one as a parameter to a callback. This change converts the object to a ScriptValue ahead of time. This is fine because the value will be passed to a ScriptPromiseResolver that will converted it to a V8 value if it isn't already. Bug: 759457 Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8 Reviewed-on: https://chromium-review.googlesource.com/701358 Reviewed-by: Kentaro Hara <[email protected]> Commit-Queue: Reilly Grant <[email protected]> Cr-Commit-Position: refs/heads/master@{#507177} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothDeviceChromeOS::RequestAuthorization( const dbus::ObjectPath& device_path, const ConfirmationCallback& callback) { callback.Run(CANCELLED); } 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: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ih264d_cavlc_4x4res_block_totalcoeff_2to10(UWORD32 u4_isdc, UWORD32 u4_total_coeff_trail_one, /*!<TotalCoefficients<<16+trailingones*/ dec_bit_stream_t *ps_bitstrm) { UWORD32 u4_total_zeroes; WORD32 i; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; WORD16 i2_level_arr[16]; tu_sblk4x4_coeff_data_t *ps_tu_4x4; WORD16 *pi2_coeff_data; dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle; ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data; ps_tu_4x4->u2_sig_coeff_map = 0; pi2_coeff_data = &ps_tu_4x4->ai2_level[0]; i = u4_total_coeff - 1; if(u4_trailing_ones) { /*********************************************************************/ /* Decode Trailing Ones */ /* read the sign of T1's and put them in level array */ /*********************************************************************/ UWORD32 u4_signs, u4_cnt = u4_trailing_ones; WORD16 (*ppi2_trlone_lkup)[3] = (WORD16 (*)[3])gai2_ih264d_trailing_one_level; WORD16 *pi2_trlone_lkup; GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt); pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs]; while(u4_cnt--) i2_level_arr[i--] = *pi2_trlone_lkup++; } /****************************************************************/ /* Decoding Levels Begins */ /****************************************************************/ if(i >= 0) { /****************************************************************/ /* First level is decoded outside the loop as it has lot of */ /* special cases. */ /****************************************************************/ UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size; WORD32 u2_lev_code, u2_abs_value; UWORD32 u4_lev_prefix; /***************************************************************/ /* u4_suffix_len = 0, Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); /*********************************************************/ /* Special decoding case when trailing ones are 3 */ /*********************************************************/ u2_lev_code = MIN(15, u4_lev_prefix); u2_lev_code += (3 == u4_trailing_ones) ? 0 : 2; if(14 == u4_lev_prefix) u4_lev_suffix_size = 4; else if(15 <= u4_lev_prefix) { u2_lev_code += 15; u4_lev_suffix_size = u4_lev_prefix - 3; } else u4_lev_suffix_size = 0; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } if(u4_lev_suffix_size) { GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code += u4_lev_suffix; } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; u4_suffix_len = (u2_abs_value > 3) ? 2 : 1; /*********************************************************/ /* Now loop over the remaining levels */ /*********************************************************/ while(i >= 0) { /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); u4_lev_suffix_size = (15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : u4_suffix_len; /*********************************************************/ /* Compute level code using prefix and suffix */ /*********************************************************/ GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len) + u4_lev_suffix; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; /*********************************************************/ /* Increment suffix length if required */ /*********************************************************/ u4_suffix_len += (u4_suffix_len < 6) ? (u2_abs_value > (3 << (u4_suffix_len - 1))) : 0; } /****************************************************************/ /* Decoding Levels Ends */ /****************************************************************/ } /****************************************************************/ /* Decoding total zeros as in section 9.2.3, table 9.7 */ /****************************************************************/ { UWORD32 u4_index; const UWORD8 (*ppu1_total_zero_lkup)[64] = (const UWORD8 (*)[64])gau1_ih264d_table_total_zero_2to10; NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 6); u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 2][u4_index]; FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4)); u4_total_zeroes &= 0xf; } /**************************************************************/ /* Decode the runs and form the coefficient buffer */ /**************************************************************/ { const UWORD8 *pu1_table_runbefore; UWORD32 u4_run; WORD32 k; UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc; WORD32 u4_zeroes_left = u4_total_zeroes; k = u4_total_coeff - 1; /**************************************************************/ /* Decoding Runs Begin for zeros left > 6 */ /**************************************************************/ while((u4_zeroes_left > 6) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); if(u4_code != 0) { FLUSHBITS(u4_bitstream_offset, 3); u4_run = (7 - u4_code); } else { FIND_ONE_IN_STREAM_LEN(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 11); u4_run = (4 + u4_code); } SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs for 0 < zeros left <=6 */ /**************************************************************/ pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before; while((u4_zeroes_left > 0) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)]; u4_run = u4_code >> 2; FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03)); SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs End */ /**************************************************************/ /**************************************************************/ /* Copy the remaining coefficients */ /**************************************************************/ if(u4_zeroes_left < 0) return -1; while(k >= 0) { SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_scan_pos--; } } { WORD32 offset; offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4; offset = ALIGN4(offset); ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset); } ps_bitstrm->u4_ofst = u4_bitstream_offset; return 0; } Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions Bug: 26399350 Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::RenderbufferStorageMultisampleHelper( const FeatureInfo* feature_info, GLenum target, GLsizei samples, GLenum internal_format, GLsizei width, GLsizei height) { if (feature_info->feature_flags().is_angle) { glRenderbufferStorageMultisampleANGLE( target, samples, internal_format, width, height); } else if (feature_info->feature_flags().use_core_framebuffer_multisample) { glRenderbufferStorageMultisample( target, samples, internal_format, width, height); } else { glRenderbufferStorageMultisampleEXT( target, samples, internal_format, width, height); } } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK(!options.executable); DCHECK(!mapped_file_); if (options.size == 0) return false; uint32 rounded_size = (options.size + 0xffff) & ~0xffff; name_ = ASCIIToWide(options.name == NULL ? "" : *options.name); mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size), name_.empty() ? NULL : name_.c_str()); if (!mapped_file_) return false; created_size_ = options.size; if (GetLastError() == ERROR_ALREADY_EXISTS) { created_size_ = 0; if (!options.open_existing) { Close(); return false; } } return true; } Commit Message: Fix integer overflow in Windows shared memory handling. BUG=164490 Review URL: https://codereview.chromium.org/11450016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171369 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } Commit Message: ... CWE ID: CWE-754 Target: 1 Example 2: Code: int SRP_Verify_B_mod_N(BIGNUM *B, BIGNUM *N) { BIGNUM *r; BN_CTX *bn_ctx; int ret = 0; if (B == NULL || N == NULL || (bn_ctx = BN_CTX_new()) == NULL) return 0; if ((r = BN_new()) == NULL) goto err; /* Checks if B % N == 0 */ if (!BN_nnmod(r,B,N,bn_ctx)) goto err; ret = !BN_is_zero(r); err: BN_CTX_free(bn_ctx); BN_free(r); return ret; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static noinline size_t if_nlmsg_size(const struct net_device *dev, u32 ext_filter_mask) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(IFALIASZ) /* IFLA_IFALIAS */ + nla_total_size(IFNAMSIZ) /* IFLA_QDISC */ + nla_total_size(sizeof(struct rtnl_link_ifmap)) + nla_total_size(sizeof(struct rtnl_link_stats)) + nla_total_size(sizeof(struct rtnl_link_stats64)) + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_BROADCAST */ + nla_total_size(4) /* IFLA_TXQLEN */ + nla_total_size(4) /* IFLA_WEIGHT */ + nla_total_size(4) /* IFLA_MTU */ + nla_total_size(4) /* IFLA_LINK */ + nla_total_size(4) /* IFLA_MASTER */ + nla_total_size(1) /* IFLA_CARRIER */ + nla_total_size(4) /* IFLA_PROMISCUITY */ + nla_total_size(4) /* IFLA_NUM_TX_QUEUES */ + nla_total_size(4) /* IFLA_NUM_RX_QUEUES */ + nla_total_size(1) /* IFLA_OPERSTATE */ + nla_total_size(1) /* IFLA_LINKMODE */ + nla_total_size(ext_filter_mask & RTEXT_FILTER_VF ? 4 : 0) /* IFLA_NUM_VF */ + rtnl_vfinfo_size(dev, ext_filter_mask) /* IFLA_VFINFO_LIST */ + rtnl_port_size(dev) /* IFLA_VF_PORTS + IFLA_PORT_SELF */ + rtnl_link_get_size(dev) /* IFLA_LINKINFO */ + rtnl_link_get_af_size(dev); /* IFLA_AF_SPEC */ } Commit Message: rtnl: fix info leak on RTM_GETLINK request for VF devices Initialize the mac address buffer with 0 as the driver specific function will probably not fill the whole buffer. In fact, all in-kernel drivers fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible bytes. Therefore we currently leak 26 bytes of stack memory to userland via the netlink interface. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int, gboolean *cap_dir, char *cap_dst, int *err, gchar **err_info) { int sec; int dsec, pkt_len; char direction[2]; char cap_src[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } *cap_dir = (direction[0] == 'o' ? NETSCREEN_EGRESS : NETSCREEN_INGRESS); phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; return pkt_len; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static int http_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; if (s->icy_metaint > 0) { size = store_icy(h, size); if (size < 0) return size; } size = http_read_stream(h, buf, size); if (size > 0) s->icy_data_read += size; return size; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) { _sx_sasl_t ctx = (_sx_sasl_t) p->private; _sx_sasl_sess_t sctx = NULL; char *buf = NULL, *out = NULL, *realm = NULL, **ext_id; char hostname[256]; int ret; #ifdef HAVE_SSL int i; #endif size_t buflen, outlen; assert(ctx); assert(ctx->cb); if(mech != NULL) { _sx_debug(ZONE, "auth request from client (mechanism=%s)", mech); if(!gsasl_server_support_p(ctx->gsasl_ctx, mech)) { _sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0); return; } /* startup */ ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd); if(ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0); return; } /* get the realm */ (ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg); /* cleanup any existing session context */ sctx = gsasl_session_hook_get(sd); if (sctx != NULL) free(sctx); /* allocate and initialize our per session context */ sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st)); sctx->s = s; sctx->ctx = ctx; gsasl_session_hook_set(sd, (void *) sctx); gsasl_property_set(sd, GSASL_SERVICE, ctx->appname); gsasl_property_set(sd, GSASL_REALM, realm); /* get hostname */ hostname[0] = '\0'; gethostname(hostname, 256); hostname[255] = '\0'; gsasl_property_set(sd, GSASL_HOSTNAME, hostname); /* get EXTERNAL data from the ssl plugin */ ext_id = NULL; #ifdef HAVE_SSL for(i = 0; i < s->env->nplugins; i++) if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL) ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id; if (ext_id != NULL) { /* if there is, store it for later */ for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++) if (ext_id[i] != NULL) { ctx->ext_id[i] = strdup(ext_id[i]); } else { ctx->ext_id[i] = NULL; break; } } #endif _sx_debug(ZONE, "sasl context initialised for %d", s->tag); s->plugin_data[p->index] = (void *) sd; if(strcmp(mech, "ANONYMOUS") == 0) { /* * special case for SASL ANONYMOUS: ignore the initial * response provided by the client and generate a random * authid to use as the jid node for the user, as * specified in XEP-0175 */ (ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg); buf = strdup(out); buflen = strlen(buf); } else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) { /* XXX The above check is hackish, but `in` is just weird */ /* This is a special case for SASL External c2s. See XEP-0178 */ _sx_debug(ZONE, "gsasl auth string is empty"); buf = strdup(""); buflen = strlen(buf); } else { /* decode and process */ ret = gsasl_base64_from(in, inlen, &buf, &buflen); if (ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); return; } } ret = gsasl_step(sd, buf, buflen, &out, &outlen); } else { /* decode and process */ ret = gsasl_base64_from(in, inlen, &buf, &buflen); if (ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); return; } if(!sd) { _sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0); if(buf != NULL) free(buf); return; } _sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf); ret = gsasl_step(sd, buf, buflen, &out, &outlen); } if(buf != NULL) free(buf); /* auth completed */ if(ret == GSASL_OK) { _sx_debug(ZONE, "sasl handshake completed"); /* encode the leftover response */ ret = gsasl_base64_to(out, outlen, &buf, &buflen); if (ret == GSASL_OK) { /* send success */ _sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0); free(buf); /* set a notify on the success nad buffer */ ((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success; ((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p; } else { _sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); } if(out != NULL) free(out); return; } /* in progress */ if(ret == GSASL_NEEDS_MORE) { _sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out); /* encode the challenge */ ret = gsasl_base64_to(out, outlen, &buf, &buflen); if (ret == GSASL_OK) { _sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0); free(buf); } else { _sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); } if(out != NULL) free(out); return; } if(out != NULL) free(out); /* its over */ _sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret)); switch (ret) { case GSASL_AUTHENTICATION_ERROR: case GSASL_NO_ANONYMOUS_TOKEN: case GSASL_NO_AUTHID: case GSASL_NO_AUTHZID: case GSASL_NO_PASSWORD: case GSASL_NO_PASSCODE: case GSASL_NO_PIN: case GSASL_NO_SERVICE: case GSASL_NO_HOSTNAME: out = _sasl_err_NOT_AUTHORIZED; break; case GSASL_UNKNOWN_MECHANISM: case GSASL_MECHANISM_PARSE_ERROR: out = _sasl_err_INVALID_MECHANISM; break; case GSASL_BASE64_ERROR: out = _sasl_err_INCORRECT_ENCODING; break; default: out = _sasl_err_MALFORMED_REQUEST; } _sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0); } Commit Message: Fixed offered SASL mechanism check CWE ID: CWE-287 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284 Target: 1 Example 2: Code: void SelectionEditor::UpdateCachedVisibleSelectionIfNeeded() const { DCHECK_GE(GetDocument().Lifecycle().GetState(), DocumentLifecycle::kAfterPerformLayout); AssertSelectionValid(); if (!NeedsUpdateVisibleSelection()) return; style_version_for_dom_tree_ = GetDocument().StyleVersion(); cached_visible_selection_in_dom_tree_is_dirty_ = false; cached_visible_selection_in_dom_tree_ = CreateVisibleSelection(selection_); if (!cached_visible_selection_in_dom_tree_.IsNone()) return; style_version_for_flat_tree_ = GetDocument().StyleVersion(); cached_visible_selection_in_flat_tree_is_dirty_ = false; cached_visible_selection_in_flat_tree_ = VisibleSelectionInFlatTree(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static double GetOpacityPixel(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_opacity) { double alpha, beta, distance, subpath_opacity; PointInfo delta; register EdgeInfo *p; register const PointInfo *q; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_opacity=0.0; subpath_opacity=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,(size_t) j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta < 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta > alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=1.0/alpha; beta=delta.x*(y-q->y)-delta.y*(x-q->x); distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_opacity < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_opacity=1.0; else { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_opacity < ((alpha-0.25)*(alpha-0.25))) *stroke_opacity=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_opacity >= 1.0)) continue; if (distance <= 0.0) { subpath_opacity=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < DrawEpsilon) { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_opacity < (alpha*alpha)) subpath_opacity=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_opacity >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_opacity); } Commit Message: Prevent buffer overflow (bug report from Max Thrane) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() { progress_event_timer_.Stop(); if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) ScheduleEvent(EventTypeNames::progress); ScheduleEvent(EventTypeNames::suspend); SetNetworkState(kNetworkIdle); } Commit Message: defeat cors attacks on audio/video tags Neutralize error messages and fire no progress events until media metadata has been loaded for media loaded from cross-origin locations. Bug: 828265, 826187 Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6 Reviewed-on: https://chromium-review.googlesource.com/1015794 Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Dale Curtis <[email protected]> Commit-Queue: Fredrik Hubinette <[email protected]> Cr-Commit-Position: refs/heads/master@{#557312} CWE ID: CWE-200 Target: 1 Example 2: Code: static int mmap_ureg(struct vm_area_struct *vma, struct qib_devdata *dd, u64 ureg) { unsigned long phys; unsigned long sz; int ret; /* * This is real hardware, so use io_remap. This is the mechanism * for the user process to update the head registers for their ctxt * in the chip. */ sz = dd->flags & QIB_HAS_HDRSUPP ? 2 * PAGE_SIZE : PAGE_SIZE; if ((vma->vm_end - vma->vm_start) > sz) { qib_devinfo(dd->pcidev, "FAIL mmap userreg: reqlen %lx > PAGE\n", vma->vm_end - vma->vm_start); ret = -EFAULT; } else { phys = dd->physaddr + ureg; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND; ret = io_remap_pfn_range(vma, vma->vm_start, phys >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ft_smooth_render_generic( FT_Renderer render, FT_GlyphSlot slot, FT_Render_Mode mode, const FT_Vector* origin, FT_Render_Mode required_mode ) { FT_Error error; FT_Outline* outline = NULL; FT_BBox cbox; FT_UInt width, height, height_org, width_org, pitch; FT_Bitmap* bitmap; FT_Memory memory; FT_Int hmul = mode == FT_RENDER_MODE_LCD; FT_Int vmul = mode == FT_RENDER_MODE_LCD_V; FT_Pos x_shift, y_shift, x_left, y_top; FT_Raster_Params params; /* check glyph image format */ if ( slot->format != render->glyph_format ) { error = Smooth_Err_Invalid_Argument; goto Exit; } /* check mode */ if ( mode != required_mode ) return Smooth_Err_Cannot_Render_Glyph; outline = &slot->outline; /* translate the outline to the new origin if needed */ if ( origin ) FT_Outline_Translate( outline, origin->x, origin->y ); /* compute the control box, and grid fit it */ FT_Outline_Get_CBox( outline, &cbox ); cbox.xMin = FT_PIX_FLOOR( cbox.xMin ); cbox.yMin = FT_PIX_FLOOR( cbox.yMin ); cbox.xMax = FT_PIX_CEIL( cbox.xMax ); cbox.yMax = FT_PIX_CEIL( cbox.yMax ); width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 ); height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 ); bitmap = &slot->bitmap; memory = render->root.memory; width_org = width; height_org = height; /* release old bitmap buffer */ if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) { FT_FREE( bitmap->buffer ); slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP; } /* allocate new one */ pitch = width; if ( hmul ) { width = width * 3; pitch = FT_PAD_CEIL( width, 4 ); } if ( vmul ) height *= 3; x_shift = (FT_Int) cbox.xMin; y_shift = (FT_Int) cbox.yMin; x_left = (FT_Int)( cbox.xMin >> 6 ); y_top = (FT_Int)( cbox.yMax >> 6 ); #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING if ( slot->library->lcd_filter_func ) { FT_Int extra = slot->library->lcd_extra; if ( hmul ) { x_shift -= 64 * ( extra >> 1 ); width += 3 * extra; pitch = FT_PAD_CEIL( width, 4 ); x_left -= extra >> 1; } if ( vmul ) { y_shift -= 64 * ( extra >> 1 ); height += 3 * extra; y_top += extra >> 1; } } #endif #if FT_UINT_MAX > 0xFFFFU /* Required check is ( pitch * height < FT_ULONG_MAX ), */ /* but we care realistic cases only. Always pitch <= width. */ if ( width > 0xFFFFU || height > 0xFFFFU ) { FT_ERROR(( "ft_smooth_render_generic: glyph too large: %d x %d\n", width, height )); return Smooth_Err_Raster_Overflow; } #endif bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; bitmap->width = width; bitmap->rows = height; bitmap->pitch = pitch; /* translate outline to render it into the bitmap */ FT_Outline_Translate( outline, -x_shift, -y_shift ); if ( FT_ALLOC( bitmap->buffer, (FT_ULong)pitch * height ) ) goto Exit; slot->internal->flags |= FT_GLYPH_OWN_BITMAP; /* set up parameters */ params.target = bitmap; params.source = outline; params.flags = FT_RASTER_FLAG_AA; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING /* implode outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x *= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y *= 3; } /* render outline into the bitmap */ error = render->raster_render( render->raster, &params ); /* deflate outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x /= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y /= 3; } if ( slot->library->lcd_filter_func ) slot->library->lcd_filter_func( bitmap, mode, slot->library ); #else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /* render outline into bitmap */ error = render->raster_render( render->raster, &params ); /* expand it horizontally */ if ( hmul ) { FT_Byte* line = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh--, line += pitch ) { FT_UInt xx; FT_Byte* end = line + width; for ( xx = width_org; xx > 0; xx-- ) { FT_UInt pixel = line[xx-1]; end[-3] = (FT_Byte)pixel; end[-2] = (FT_Byte)pixel; end[-1] = (FT_Byte)pixel; end -= 3; } } } /* expand it vertically */ if ( vmul ) { FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch; FT_Byte* write = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh-- ) { ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; read += pitch; } } #endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ FT_Outline_Translate( outline, x_shift, y_shift ); /* * XXX: on 16bit system, we return an error for huge bitmap * to prevent an overflow. */ if ( x_left > FT_INT_MAX || y_top > FT_INT_MAX ) return Smooth_Err_Invalid_Pixel_Size; if ( error ) goto Exit; slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = (FT_Int)x_left; slot->bitmap_top = (FT_Int)y_top; Exit: if ( outline && origin ) FT_Outline_Translate( outline, -origin->x, -origin->y ); return error; } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int hugetlb_reserve_pages(struct inode *inode, long from, long to, struct vm_area_struct *vma, vm_flags_t vm_flags) { long ret, chg; struct hstate *h = hstate_inode(inode); /* * Only apply hugepage reservation if asked. At fault time, an * attempt will be made for VM_NORESERVE to allocate a page * and filesystem quota without using reserves */ if (vm_flags & VM_NORESERVE) return 0; /* * Shared mappings base their reservation on the number of pages that * are already allocated on behalf of the file. Private mappings need * to reserve the full area even if read-only as mprotect() may be * called to make the mapping read-write. Assume !vma is a shm mapping */ if (!vma || vma->vm_flags & VM_MAYSHARE) chg = region_chg(&inode->i_mapping->private_list, from, to); else { struct resv_map *resv_map = resv_map_alloc(); if (!resv_map) return -ENOMEM; chg = to - from; set_vma_resv_map(vma, resv_map); set_vma_resv_flags(vma, HPAGE_RESV_OWNER); } if (chg < 0) return chg; /* There must be enough filesystem quota for the mapping */ if (hugetlb_get_quota(inode->i_mapping, chg)) return -ENOSPC; /* * Check enough hugepages are available for the reservation. * Hand back the quota if there are not */ ret = hugetlb_acct_memory(h, chg); if (ret < 0) { hugetlb_put_quota(inode->i_mapping, chg); return ret; } /* * Account for the reservations made. Shared mappings record regions * that have reservations as they are shared by multiple VMAs. * When the last VMA disappears, the region map says how much * the reservation was and the page cache tells how much of * the reservation was consumed. Private mappings are per-VMA and * only the consumed reservations are tracked. When the VMA * disappears, the original reservation is the VMA size and the * consumed reservations are stored in the map. Hence, nothing * else has to be done for private mappings here */ if (!vma || vma->vm_flags & VM_MAYSHARE) region_add(&inode->i_mapping->private_list, from, to); return 0; } Commit Message: hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <[email protected]> Signed-off-by: David Gibson <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Minchan Kim <[email protected]> Cc: Hillf Danton <[email protected]> Cc: Paul Mackerras <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: const UsbConfigDescriptor* UsbDeviceImpl::GetConfiguration() { DCHECK(thread_checker_.CalledOnValidThread()); return configuration_.get(); } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SingleDesktopTestObserver::OnBrowserAdded(Browser* browser) { CHECK(CalledOnValidThread()); CHECK_EQ(browser->host_desktop_type(), allowed_desktop_); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int netlbl_cipsov4_add_common(struct genl_info *info, struct cipso_v4_doi *doi_def) { struct nlattr *nla; int nla_rem; u32 iter = 0; doi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]); if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST], NLBL_CIPSOV4_A_MAX, netlbl_cipsov4_genl_policy) != 0) return -EINVAL; nla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem) if (nla->nla_type == NLBL_CIPSOV4_A_TAG) { if (iter > CIPSO_V4_TAG_MAXCNT) return -EINVAL; doi_def->tags[iter++] = nla_get_u8(nla); } if (iter < CIPSO_V4_TAG_MAXCNT) doi_def->tags[iter] = CIPSO_V4_TAG_INVALID; return 0; } Commit Message: NetLabel: correct CIPSO tag handling when adding new DOI definitions The current netlbl_cipsov4_add_common() function has two problems which are fixed with this patch. The first is an off-by-one bug where it is possibile to overflow the doi_def->tags[] array. The second is a bug where the same doi_def->tags[] array was not always fully initialized, which caused sporadic failures. Signed-off-by: Paul Moore <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void TaskManagerView::LinkClicked(views::Link* source, int event_flags) { DCHECK(source == about_memory_link_); task_manager_->OpenAboutMemory(); } Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans. BUG=128242 [email protected] Review URL: https://chromiumcodereview.appspot.com/10399085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Plugin::Init(int argc, char* argn[], char* argv[]) { PLUGIN_PRINTF(("Plugin::Init (instance=%p)\n", static_cast<void*>(this))); #ifdef NACL_OSX pp::TextInput_Dev(this).SetTextInputType(PP_TEXTINPUT_TYPE_NONE); #endif argn_ = new char*[argc]; argv_ = new char*[argc]; argc_ = 0; for (int i = 0; i < argc; ++i) { if (NULL != argn_ && NULL != argv_) { argn_[argc_] = strdup(argn[i]); argv_[argc_] = strdup(argv[i]); if (NULL == argn_[argc_] || NULL == argv_[argc_]) { free(argn_[argc_]); free(argv_[argc_]); continue; } ++argc_; } } wrapper_factory_ = new nacl::DescWrapperFactory(); if (NULL == wrapper_factory_) { return false; } PLUGIN_PRINTF(("Plugin::Init (wrapper_factory=%p)\n", static_cast<void*>(wrapper_factory_))); AddPropertyGet("exitStatus", &Plugin::GetExitStatus); AddPropertyGet("lastError", &Plugin::GetLastError); AddPropertyGet("readyState", &Plugin::GetReadyStateProperty); PLUGIN_PRINTF(("Plugin::Init (return 1)\n")); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb) { atomic_sub(skb->truesize, &nf->mem); kfree_skb(skb); } Commit Message: ipv6: discard overlapping fragment RFC5722 prohibits reassembling fragments when some data overlaps. Bug spotted by Zhang Zuotao <[email protected]>. Signed-off-by: Nicolas Dichtel <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: void Wait() { std::vector<DownloadItem*> downloads; manager_->GetAllDownloads(&downloads); if (!downloads.empty()) return; waiting_ = true; content::RunMessageLoop(); waiting_ = false; } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLOzoneEGLX11() {} Commit Message: Add ThreadChecker for Ozone X11 GPU. Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM. BUG=none Review-Url: https://codereview.chromium.org/2366643002 Cr-Commit-Position: refs/heads/master@{#421817} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt, void (*get)(struct x86_emulate_ctxt *ctxt, struct desc_ptr *ptr)) { struct desc_ptr desc_ptr; if (ctxt->mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; get(ctxt, &desc_ptr); if (ctxt->op_bytes == 2) { ctxt->op_bytes = 4; desc_ptr.address &= 0x00ffffff; } /* Disable writeback. */ ctxt->dst.type = OP_NONE; return segmented_write(ctxt, ctxt->dst.addr.mem, &desc_ptr, 2 + ctxt->op_bytes); } Commit Message: KVM: x86: Introduce segmented_write_std Introduces segemented_write_std. Switches from emulated reads/writes to standard read/writes in fxsave, fxrstor, sgdt, and sidt. This fixes CVE-2017-2584, a longstanding kernel memory leak. Since commit 283c95d0e389 ("KVM: x86: emulate FXSAVE and FXRSTOR", 2016-11-09), which is luckily not yet in any final release, this would also be an exploitable kernel memory *write*! Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: 96051572c819194c37a8367624b285be10297eca Fixes: 283c95d0e3891b64087706b344a4b545d04a6e62 Suggested-by: Paolo Bonzini <[email protected]> Signed-off-by: Steve Rutherford <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static __exit void hardware_unsetup(void) { free_kvm_area(); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ unsigned long len = php_mysqlnd_net_field_length(&p); if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); } Commit Message: Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long mkvparser::GetUIntLength( IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); long long total, available; int status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); len = 1; if (pos >= available) return pos; //too few bytes available //// TODO(vigneshv): This function assumes that unsigned values never have their //// high bit set. unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) return status; assert(status == 0); if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } return 0; //success } 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 Target: 1 Example 2: Code: void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) { FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET); const FPDF_CharsetFontMap* font_map = FPDF_GetDefaultTTFMap(); for (; font_map->charset != -1; ++font_map) { FPDF_AddInstalledFont(mapper, font_map->fontname, font_map->charset); } } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(pg_connection_reset) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_BAD) { RETURN_FALSE; } RETURN_TRUE; } Commit Message: CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { const int shmkey = shmget(IPC_PRIVATE, size, 0666); if (shmkey == -1) { DLOG(ERROR) << "Failed to create SysV shared memory region" << " errno:" << errno; return NULL; } void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); shmctl(shmkey, IPC_RMID, 0); if (address == kInvalidAddress) return NULL; TransportDIB* dib = new TransportDIB; dib->key_.shmkey = shmkey; dib->address_ = address; dib->size_ = size; return dib; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: PHP_FUNCTION(pg_parameter_status) { zval *pgsql_link; int id; PGconn *pgsql; char *param; int len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &param, &len) == SUCCESS) { id = -1; } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &param, &len) == SUCCESS) { pgsql_link = NULL; id = PGG(default_link); } else { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); param = (char*)PQparameterStatus(pgsql, param); if (param) { RETURN_STRING(param, 1); } else { RETURN_FALSE; } } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)" R"([a-z][\u0585\u0581]+[a-z]|)" R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)" R"([\p{scx=armn}][og]+[\p{scx=armn}]|)" R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)" R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)" R"([^\p{scx=hebr}]\u05b4)", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: IDN display: Block U+0307 after i or U+0131 U+0307 (dot above) after i, j, l, or U+0131 (dotless i) would be very hard to see if possible at all. This is not blocked by the 'repeated diacritic' check because i is not decomposed into dotless-i + U+0307. So, it has to be blocked separately. Also, change the indentation in the output of idn_test_case_generator.py . This change blocks 80+ domains out of a million IDNs in .com TLD. BUG=750239 TEST=components_unittests --gtest_filter=*IDN* Change-Id: I4950aeb7aa080f92e38a2b5dea46ef4e5c25b65b Reviewed-on: https://chromium-review.googlesource.com/607907 Reviewed-by: Peter Kasting <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Matt Giuca <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#502987} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } Commit Message: Fix bug #72114 - int/size_t confusion in fread CWE ID: CWE-190 Target: 1 Example 2: Code: free_Folder(struct _7z_folder *f) { unsigned i; if (f->coders) { for (i = 0; i< f->numCoders; i++) { free(f->coders[i].properties); } free(f->coders); } free(f->bindPairs); free(f->packedStreams); free(f->unPackSize); } Commit Message: Issue #718: Fix TALOS-CAN-152 If a 7-Zip archive declares a rediculously large number of substreams, it can overflow an internal counter, leading a subsequent memory allocation to be too small for the substream data. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this issue. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static const char *req_range_field(request_rec *r) { return r->range; } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mark_screen_rdonly(struct mm_struct *mm) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; spinlock_t *ptl; int i; pgd = pgd_offset(mm, 0xA0000); if (pgd_none_or_clear_bad(pgd)) goto out; pud = pud_offset(pgd, 0xA0000); if (pud_none_or_clear_bad(pud)) goto out; pmd = pmd_offset(pud, 0xA0000); split_huge_page_pmd(mm, pmd); if (pmd_none_or_clear_bad(pmd)) goto out; pte = pte_offset_map_lock(mm, pmd, 0xA0000, &ptl); for (i = 0; i < 32; i++) { if (pte_present(*pte)) set_pte(pte, pte_wrprotect(*pte)); pte++; } pte_unmap_unlock(pte, ptl); out: flush_tlb(); } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: __nfs4_get_fd(struct nfs4_file *f, int oflag) { if (f->fi_fds[oflag]) return get_file(f->fi_fds[oflag]); return NULL; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static RELOC_PTRS_BEGIN(pattern2_instance_reloc_ptrs) { RELOC_PREFIX(st_pattern_instance); RELOC_SUPER(gs_pattern2_instance_t, st_pattern2_template, templat); } RELOC_PTRS_END Commit Message: CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { ND_PRINT((ndo," orig=(")); switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); break; case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN: if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA, (const struct isakmp_gen *)cp, ep, phase, doi, proto, depth) == NULL) return NULL; break; default: /* NULL is dummy */ isakmp_print(ndo, cp, item_len - sizeof(*p) - n.spi_size, NULL); } ND_PRINT((ndo,")")); } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data. The closest thing to a specification for the contents of the payload data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it is ever a complete ISAKMP message, so don't dissect types we don't have specific code for as a complete ISAKMP message. While we're at it, fix a comment, and clean up printing of V1 Nonce, V2 Authentication payloads, and v2 Notice payloads. This fixes an infinite loop discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-835 Target: 1 Example 2: Code: static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) { UINT32 front; if (count <= 0) return; if (count > zgfx->HistoryBufferSize) { const size_t residue = count - zgfx->HistoryBufferSize; count = zgfx->HistoryBufferSize; src += residue; zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; } if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) { CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; } else { front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); zgfx->HistoryIndex = count - front; } } Commit Message: Fixed CVE-2018-8784 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: top_proc(mrb_state *mrb, struct RProc *proc) { while (proc->upper) { if (MRB_PROC_SCOPE_P(proc) || MRB_PROC_STRICT_P(proc)) return proc; proc = proc->upper; } return proc; } Commit Message: Check length of env stack before accessing upvar; fix #3995 CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void timerfd_remove_cancel(struct timerfd_ctx *ctx) { if (ctx->might_cancel) { ctx->might_cancel = false; spin_lock(&cancel_lock); list_del_rcu(&ctx->clist); spin_unlock(&cancel_lock); } } Commit Message: timerfd: Protect the might cancel mechanism proper The handling of the might_cancel queueing is not properly protected, so parallel operations on the file descriptor can race with each other and lead to list corruptions or use after free. Protect the context for these operations with a seperate lock. The wait queue lock cannot be reused for this because that would create a lock inversion scenario vs. the cancel lock. Replacing might_cancel with an atomic (atomic_t or atomic bit) does not help either because it still can race vs. the actual list operation. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: "[email protected]" Cc: syzkaller <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos Signed-off-by: Thomas Gleixner <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static unsigned long oops_begin(void) { int cpu; unsigned long flags; oops_enter(); /* racy, but better than risking deadlock. */ raw_local_irq_save(flags); cpu = smp_processor_id(); if (!arch_spin_trylock(&die_lock)) { if (cpu == die_owner) /* nested oops. should stop eventually */; else arch_spin_lock(&die_lock); } die_nest_count++; die_owner = cpu; console_verbose(); bust_spinlocks(1); return flags; } Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to prevent it from being used as a covert channel between two tasks. There are more and more applications coming to Windows RT, Wine could support them, but mostly they expect to have the thread environment block (TEB) in TPIDRURW. This patch preserves that register per thread instead of clearing it. Unlike the TPIDRURO, which is already switched, the TPIDRURW can be updated from userspace so needs careful treatment in the case that we modify TPIDRURW and call fork(). To avoid this we must always read TPIDRURW in copy_thread. Signed-off-by: André Hentschel <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Jonathan Austin <[email protected]> Signed-off-by: Russell King <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: LocalSiteCharacteristicsDataImpl::LocalSiteCharacteristicsDataImpl( const url::Origin& origin, OnDestroyDelegate* delegate, LocalSiteCharacteristicsDatabase* database) : origin_(origin), loaded_tabs_count_(0U), loaded_tabs_in_background_count_(0U), database_(database), delegate_(delegate), safe_to_write_to_db_(false), is_dirty_(false), weak_factory_(this) { DCHECK(database_); DCHECK(delegate_); DCHECK(!site_characteristics_.IsInitialized()); database_->ReadSiteCharacteristicsFromDB( origin_, base::BindOnce(&LocalSiteCharacteristicsDataImpl::OnInitCallback, weak_factory_.GetWeakPtr())); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: 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 Target: 1 Example 2: Code: PDFiumEngine::FindTextIndex::FindTextIndex() : valid_(false), index_(0) { } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BrowserLauncherItemController::Clicked() { views::Widget* widget = views::Widget::GetWidgetForNativeView(window_); if (widget && widget->IsActive()) { widget->Minimize(); } else { Activate(); } } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len) { struct vendor_attribute *attr; attr = (struct vendor_attribute *)*data; *vendor = ntohl(attr->vendor_value); *data = attr->attrib_data; *len = attr->attrib_len - 2; return (attr->attrib_type); } Commit Message: Fix a security issue in radius_get_vendor_attr(). The underlying rad_get_vendor_attr() function assumed that it would always be given valid VSA data. Indeed, the buffer length wasn't even passed in; the assumption was that the length field within the VSA structure would be valid. This could result in denial of service by providing a length that would be beyond the memory limit, or potential arbitrary memory access by providing a length greater than the actual data given. rad_get_vendor_attr() has been changed to require the raw data length be provided, and this is then used to check that the VSA is valid. Conflicts: radlib_vs.h CWE ID: CWE-119 Target: 1 Example 2: Code: static int parse_one_feature(const char *feature, int from_stream) { const char *arg; if (skip_prefix(feature, "date-format=", &arg)) { option_date_format(arg); } else if (skip_prefix(feature, "import-marks=", &arg)) { option_import_marks(arg, from_stream, 0); } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) { option_import_marks(arg, from_stream, 1); } else if (skip_prefix(feature, "export-marks=", &arg)) { option_export_marks(arg); } else if (!strcmp(feature, "get-mark")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "cat-blob")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "relative-marks")) { relative_marks_paths = 1; } else if (!strcmp(feature, "no-relative-marks")) { relative_marks_paths = 0; } else if (!strcmp(feature, "done")) { require_explicit_termination = 1; } else if (!strcmp(feature, "force")) { force_update = 1; } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) { ; /* do nothing; we have the feature */ } else { return 0; } return 1; } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; struct sockaddr_in *sin; struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); msg->msg_namelen = 0; if (msg_flags & MSG_OOB) goto out; while (1) { /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); msg->msg_namelen = sizeof(*sin); } break; } if (inc) rds_inc_put(inc); out: return ret; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int _vivid_fb_check_var(struct fb_var_screeninfo *var, struct vivid_dev *dev) { dprintk(dev, 1, "vivid_fb_check_var\n"); var->bits_per_pixel = 16; if (var->green.length == 5) { var->red.offset = 10; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 15; var->transp.length = 1; } else { var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; } var->xoffset = var->yoffset = 0; var->left_margin = var->upper_margin = 0; var->nonstd = 0; var->vmode &= ~FB_VMODE_MASK; var->vmode = FB_VMODE_NONINTERLACED; /* Dummy values */ var->hsync_len = 24; var->vsync_len = 2; var->pixclock = 84316; var->right_margin = 776; var->lower_margin = 591; return 0; } Commit Message: [media] media/vivid-osd: fix info leak in ioctl The vivid_fb_ioctl() code fails to initialize the 16 _reserved bytes of struct fb_vblank after the ->hcount member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[email protected]> Signed-off-by: Hans Verkuil <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BrowserPolicyConnector::ScheduleServiceInitialization( int64 delay_milliseconds) { if (user_cloud_policy_subsystem_.get()) { user_cloud_policy_subsystem_-> ScheduleServiceInitialization(delay_milliseconds); } #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) { device_cloud_policy_subsystem_-> ScheduleServiceInitialization(delay_milliseconds); } #endif } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: JSValue JSWebKitMutationObserver::observe(ExecState* exec) { if (exec->argumentCount() < 2) return throwError(exec, createTypeError(exec, "Not enough arguments")); Node* target = toNode(exec->argument(0)); if (exec->hadException()) return jsUndefined(); JSObject* optionsObject = exec->argument(1).getObject(); if (!optionsObject) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } JSDictionary dictionary(exec, optionsObject); MutationObserverOptions options = 0; for (unsigned i = 0; i < numBooleanOptions; ++i) { bool option = false; if (!dictionary.tryGetProperty(booleanOptions[i].name, option)) return jsUndefined(); if (option) options |= booleanOptions[i].value; } HashSet<AtomicString> attributeFilter; if (!dictionary.tryGetProperty("attributeFilter", attributeFilter)) return jsUndefined(); if (!attributeFilter.isEmpty()) options |= WebKitMutationObserver::AttributeFilter; ExceptionCode ec = 0; impl()->observe(target, options, attributeFilter, ec); if (ec) setDOMException(exec, ec); return jsUndefined(); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: const AXObject* AXNodeObject::inheritsPresentationalRoleFrom() const { if (canSetFocusAttribute()) return 0; if (isPresentational()) return this; if (ariaRoleAttribute() != UnknownRole) return 0; AXObject* parent = parentObject(); if (!parent) return 0; HTMLElement* element = nullptr; if (getNode() && getNode()->isHTMLElement()) element = toHTMLElement(getNode()); if (!parent->hasInheritedPresentationalRole()) { if (!getLayoutObject() || !getLayoutObject()->isBoxModelObject()) return 0; LayoutBoxModelObject* cssBox = toLayoutBoxModelObject(getLayoutObject()); if (!cssBox->isTableCell() && !cssBox->isTableRow()) return 0; if (!isPresentationalInTable(parent, element)) return 0; } if (isRequiredOwnedElement(parent, roleValue(), element)) return parent; return 0; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; struct crypto_blkcipher *tfm = desc->tfm; struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm); int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, 64); salsa20_ivsetup(ctx, walk.iv); if (likely(walk.nbytes == nbytes)) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, nbytes); return blkcipher_walk_done(desc, &walk, 0); } while (walk.nbytes >= 64) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, walk.nbytes - (walk.nbytes % 64)); err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64); } if (walk.nbytes) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, walk.nbytes); err = blkcipher_walk_done(desc, &walk, 0); } return err; } Commit Message: crypto: salsa20 - fix blkcipher_walk API usage When asked to encrypt or decrypt 0 bytes, both the generic and x86 implementations of Salsa20 crash in blkcipher_walk_done(), either when doing 'kfree(walk->buffer)' or 'free_page((unsigned long)walk->page)', because walk->buffer and walk->page have not been initialized. The bug is that Salsa20 is calling blkcipher_walk_done() even when nothing is in 'walk.nbytes'. But blkcipher_walk_done() is only meant to be called when a nonzero number of bytes have been provided. The broken code is part of an optimization that tries to make only one call to salsa20_encrypt_bytes() to process inputs that are not evenly divisible by 64 bytes. To fix the bug, just remove this "optimization" and use the blkcipher_walk API the same way all the other users do. Reproducer: #include <linux/if_alg.h> #include <sys/socket.h> #include <unistd.h> int main() { int algfd, reqfd; struct sockaddr_alg addr = { .salg_type = "skcipher", .salg_name = "salsa20", }; char key[16] = { 0 }; algfd = socket(AF_ALG, SOCK_SEQPACKET, 0); bind(algfd, (void *)&addr, sizeof(addr)); reqfd = accept(algfd, 0, 0); setsockopt(algfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key)); read(reqfd, key, sizeof(key)); } Reported-by: syzbot <[email protected]> Fixes: eb6f13eb9f81 ("[CRYPTO] salsa20_generic: Fix multi-page processing") Cc: <[email protected]> # v2.6.25+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char buf[512], *actual_alias = NULL, *p; phar_entry_info entry = {0}; size_t pos = 0, read, totalsize; tar_header *hdr; php_uint32 sum1, sum2, size, old; phar_archive_data *myphar, **actual; int last_was_longlink = 0; if (error) { *error = NULL; } php_stream_seek(fp, 0, SEEK_END); totalsize = php_stream_tell(fp); php_stream_seek(fp, 0, SEEK_SET); read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is not a tar file or is truncated", fname); } php_stream_close(fp); return FAILURE; } hdr = (tar_header*)buf; old = (memcmp(hdr->magic, "ustar", sizeof("ustar")-1) != 0); myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); myphar->is_persistent = PHAR_G(persist); /* estimate number of entries, can't be certain with tar files */ zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11), zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); myphar->is_tar = 1; /* remember whether this entire phar was compressed with gz/bzip2 */ myphar->flags = compression; entry.is_tar = 1; entry.is_crc_checked = 1; entry.phar = myphar; pos += sizeof(buf); do { phar_entry_info *newentry; pos = php_stream_tell(fp); hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } memset(hdr->checksum, ' ', sizeof(hdr->checksum)); sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header)); size = entry.uncompressed_filesize = entry.compressed_filesize = phar_tar_number(hdr->size, sizeof(hdr->size)); if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(".phar/signature.bin")-1 && !strncmp(hdr->name, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { off_t curloc; if (size > 511) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has signature that is larger than 511 bytes, cannot process", fname); } bail: php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } curloc = php_stream_tell(fp); read = php_stream_read(fp, buf, size); if (read != size) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be read", fname); } goto bail; } #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer) \ (((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0])) #else # define PHAR_GET_32(buffer) (php_uint32) *(buffer) #endif myphar->sig_flags = PHAR_GET_32(buf); if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be verified: %s", fname, save); efree(save); } goto bail; } php_stream_seek(fp, curloc + 512, SEEK_SET); /* signature checked out, let's ensure this is the last file in the phar */ if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, 512, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } if (error) { spprintf(error, 4096, "phar error: \"%s\" has entries after signature, invalid phar", fname); } goto bail; } if (!last_was_longlink && hdr->typeflag == 'L') { last_was_longlink = 1; /* support the ././@LongLink system for storing long filenames */ entry.filename_len = entry.uncompressed_filesize; /* Check for overflow - bug 61065 */ if (entry.filename_len == UINT_MAX) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent); read = php_stream_read(fp, entry.filename, entry.filename_len); if (read != entry.filename_len) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename[entry.filename_len] = '\0'; /* skip blank stuff */ size = ((size+511)&~511) - size; /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } continue; } else if (!last_was_longlink && !old && hdr->prefix[0] != 0) { char name[256]; int i, j; for (i = 0; i < 155; i++) { name[i] = hdr->prefix[i]; if (name[i] == '\0') { break; } } name[i++] = '/'; for (j = 0; j < 100; j++) { name[i+j] = hdr->name[j]; if (name[i+j] == '\0') { break; } } entry.filename_len = i+j; if (name[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename_len--; } entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent); } else if (!last_was_longlink) { int i; /* calculate strlen, which can be no longer than 100 */ for (i = 0; i < 100; i++) { if (hdr->name[i] == '\0') { break; } } entry.filename_len = i; entry.filename = pestrndup(hdr->name, i, myphar->is_persistent); if (entry.filename[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename[entry.filename_len - 1] = '\0'; entry.filename_len--; } } last_was_longlink = 0; phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC); if (sum1 != sum2) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (checksum mismatch of file \"%s\")", fname, entry.filename); } pefree(entry.filename, myphar->is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag); entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */ entry.fp_type = PHAR_FP; entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK; entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime)); entry.is_persistent = myphar->is_persistent; #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) { entry.tar_type = TAR_DIR; } if (entry.tar_type == TAR_DIR) { entry.is_dir = 1; } else { entry.is_dir = 0; } entry.link = NULL; if (entry.tar_type == TAR_LINK) { if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file - hard link to non-existent file \"%s\"", fname, hdr->linkname); } pefree(entry.filename, entry.is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.link = estrdup(hdr->linkname); } else if (entry.tar_type == TAR_SYMLINK) { entry.link = estrdup(hdr->linkname); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry); if (entry.is_persistent) { ++entry.manifest_pos; } if (entry.filename_len >= sizeof(".phar/.metadata")-1 && !memcmp(entry.filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) { if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has invalid metadata in magic file \"%s\"", fname, entry.filename); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { /* found explicit alias */ if (size > 511) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has alias that is larger than 511 bytes, cannot process", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, size); if (read == size) { buf[size] = '\0'; if (!phar_validate_alias(buf, size)) { if (size > 50) { buf[50] = '.'; buf[51] = '.'; buf[52] = '.'; buf[53] = '\0'; } if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in tar-based phar \"%s\"", buf, fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } actual_alias = pestrndup(buf, size, myphar->is_persistent); myphar->alias = actual_alias; myphar->alias_len = size; php_stream_seek(fp, pos, SEEK_SET); } else { if (error) { spprintf(error, 4096, "phar error: Unable to read alias from tar-based phar \"%s\"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } size = (size+511)&~511; if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } while (read != 0); if (zend_hash_exists(&(myphar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { myphar->is_data = 0; } else { myphar->is_data = 1; } /* ensure signature set */ if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) { php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); if (error) { spprintf(error, 0, "tar-based phar \"%s\" does not have a signature", fname); } return FAILURE; } myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(myphar->fname, fname_len); #endif myphar->fname_len = fname_len; myphar->fp = fp; p = strrchr(myphar->fname, '/'); if (p) { myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p); if (myphar->ext == p) { myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1); } if (myphar->ext) { myphar->ext_len = (myphar->fname + fname_len) - myphar->ext; } } phar_request_initialize(TSRMLS_C); if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\" to phar registry", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } myphar = *actual; if (actual_alias) { phar_archive_data **fd_ptr; myphar->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent); myphar->alias_len = alias_len; } else { myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent); myphar->alias_len = fname_len; } myphar->is_temporary_alias = 1; } if (pphar) { *pphar = myphar; } return SUCCESS; } /* }}} */ Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static void readonlyWindowAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValueFast(info, WTF::getPtr(imp->readonlyWindowAttribute()), imp); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadJPEGImage(const ImageInfo *image_info, ExceptionInfo *exception) { char value[MaxTextExtent]; const char *option; ErrorManager error_manager; Image *image; IndexPacket index; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType debug, status; MagickSizeType number_pixels; MemoryInfo *memory_info; register ssize_t i; struct jpeg_decompress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; register JSAMPLE *p; size_t units; ssize_t y; /* 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); debug=IsEventLogging(); (void) debug; image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; memory_info=(MemoryInfo *) NULL; error_manager.image=image; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_decompress(&jpeg_info); if (error_manager.profile != (StringInfo *) NULL) error_manager.profile=DestroyStringInfo(error_manager.profile); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); InheritException(exception,&image->exception); return(DestroyImage(image)); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_decompress(&jpeg_info); JPEGSourceManager(&jpeg_info,image); jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment); option=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile); if (IsOptionMember("IPTC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile); for (i=1; i < 16; i++) if ((i != 2) && (i != 13) && (i != 14)) if (IsOptionMember("APP",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile); i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE); if ((image_info->colorspace == YCbCrColorspace) || (image_info->colorspace == Rec601YCbCrColorspace) || (image_info->colorspace == Rec709YCbCrColorspace)) jpeg_info.out_color_space=JCS_YCbCr; /* Set image resolution. */ units=0; if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) && (jpeg_info.Y_density != 1)) { image->x_resolution=(double) jpeg_info.X_density; image->y_resolution=(double) jpeg_info.Y_density; units=(size_t) jpeg_info.density_unit; } if (units == 1) image->units=PixelsPerInchResolution; if (units == 2) image->units=PixelsPerCentimeterResolution; number_pixels=(MagickSizeType) image->columns*image->rows; option=GetImageOption(image_info,"jpeg:size"); if ((option != (const char *) NULL) && (jpeg_info.out_color_space != JCS_YCbCr)) { double scale_factor; GeometryInfo geometry_info; MagickStatusType flags; /* Scale the image. */ flags=ParseGeometry(option,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_calc_output_dimensions(&jpeg_info); image->magick_columns=jpeg_info.output_width; image->magick_rows=jpeg_info.output_height; scale_factor=1.0; if (geometry_info.rho != 0.0) scale_factor=jpeg_info.output_width/geometry_info.rho; if ((geometry_info.sigma != 0.0) && (scale_factor > (jpeg_info.output_height/geometry_info.sigma))) scale_factor=jpeg_info.output_height/geometry_info.sigma; jpeg_info.scale_num=1U; jpeg_info.scale_denom=(unsigned int) scale_factor; jpeg_calc_output_dimensions(&jpeg_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Scale factor: %.20g",(double) scale_factor); } #if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED) #if defined(D_LOSSLESS_SUPPORTED) image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ? JPEGInterlace : NoInterlace; image->compression=jpeg_info.process == JPROC_LOSSLESS ? LosslessJPEGCompression : JPEGCompression; if (jpeg_info.data_precision > 8) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'", image->filename); if (jpeg_info.data_precision == 16) jpeg_info.data_precision=12; #else image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace : NoInterlace; image->compression=JPEGCompression; #endif #else image->compression=JPEGCompression; image->interlace=JPEGInterlace; #endif option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) { /* Let the JPEG library quantize for us. */ jpeg_info.quantize_colors=TRUE; jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option); } option=GetImageOption(image_info,"jpeg:block-smoothing"); if (option != (const char *) NULL) jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:fancy-upsampling"); if (option != (const char *) NULL) jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; (void) jpeg_start_decompress(&jpeg_info); image->columns=jpeg_info.output_width; image->rows=jpeg_info.output_height; image->depth=(size_t) jpeg_info.data_precision; switch (jpeg_info.out_color_space) { case JCS_RGB: default: { (void) SetImageColorspace(image,sRGBColorspace); break; } case JCS_GRAYSCALE: { (void) SetImageColorspace(image,GRAYColorspace); break; } case JCS_YCbCr: { (void) SetImageColorspace(image,YCbCrColorspace); break; } case JCS_CMYK: { (void) SetImageColorspace(image,CMYKColorspace); break; } } if (IsITUFaxImage(image) != MagickFalse) { (void) SetImageColorspace(image,LabColorspace); jpeg_info.out_color_space=JCS_YCbCr; } if (option != (const char *) NULL) if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == MagickFalse)) { size_t colors; colors=(size_t) GetQuantumRange(image->depth)+1; if (AcquireImageColormap(image,colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (image->debug != MagickFalse) { if (image->interlace != NoInterlace) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d", (int) jpeg_info.data_precision); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d", (int) jpeg_info.output_width,(int) jpeg_info.output_height); } JPEGSetImageQuality(&jpeg_info,image); JPEGSetImageSamplingFactor(&jpeg_info,image); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) jpeg_info.out_color_space); (void) SetImageProperty(image,"jpeg:colorspace",value); if (image_info->ping != MagickFalse) { jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.output_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); /* Convert JPEG pixels to pixel packets. */ if (setjmp(error_manager.error_recovery) != 0) { if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); return(DestroyImage(image)); } if (jpeg_info.quantize_colors != MagickFalse) { image->colors=(size_t) jpeg_info.actual_number_of_colors; if (jpeg_info.out_color_space == JCS_GRAYSCALE) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=image->colormap[i].red; image->colormap[i].blue=image->colormap[i].red; image->colormap[i].opacity=OpaqueOpacity; } else for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]); image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]); image->colormap[i].opacity=OpaqueOpacity; } } scanline[0]=(JSAMPROW) jpeg_pixels; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); continue; } p=jpeg_pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (jpeg_info.data_precision > 8) { unsigned short scale; scale=65535U/GetQuantumRange(jpeg_info.data_precision); if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { size_t pixel; pixel=(size_t) (scale*GETJSAMPLE(*p)); index=ConstrainColormapIndex(image,pixel); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum(scale*GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleShortToQuantum(scale*GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleShortToQuantum(scale*GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(scale* GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(scale* GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(scale* GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(scale* GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } } else if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum( (unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) { jpeg_abort_decompress(&jpeg_info); break; } } if (status != MagickFalse) { error_manager.finished=MagickTrue; if (setjmp(error_manager.error_recovery) == 0) (void) jpeg_finish_decompress(&jpeg_info); } /* Free jpeg resources. */ jpeg_destroy_decompress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal) { #ifdef PNG_USE_LOCAL_ARRAYS PNG_PLTE; #endif png_uint_32 i; png_colorp pal_ptr; png_byte buf[3]; png_debug(1, "in png_write_PLTE"); if (( #ifdef PNG_MNG_FEATURES_SUPPORTED !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) && #endif num_pal == 0) || num_pal > 256) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { png_error(png_ptr, "Invalid number of colors in palette"); } else { png_warning(png_ptr, "Invalid number of colors in palette"); return; } } if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) { png_warning(png_ptr, "Ignoring request to write a PLTE chunk in grayscale PNG"); return; } png_ptr->num_palette = (png_uint_16)num_pal; png_debug1(3, "num_palette = %d", png_ptr->num_palette); png_write_chunk_start(png_ptr, (png_bytep)png_PLTE, (png_uint_32)(num_pal * 3)); #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++) { buf[0] = pal_ptr->red; buf[1] = pal_ptr->green; buf[2] = pal_ptr->blue; png_write_chunk_data(png_ptr, buf, (png_size_t)3); } #else /* This is a little slower but some buggy compilers need to do this * instead */ pal_ptr=palette; for (i = 0; i < num_pal; i++) { buf[0] = pal_ptr[i].red; buf[1] = pal_ptr[i].green; buf[2] = pal_ptr[i].blue; png_write_chunk_data(png_ptr, buf, (png_size_t)3); } #endif png_write_chunk_end(png_ptr); png_ptr->mode |= PNG_HAVE_PLTE; } 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 Target: 1 Example 2: Code: void NavigationControllerImpl::LoadIfNecessary() { if (!needs_reload_) return; pending_entry_index_ = last_committed_entry_index_; NavigateToPendingEntry(NO_RELOAD); } Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof. BUG=280512 BUG=278899 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23978003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ChromeClientImpl::SetEventListenerProperties( LocalFrame* frame, WebEventListenerClass event_class, WebEventListenerProperties properties) { if (!frame) return; WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame); WebFrameWidgetBase* widget = web_frame->LocalRoot()->FrameWidget(); if (!widget) { DCHECK(properties == WebEventListenerProperties::kNothing); return; } WebWidgetClient* client = widget->Client(); if (WebLayerTreeView* tree_view = widget->GetLayerTreeView()) { tree_view->SetEventListenerProperties(event_class, properties); if (event_class == WebEventListenerClass::kTouchStartOrMove) { client->HasTouchEventHandlers( properties != WebEventListenerProperties::kNothing || tree_view->EventListenerProperties( WebEventListenerClass::kTouchEndOrCancel) != WebEventListenerProperties::kNothing); } else if (event_class == WebEventListenerClass::kTouchEndOrCancel) { client->HasTouchEventHandlers( properties != WebEventListenerProperties::kNothing || tree_view->EventListenerProperties( WebEventListenerClass::kTouchStartOrMove) != WebEventListenerProperties::kNothing); } } else { client->HasTouchEventHandlers(true); } } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *value = NULL; xmlChar *URI = NULL, *literal = NULL; const xmlChar *ndata = NULL; int isParameter = 0; xmlChar *orig = NULL; int skipped; /* GROW; done in the caller */ if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) { xmlParserInputPtr input = ctxt->input; SHRINK; SKIP(8); skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ENTITY'\n"); } if (RAW == '%') { NEXT; skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '%'\n"); } isParameter = 1; } name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityDecl: no name\n"); return; } if (xmlStrchr(name, ':') != NULL) { xmlNsErr(ctxt, XML_NS_ERR_COLON, "colon are forbidden from entities names '%s'\n", name, NULL, NULL); } skipped = SKIP_BLANKS; if (skipped == 0) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the entity name\n"); } ctxt->instate = XML_PARSER_ENTITY_DECL; /* * handle the various case of definitions... */ if (isParameter) { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if (value) { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_PARAMETER_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *) URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_PARAMETER_ENTITY, literal, URI, NULL); } xmlFreeURI(uri); } } } } else { if ((RAW == '"') || (RAW == '\'')) { value = xmlParseEntityValue(ctxt, &orig); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); /* * For expat compatibility in SAX mode. */ if ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, value); } } else { URI = xmlParseExternalID(ctxt, &literal, 1); if ((URI == NULL) && (literal == NULL)) { xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL); } if (URI) { xmlURIPtr uri; uri = xmlParseURI((const char *)URI); if (uri == NULL) { xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI, "Invalid URI: %s\n", URI); /* * This really ought to be a well formedness error * but the XML Core WG decided otherwise c.f. issue * E26 of the XML erratas. */ } else { if (uri->fragment != NULL) { /* * Okay this is foolish to block those but not * invalid URIs. */ xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL); } xmlFreeURI(uri); } } if ((RAW != '>') && (!IS_BLANK_CH(CUR))) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required before 'NDATA'\n"); } SKIP_BLANKS; if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) { SKIP(5); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'NDATA'\n"); } SKIP_BLANKS; ndata = xmlParseName(ctxt); if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->unparsedEntityDecl != NULL)) ctxt->sax->unparsedEntityDecl(ctxt->userData, name, literal, URI, ndata); } else { if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL)) ctxt->sax->entityDecl(ctxt->userData, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); /* * For expat compatibility in SAX mode. * assuming the entity repalcement was asked for */ if ((ctxt->replaceEntities != 0) && ((ctxt->myDoc == NULL) || (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) { if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if (ctxt->myDoc->intSubset == NULL) ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "fake", NULL, NULL); xmlSAX2EntityDecl(ctxt, name, XML_EXTERNAL_GENERAL_PARSED_ENTITY, literal, URI, NULL); } } } } SKIP_BLANKS; if (RAW != '>') { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, "xmlParseEntityDecl: entity %s not terminated\n", name); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Entity declaration doesn't start and stop in the same entity\n"); } NEXT; } if (orig != NULL) { /* * Ugly mechanism to save the raw entity value. */ xmlEntityPtr cur = NULL; if (isParameter) { if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) cur = ctxt->sax->getParameterEntity(ctxt->userData, name); } else { if ((ctxt->sax != NULL) && (ctxt->sax->getEntity != NULL)) cur = ctxt->sax->getEntity(ctxt->userData, name); if ((cur == NULL) && (ctxt->userData==ctxt)) { cur = xmlSAX2GetEntity(ctxt, name); } } if (cur != NULL) { if (cur->orig != NULL) xmlFree(orig); else cur->orig = orig; } else xmlFree(orig); } if (value != NULL) xmlFree(value); if (URI != NULL) xmlFree(URI); if (literal != NULL) xmlFree(literal); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: service_manager::InterfaceProvider* RenderFrameHostImpl::GetRemoteInterfaces() { return remote_interfaces_.get(); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool decode_dirsync_request(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; DATA_BLOB cookie; struct asn1_data *data = asn1_init(mem_ctx); struct ldb_dirsync_control *ldc; if (!data) return false; if (!asn1_load(data, in)) { return false; } ldc = talloc(mem_ctx, struct ldb_dirsync_control); if (!ldc) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } if (!asn1_read_Integer(data, &(ldc->flags))) { return false; } if (!asn1_read_Integer(data, &(ldc->max_attributes))) { return false; } if (!asn1_read_OctetString(data, mem_ctx, &cookie)) { return false; } ldc->cookie_len = cookie.length; if (ldc->cookie_len) { ldc->cookie = talloc_memdup(ldc, cookie.data, cookie.length); if (!(ldc->cookie)) { return false; } } else { ldc->cookie = NULL; } if (!asn1_end_tag(data)) { return false; } *out = ldc; return true; } Commit Message: CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: atol8(const char *p, size_t char_cnt) { int64_t l; int digit; l = 0; while (char_cnt-- > 0) { if (*p >= '0' && *p <= '7') digit = *p - '0'; else break; p++; l <<= 3; l |= digit; } return (l); } Commit Message: Do something sensible for empty strings to make fuzzers happy. CWE ID: CWE-125 Target: 1 Example 2: Code: void ArthurOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, GBool inlineImg) { qDebug() << "drawImageMask"; #if 0 unsigned char *buffer; unsigned char *dest; cairo_surface_t *image; cairo_pattern_t *pattern; int x, y; ImageStream *imgStr; Guchar *pix; double *ctm; cairo_matrix_t matrix; int invert_bit; int row_stride; row_stride = (width + 3) & ~3; buffer = (unsigned char *) malloc (height * row_stride); if (buffer == NULL) { error(-1, "Unable to allocate memory for image."); return; } /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, 1, 1); imgStr->reset(); invert_bit = invert ? 1 : 0; for (y = 0; y < height; y++) { pix = imgStr->getLine(); dest = buffer + y * row_stride; for (x = 0; x < width; x++) { if (pix[x] ^ invert_bit) *dest++ = 0; else *dest++ = 255; } } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_A8, width, height, row_stride); if (image == NULL) return; pattern = cairo_pattern_create_for_surface (image); if (pattern == NULL) return; ctm = state->getCTM(); LOG (printf ("drawImageMask %dx%d, matrix: %f, %f, %f, %f, %f, %f\n", width, height, ctm[0], ctm[1], ctm[2], ctm[3], ctm[4], ctm[5])); matrix.xx = ctm[0] / width; matrix.xy = -ctm[2] / height; matrix.yx = ctm[1] / width; matrix.yy = -ctm[3] / height; matrix.x0 = ctm[2] + ctm[4]; matrix.y0 = ctm[3] + ctm[5]; cairo_matrix_invert (&matrix); cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BEST); /* FIXME: Doesn't the image mask support any colorspace? */ cairo_set_source_rgb (cairo, fill_color.r, fill_color.g, fill_color.b); cairo_mask (cairo, pattern); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); delete imgStr; #endif } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::SendFailedProvisionalLoad( const blink::WebURLRequest& request, const blink::WebURLError& error, blink::WebLocalFrame* frame) { bool show_repost_interstitial = (error.reason == net::ERR_CACHE_MISS && base::EqualsASCII(base::StringPiece16(request.httpMethod()), "POST")); FrameHostMsg_DidFailProvisionalLoadWithError_Params params; params.error_code = error.reason; GetContentClient()->renderer()->GetNavigationErrorStrings( render_view_.get(), frame, request, error, NULL, &params.error_description); params.url = error.unreachableURL; params.showing_repost_interstitial = show_repost_interstitial; params.was_ignored_by_handler = error.wasIgnoredByHandler; Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params)); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Track::GetFirst(const BlockEntry*& pBlockEntry) const { const Cluster* pCluster = m_pSegment->GetFirst(); for (int i = 0;;) { if (pCluster == NULL) { pBlockEntry = GetEOS(); return 1; } if (pCluster->EOS()) { #if 0 if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded pBlockEntry = GetEOS(); return 1; } #else if (m_pSegment->DoneParsing()) { pBlockEntry = GetEOS(); return 1; } #endif pBlockEntry = 0; return E_BUFFER_NOT_FULL; } long status = pCluster->GetFirst(pBlockEntry); if (status < 0) // error return status; if (pBlockEntry == 0) { // empty cluster pCluster = m_pSegment->GetNext(pCluster); continue; } for (;;) { const Block* const pBlock = pBlockEntry->GetBlock(); assert(pBlock); const long long tn = pBlock->GetTrackNumber(); if ((tn == m_info.number) && VetEntry(pBlockEntry)) return 0; const BlockEntry* pNextEntry; status = pCluster->GetNext(pBlockEntry, pNextEntry); if (status < 0) // error return status; if (pNextEntry == 0) break; pBlockEntry = pNextEntry; } ++i; if (i >= 100) break; pCluster = m_pSegment->GetNext(pCluster); } pBlockEntry = GetEOS(); // so we can return a non-NULL value return 1; } 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 Target: 1 Example 2: Code: void RenderFrameHostImpl::CommitNavigation( NavigationRequest* navigation_request, network::ResourceResponse* response, network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, const CommonNavigationParams& common_params, const CommitNavigationParams& commit_params, bool is_view_source, base::Optional<SubresourceLoaderParams> subresource_loader_params, base::Optional<std::vector<mojom::TransferrableURLLoaderPtr>> subresource_overrides, blink::mojom::ServiceWorkerProviderInfoForWindowPtr provider_info, const base::UnguessableToken& devtools_navigation_token) { TRACE_EVENT2("navigation", "RenderFrameHostImpl::CommitNavigation", "frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url", common_params.url.possibly_invalid_spec()); DCHECK(!IsRendererDebugURL(common_params.url)); DCHECK( (response && url_loader_client_endpoints) || common_params.url.SchemeIs(url::kDataScheme) || FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type) || !IsURLHandledByNetworkStack(common_params.url)); const bool is_first_navigation = !has_committed_any_navigation_; has_committed_any_navigation_ = true; UpdatePermissionsForNavigation(common_params, commit_params); ResetWaitingState(); if (is_view_source && IsCurrent()) { DCHECK(!GetParent()); render_view_host()->Send(new FrameMsg_EnableViewSourceMode(routing_id_)); } const network::ResourceResponseHead head = response ? response->head : network::ResourceResponseHead(); const bool is_same_document = FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type); std::unique_ptr<blink::URLLoaderFactoryBundleInfo> subresource_loader_factories; if (base::FeatureList::IsEnabled(network::features::kNetworkService) && (!is_same_document || is_first_navigation)) { recreate_default_url_loader_factory_after_network_service_crash_ = false; subresource_loader_factories = std::make_unique<blink::URLLoaderFactoryBundleInfo>(); BrowserContext* browser_context = GetSiteInstance()->GetBrowserContext(); if (subresource_loader_params && subresource_loader_params->appcache_loader_factory_info.is_valid()) { subresource_loader_factories->appcache_factory_info() = std::move(subresource_loader_params->appcache_loader_factory_info); if (!GetCreateNetworkFactoryCallbackForRenderFrame().is_null()) { network::mojom::URLLoaderFactoryPtrInfo original_factory = std::move(subresource_loader_factories->appcache_factory_info()); network::mojom::URLLoaderFactoryRequest new_request = mojo::MakeRequest( &subresource_loader_factories->appcache_factory_info()); GetCreateNetworkFactoryCallbackForRenderFrame().Run( std::move(new_request), GetProcess()->GetID(), std::move(original_factory)); } } non_network_url_loader_factories_.clear(); network::mojom::URLLoaderFactoryPtrInfo default_factory_info; std::string scheme = common_params.url.scheme(); const auto& webui_schemes = URLDataManagerBackend::GetWebUISchemes(); if (base::ContainsValue(webui_schemes, scheme)) { network::mojom::URLLoaderFactoryPtr factory_for_webui = CreateWebUIURLLoaderBinding(this, scheme); if ((enabled_bindings_ & kWebUIBindingsPolicyMask) && !GetContentClient()->browser()->IsWebUIAllowedToMakeNetworkRequests( url::Origin::Create(common_params.url.GetOrigin()))) { default_factory_info = factory_for_webui.PassInterface(); non_network_url_loader_factories_[url::kAboutScheme] = std::make_unique<AboutURLLoaderFactory>(); } else { subresource_loader_factories->scheme_specific_factory_infos().emplace( scheme, factory_for_webui.PassInterface()); } } if (!default_factory_info) { recreate_default_url_loader_factory_after_network_service_crash_ = true; bool bypass_redirect_checks = CreateNetworkServiceDefaultFactoryAndObserve( GetOriginForURLLoaderFactory(common_params), mojo::MakeRequest(&default_factory_info)); subresource_loader_factories->set_bypass_redirect_checks( bypass_redirect_checks); } DCHECK(default_factory_info); subresource_loader_factories->default_factory_info() = std::move(default_factory_info); if (common_params.url.SchemeIsFile()) { auto file_factory = std::make_unique<FileURLLoaderFactory>( browser_context->GetPath(), browser_context->GetSharedCorsOriginAccessList(), base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); non_network_url_loader_factories_.emplace(url::kFileScheme, std::move(file_factory)); } #if defined(OS_ANDROID) if (common_params.url.SchemeIs(url::kContentScheme)) { auto content_factory = std::make_unique<ContentURLLoaderFactory>( base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); non_network_url_loader_factories_.emplace(url::kContentScheme, std::move(content_factory)); } #endif StoragePartition* partition = BrowserContext::GetStoragePartition(browser_context, GetSiteInstance()); std::string storage_domain; if (site_instance_) { std::string partition_name; bool in_memory; GetContentClient()->browser()->GetStoragePartitionConfigForSite( browser_context, site_instance_->GetSiteURL(), true, &storage_domain, &partition_name, &in_memory); } non_network_url_loader_factories_.emplace( url::kFileSystemScheme, content::CreateFileSystemURLLoaderFactory( this, /*is_navigation=*/false, partition->GetFileSystemContext(), storage_domain)); non_network_url_loader_factories_.emplace( url::kDataScheme, std::make_unique<DataURLLoaderFactory>()); GetContentClient() ->browser() ->RegisterNonNetworkSubresourceURLLoaderFactories( process_->GetID(), routing_id_, &non_network_url_loader_factories_); for (auto& factory : non_network_url_loader_factories_) { network::mojom::URLLoaderFactoryPtrInfo factory_proxy_info; auto factory_request = mojo::MakeRequest(&factory_proxy_info); GetContentClient()->browser()->WillCreateURLLoaderFactory( browser_context, this, GetProcess()->GetID(), false /* is_navigation */, false /* is_download */, GetOriginForURLLoaderFactory(common_params), &factory_request, nullptr /* header_client */, nullptr /* bypass_redirect_checks */); devtools_instrumentation::WillCreateURLLoaderFactory( this, false /* is_navigation */, false /* is_download */, &factory_request); factory.second->Clone(std::move(factory_request)); subresource_loader_factories->scheme_specific_factory_infos().emplace( factory.first, std::move(factory_proxy_info)); } subresource_loader_factories->initiator_specific_factory_infos() = CreateInitiatorSpecificURLLoaderFactories( initiators_requiring_separate_url_loader_factory_); } DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService) || is_same_document || !is_first_navigation || subresource_loader_factories); if (is_same_document) { DCHECK(same_document_navigation_request_); GetNavigationControl()->CommitSameDocumentNavigation( common_params, commit_params, base::BindOnce(&RenderFrameHostImpl::OnSameDocumentCommitProcessed, base::Unretained(this), same_document_navigation_request_->navigation_handle() ->GetNavigationId(), common_params.should_replace_current_entry)); } else { blink::mojom::ControllerServiceWorkerInfoPtr controller; blink::mojom::ServiceWorkerObjectAssociatedPtrInfo remote_object; blink::mojom::ServiceWorkerState sent_state; if (subresource_loader_params && subresource_loader_params->controller_service_worker_info) { controller = std::move(subresource_loader_params->controller_service_worker_info); if (controller->object_info) { controller->object_info->request = mojo::MakeRequest(&remote_object); sent_state = controller->object_info->state; } } std::unique_ptr<blink::URLLoaderFactoryBundleInfo> factory_bundle_for_prefetch; network::mojom::URLLoaderFactoryPtr prefetch_loader_factory; if (subresource_loader_factories) { auto bundle = base::MakeRefCounted<blink::URLLoaderFactoryBundle>( std::move(subresource_loader_factories)); subresource_loader_factories = CloneFactoryBundle(bundle); factory_bundle_for_prefetch = CloneFactoryBundle(bundle); } else if (!is_same_document || is_first_navigation) { DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService)); factory_bundle_for_prefetch = std::make_unique<blink::URLLoaderFactoryBundleInfo>(); network::mojom::URLLoaderFactoryPtrInfo factory_info; CreateNetworkServiceDefaultFactoryInternal( url::Origin(), mojo::MakeRequest(&factory_info)); factory_bundle_for_prefetch->default_factory_info() = std::move(factory_info); } if (factory_bundle_for_prefetch) { auto* storage_partition = static_cast<StoragePartitionImpl*>( BrowserContext::GetStoragePartition( GetSiteInstance()->GetBrowserContext(), GetSiteInstance())); base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PrefetchURLLoaderService::GetFactory, storage_partition->GetPrefetchURLLoaderService(), mojo::MakeRequest(&prefetch_loader_factory), frame_tree_node_->frame_tree_node_id(), std::move(factory_bundle_for_prefetch))); } mojom::NavigationClient* navigation_client = nullptr; if (IsPerNavigationMojoInterfaceEnabled() && navigation_request) navigation_client = navigation_request->GetCommitNavigationClient(); if (!GetParent() && frame_tree_node()->current_frame_host() == this) { if (NavigationEntryImpl* last_committed_entry = NavigationEntryImpl::FromNavigationEntry( frame_tree_node() ->navigator() ->GetController() ->GetLastCommittedEntry())) { if (last_committed_entry->back_forward_cache_metrics()) { last_committed_entry->back_forward_cache_metrics() ->RecordFeatureUsage(this); } } } SendCommitNavigation( navigation_client, navigation_request, head, common_params, commit_params, std::move(url_loader_client_endpoints), std::move(subresource_loader_factories), std::move(subresource_overrides), std::move(controller), std::move(provider_info), std::move(prefetch_loader_factory), devtools_navigation_token); if (remote_object.is_valid()) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerObjectHost::AddRemoteObjectPtrAndUpdateState, subresource_loader_params->controller_service_worker_object_host, std::move(remote_object), sent_state)); } if (IsURLHandledByNetworkStack(common_params.url)) last_navigation_previews_state_ = common_params.previews_state; } is_loading_ = true; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PaintController::CopyCachedSubsequence(size_t begin_index, size_t end_index) { DCHECK(!RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()); base::AutoReset<size_t> subsequence_begin_index( &current_cached_subsequence_begin_index_in_new_list_, new_display_item_list_.size()); DisplayItem* cached_item = &current_paint_artifact_.GetDisplayItemList()[begin_index]; Vector<PaintChunk>::const_iterator cached_chunk; base::Optional<PropertyTreeState> properties_before_subsequence; if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { cached_chunk = current_paint_artifact_.FindChunkByDisplayItemIndex(begin_index); DCHECK(cached_chunk != current_paint_artifact_.PaintChunks().end()); properties_before_subsequence = new_paint_chunks_.CurrentPaintChunkProperties(); UpdateCurrentPaintChunkPropertiesUsingIdWithFragment( cached_chunk->id, cached_chunk->properties.GetPropertyTreeState()); } else { cached_chunk = current_paint_artifact_.PaintChunks().begin(); } for (size_t current_index = begin_index; current_index < end_index; ++current_index) { cached_item = &current_paint_artifact_.GetDisplayItemList()[current_index]; SECURITY_CHECK(!cached_item->IsTombstone()); #if DCHECK_IS_ON() DCHECK(cached_item->Client().IsAlive()); #endif if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && current_index == cached_chunk->end_index) { ++cached_chunk; DCHECK(cached_chunk != current_paint_artifact_.PaintChunks().end()); new_paint_chunks_.ForceNewChunk(); UpdateCurrentPaintChunkPropertiesUsingIdWithFragment( cached_chunk->id, cached_chunk->properties.GetPropertyTreeState()); } #if DCHECK_IS_ON() if (cached_item->VisualRect() != FloatRect(cached_item->Client().VisualRect())) { LOG(ERROR) << "Visual rect changed in a cached subsequence: " << cached_item->Client().DebugName() << " old=" << cached_item->VisualRect().ToString() << " new=" << cached_item->Client().VisualRect().ToString(); } #endif ProcessNewItem(MoveItemFromCurrentListToNewList(current_index)); if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { DCHECK((!new_paint_chunks_.LastChunk().is_cacheable && !cached_chunk->is_cacheable) || new_paint_chunks_.LastChunk().Matches(*cached_chunk)); } } if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { under_invalidation_checking_end_ = end_index; DCHECK(IsCheckingUnderInvalidation()); } else if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { new_paint_chunks_.ForceNewChunk(); UpdateCurrentPaintChunkProperties(base::nullopt, *properties_before_subsequence); } } 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: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;" "[зӡ] > 3"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Map U+04CF to lowercase L as well. U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered in some fonts. If a host name contains it, calculate the confusability skeleton twice, once with the default mapping to 'i' (lowercase I) and the 2nd time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L) also gets it treated as similar to digit 1 because the confusability skeleton of digit 1 is 'l'. Bug: 817247 Test: components_unittests --gtest_filter=*IDN* Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c Reviewed-on: https://chromium-review.googlesource.com/974165 Commit-Queue: Jungshik Shin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Reviewed-by: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#551263} CWE ID: Target: 1 Example 2: Code: static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu, struct vmx_msr_entry *e) { if (e->index == MSR_FS_BASE || e->index == MSR_GS_BASE || e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */ nested_vmx_msr_check_common(vcpu, e)) return -EINVAL; return 0; } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void UpdatePropertyCallback(IBusPanelService* panel, IBusProperty* ibus_prop, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateProperty(ibus_prop); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long SeekHead::Parse() { IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = m_start; const long long stop = m_start + m_size; int entry_count = 0; int void_element_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x0DBB) //SeekEntry ID ++entry_count; else if (id == 0x6C) //Void ID ++void_element_count; pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); m_entries = new (std::nothrow) Entry[entry_count]; if (m_entries == NULL) return -1; m_void_elements = new (std::nothrow) VoidElement[void_element_count]; if (m_void_elements == NULL) return -1; Entry* pEntry = m_entries; VoidElement* pVoidElement = m_void_elements; pos = m_start; while (pos < stop) { const long long idpos = pos; long long id, size; const long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x0DBB) //SeekEntry ID { if (ParseEntry(pReader, pos, size, pEntry)) { Entry& e = *pEntry++; e.element_start = idpos; e.element_size = (pos + size) - idpos; } } else if (id == 0x6C) //Void ID { VoidElement& e = *pVoidElement++; e.element_start = idpos; e.element_size = (pos + size) - idpos; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries); assert(count_ >= 0); assert(count_ <= entry_count); m_entry_count = static_cast<int>(count_); count_ = ptrdiff_t(pVoidElement - m_void_elements); assert(count_ >= 0); assert(count_ <= void_element_count); m_void_element_count = static_cast<int>(count_); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx) { int i, nr_msrs; struct perf_guest_switch_msr *msrs; msrs = perf_guest_get_msrs(&nr_msrs); if (!msrs) return; for (i = 0; i < nr_msrs; i++) if (msrs[i].host == msrs[i].guest) clear_atomic_switch_msr(vmx, msrs[i].msr); else add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest, msrs[i].host); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c ) { chunkType = c; // base class assumption this->parent = parent; this->oldSize = 0; this->hasChange = false; // [2414649] valid assumption at creation time XMP_IO* file = handler->parent->ioRef; this->oldPos = file->Offset(); this->id = XIO::ReadUns32_LE( file ); this->oldSize = XIO::ReadUns32_LE( file ) + 8; XMP_Int64 chunkEnd = this->oldPos + this->oldSize; if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize; if ( chunkEnd > chunkLimit ) { bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate ); bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile ); if ( (! isUpdate) || (repairFile && (parent == 0)) ) { this->oldSize = chunkLimit - this->oldPos; } else { XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat ); } } this->newSize = this->oldSize; this->needSizeFix = false; if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent ); if ( this->parent != NULL ) { this->parent->children.push_back( this ); if( this->chunkType == chunk_VALUE ) this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) ); } } Commit Message: CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FetchContext::DispatchWillSendRequest(unsigned long, ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&) {} Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 1 Example 2: Code: stop_server(char *prefix, char *port) { char *path = NULL; int pid, path_size = strlen(prefix) + strlen(port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.pid", prefix, port); FILE *f = fopen(path, "r"); if (f == NULL) { if (verbose) { LOGE("unable to open pid file"); } ss_free(path); return; } if (fscanf(f, "%d", &pid) != EOF) { kill(pid, SIGTERM); } fclose(f); ss_free(path); } Commit Message: Fix #1734 CWE ID: CWE-78 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PlatformSensorFusion::PlatformSensorFusion( mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm, PlatformSensorFusion::SourcesMap sources) : PlatformSensor(fusion_algorithm->fused_type(), std::move(mapping), provider), fusion_algorithm_(std::move(fusion_algorithm)), source_sensors_(std::move(sources)), reporting_mode_(mojom::ReportingMode::CONTINUOUS) { for (const auto& pair : source_sensors_) pair.second->AddClient(this); fusion_algorithm_->set_fusion_sensor(this); if (std::any_of(source_sensors_.begin(), source_sensors_.end(), [](const SourcesMapEntry& pair) { return pair.second->GetReportingMode() == mojom::ReportingMode::ON_CHANGE; })) { reporting_mode_ = mojom::ReportingMode::ON_CHANGE; } } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual InputMethodDescriptors* GetActiveInputMethods() { chromeos::InputMethodDescriptors* result = new chromeos::InputMethodDescriptors; for (size_t i = 0; i < active_input_method_ids_.size(); ++i) { const std::string& input_method_id = active_input_method_ids_[i]; const InputMethodDescriptor* descriptor = chromeos::input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { result->push_back(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } } if (result->empty()) { LOG(WARNING) << "No active input methods found."; result->push_back(input_method::GetFallbackInputMethodDescriptor()); } return result; } 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 Target: 1 Example 2: Code: static void domStringListFunctionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "domStringListFunction", "TestObject", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 1)) { exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, info.Length())); exceptionState.throwIfNeeded(); return; } TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_VOID(DOMStringList*, values, V8DOMStringList::toNativeWithTypeCheck(info.GetIsolate(), info[0])); RefPtr<DOMStringList> result = imp->domStringListFunction(values, exceptionState); if (exceptionState.throwIfNeeded()) return; v8SetReturnValue(info, result.release()); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM( uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) { GLuint count = c.count; uint32 pnames_size; if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) { return error::kOutOfBounds; } const GLenum* pnames = GetSharedMemoryAs<const GLenum*>( c.pnames_shm_id, c.pnames_shm_offset, pnames_size); if (pnames == NULL) { return error::kOutOfBounds; } scoped_array<GLenum> enums(new GLenum[count]); memcpy(enums.get(), pnames, pnames_size); uint32 num_results = 0; for (GLuint ii = 0; ii < count; ++ii) { uint32 num = util_.GLGetNumValuesReturned(enums[ii]); if (num == 0) { SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname"); return error::kNoError; } DCHECK_LE(num, 4u); if (!SafeAdd(num_results, num, &num_results)) { return error::kOutOfBounds; } } uint32 result_size = 0; if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) { return error::kOutOfBounds; } if (result_size != static_cast<uint32>(c.size)) { SetGLError(GL_INVALID_VALUE, "glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE"); return error::kNoError; } GLint* results = GetSharedMemoryAs<GLint*>( c.results_shm_id, c.results_shm_offset, result_size); if (results == NULL) { return error::kOutOfBounds; } for (uint32 ii = 0; ii < num_results; ++ii) { if (results[ii]) { return error::kInvalidArguments; } } GLint* start = results; for (GLuint ii = 0; ii < count; ++ii) { GLsizei num_written = 0; if (!GetHelper(enums[ii], results, &num_written)) { glGetIntegerv(enums[ii], results); } results += num_written; } if (static_cast<uint32>(results - start) != num_results) { return error::kOutOfBounds; } return error::kNoError; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { png_structp png_ptr = *ptr_ptr; #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_write_init() and should be recompiled."); #endif } i++; } while (png_libpng_ver[i] != 0 && user_png_ver[i] != 0); png_debug(1, "in png_write_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); *ptr_ptr = png_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, 1, png_doublep_NULL, png_doublep_NULL); #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void unset_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { vpx_active_map_t map = {0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = NULL; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod7(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); DOMStringList* arrayArg(toDOMStringList(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(arrayArg); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: irc_ctcp_reply_to_nick (struct t_irc_server *server, const char *command, struct t_irc_channel *channel, const char *nick, const char *ctcp, const char *arguments) { struct t_hashtable *hashtable; int number; char hash_key[32]; const char *str_args; char *str_args_color; hashtable = irc_server_sendf ( server, IRC_SERVER_SEND_OUTQ_PRIO_LOW | IRC_SERVER_SEND_RETURN_HASHTABLE, NULL, "NOTICE %s :\01%s%s%s\01", nick, ctcp, (arguments) ? " " : "", (arguments) ? arguments : ""); if (hashtable) { if (weechat_config_boolean (irc_config_look_display_ctcp_reply)) { number = 1; while (1) { snprintf (hash_key, sizeof (hash_key), "args%d", number); str_args = weechat_hashtable_get (hashtable, hash_key); if (!str_args) break; str_args_color = irc_color_decode (str_args, 1); if (!str_args_color) break; weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", (channel) ? channel->buffer : NULL), 0, irc_protocol_tags ( command, "irc_ctcp,irc_ctcp_reply,self_msg,notify_none," "no_highlight", NULL, NULL), _("%sCTCP reply to %s%s%s: %s%s%s%s%s"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, ctcp, (str_args_color[0]) ? IRC_COLOR_RESET : "", (str_args_color[0]) ? " " : "", str_args_color); free (str_args_color); number++; } } weechat_hashtable_free (hashtable); } } Commit Message: irc: fix parsing of DCC filename CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); return(xmlStrndup(buf, len)); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: int shmem_unuse(swp_entry_t swap, struct page *page) { return 0; } Commit Message: tmpfs: fix use-after-free of mempolicy object The tmpfs remount logic preserves filesystem mempolicy if the mpol=M option is not specified in the remount request. A new policy can be specified if mpol=M is given. Before this patch remounting an mpol bound tmpfs without specifying mpol= mount option in the remount request would set the filesystem's mempolicy object to a freed mempolicy object. To reproduce the problem boot a DEBUG_PAGEALLOC kernel and run: # mkdir /tmp/x # mount -t tmpfs -o size=100M,mpol=interleave nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=102400k,mpol=interleave:0-3 0 0 # mount -o remount,size=200M nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=204800k,mpol=??? 0 0 # note ? garbage in mpol=... output above # dd if=/dev/zero of=/tmp/x/f count=1 # panic here Panic: BUG: unable to handle kernel NULL pointer dereference at (null) IP: [< (null)>] (null) [...] Oops: 0010 [#1] SMP DEBUG_PAGEALLOC Call Trace: mpol_shared_policy_init+0xa5/0x160 shmem_get_inode+0x209/0x270 shmem_mknod+0x3e/0xf0 shmem_create+0x18/0x20 vfs_create+0xb5/0x130 do_last+0x9a1/0xea0 path_openat+0xb3/0x4d0 do_filp_open+0x42/0xa0 do_sys_open+0xfe/0x1e0 compat_sys_open+0x1b/0x20 cstar_dispatch+0x7/0x1f Non-debug kernels will not crash immediately because referencing the dangling mpol will not cause a fault. Instead the filesystem will reference a freed mempolicy object, which will cause unpredictable behavior. The problem boils down to a dropped mpol reference below if shmem_parse_options() does not allocate a new mpol: config = *sbinfo shmem_parse_options(data, &config, true) mpol_put(sbinfo->mpol) sbinfo->mpol = config.mpol /* BUG: saves unreferenced mpol */ This patch avoids the crash by not releasing the mempolicy if shmem_parse_options() doesn't create a new mpol. How far back does this issue go? I see it in both 2.6.36 and 3.3. I did not look back further. Signed-off-by: Greg Thelen <[email protected]> Acked-by: Hugh Dickins <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AppControllerImpl::AppControllerImpl(Profile* profile) //// static : profile_(profile), app_service_proxy_(apps::AppServiceProxy::Get(profile)), url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( chromeos::switches::kKioskNextHomeUrlPrefix)) { app_service_proxy_->AppRegistryCache().AddObserver(this); if (profile) { content::URLDataSource::Add(profile, std::make_unique<apps::AppIconSource>(profile)); } } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ImageLoader::ImageLoader(Element* element) : m_element(element), m_derefElementTimer(this, &ImageLoader::timerFired), m_hasPendingLoadEvent(false), m_hasPendingErrorEvent(false), m_imageComplete(true), m_loadingImageDocument(false), m_elementIsProtected(false), m_suppressErrorEvents(false) { RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this; } Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer. Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer. This associates it with the frame's Networking timer task queue. BUG=624694 Review-Url: https://codereview.chromium.org/2642103002 Cr-Commit-Position: refs/heads/master@{#444927} CWE ID: Target: 1 Example 2: Code: static int airspy_s_frequency(struct file *file, void *priv, const struct v4l2_frequency *f) { struct airspy *s = video_drvdata(file); int ret; u8 buf[4]; if (f->tuner == 0) { s->f_adc = clamp_t(unsigned int, f->frequency, bands[0].rangelow, bands[0].rangehigh); dev_dbg(s->dev, "ADC frequency=%u Hz\n", s->f_adc); ret = 0; } else if (f->tuner == 1) { s->f_rf = clamp_t(unsigned int, f->frequency, bands_rf[0].rangelow, bands_rf[0].rangehigh); dev_dbg(s->dev, "RF frequency=%u Hz\n", s->f_rf); buf[0] = (s->f_rf >> 0) & 0xff; buf[1] = (s->f_rf >> 8) & 0xff; buf[2] = (s->f_rf >> 16) & 0xff; buf[3] = (s->f_rf >> 24) & 0xff; ret = airspy_ctrl_msg(s, CMD_SET_FREQ, 0, 0, buf, 4); } else { ret = -EINVAL; } return ret; } Commit Message: media: fix airspy usb probe error path Fix a memory leak on probe error of the airspy usb device driver. The problem is triggered when more than 64 usb devices register with v4l2 of type VFL_TYPE_SDR or VFL_TYPE_SUBDEV. The memory leak is caused by the probe function of the airspy driver mishandeling errors and not freeing the corresponding control structures when an error occours registering the device to v4l2 core. A badusb device can emulate 64 of these devices, and then through continual emulated connect/disconnect of the 65th device, cause the kernel to run out of RAM and crash the kernel, thus causing a local DOS vulnerability. Fixes CVE-2016-5400 Signed-off-by: James Patrick-Evans <[email protected]> Reviewed-by: Kees Cook <[email protected]> Cc: [email protected] # 3.17+ Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void _note_batch_job_finished(uint32_t job_id) { slurm_mutex_lock(&fini_mutex); fini_job_id[next_fini_job_inx] = job_id; if (++next_fini_job_inx >= FINI_JOB_CNT) next_fini_job_inx = 0; slurm_mutex_unlock(&fini_mutex); } Commit Message: Fix security issue in _prolog_error(). Fix security issue caused by insecure file path handling triggered by the failure of a Prolog script. To exploit this a user needs to anticipate or cause the Prolog to fail for their job. (This commit is slightly different from the fix to the 15.08 branch.) CVE-2016-10030. CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CSSDefaultStyleSheets::initDefaultStyle(Element* root) { if (!defaultStyle) { if (!root || elementCanUseSimpleDefaultStyle(root)) loadSimpleDefaultStyle(); else loadFullDefaultStyle(); } } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: u32 hid_field_extract(const struct hid_device *hid, u8 *report, unsigned offset, unsigned n) { if (n > 32) { hid_warn(hid, "hid_field_extract() called with n (%d) > 32! (%s)\n", n, current->comm); n = 32; } return __extract(report, offset, n); } Commit Message: HID: core: prevent out-of-bound readings Plugging a Logitech DJ receiver with KASAN activated raises a bunch of out-of-bound readings. The fields are allocated up to MAX_USAGE, meaning that potentially, we do not have enough fields to fit the incoming values. Add checks and silence KASAN. Signed-off-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: nfsd_create_setattr(struct svc_rqst *rqstp, struct svc_fh *resfhp, struct iattr *iap) { /* * Mode has already been set earlier in create: */ iap->ia_valid &= ~ATTR_MODE; /* * Setting uid/gid works only for root. Irix appears to * send along the gid on create when it tries to implement * setgid directories via NFS: */ if (!uid_eq(current_fsuid(), GLOBAL_ROOT_UID)) iap->ia_valid &= ~(ATTR_UID|ATTR_GID); if (iap->ia_valid) return nfsd_setattr(rqstp, resfhp, iap, 0, (time_t)0); /* Callers expect file metadata to be committed here */ return nfserrno(commit_metadata(resfhp)); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; } 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 Target: 1 Example 2: Code: apprentice_magic_strength(const struct magic *m) { #define MULT 10 size_t v, val = 2 * MULT; /* baseline strength */ switch (m->type) { case FILE_DEFAULT: /* make sure this sorts last */ if (m->factor_op != FILE_FACTOR_OP_NONE) abort(); return 0; case FILE_BYTE: val += 1 * MULT; break; case FILE_SHORT: case FILE_LESHORT: case FILE_BESHORT: val += 2 * MULT; break; case FILE_LONG: case FILE_LELONG: case FILE_BELONG: case FILE_MELONG: val += 4 * MULT; break; case FILE_PSTRING: case FILE_STRING: val += m->vallen * MULT; break; case FILE_BESTRING16: case FILE_LESTRING16: val += m->vallen * MULT / 2; break; case FILE_SEARCH: val += m->vallen * MAX(MULT / m->vallen, 1); break; case FILE_REGEX: v = nonmagic(m->value.s); val += v * MAX(MULT / v, 1); break; case FILE_DATE: case FILE_LEDATE: case FILE_BEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_LELDATE: case FILE_BELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: val += 4 * MULT; break; case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: case FILE_QDATE: case FILE_LEQDATE: case FILE_BEQDATE: case FILE_QLDATE: case FILE_LEQLDATE: case FILE_BEQLDATE: case FILE_QWDATE: case FILE_LEQWDATE: case FILE_BEQWDATE: case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: val += 8 * MULT; break; case FILE_INDIRECT: case FILE_NAME: case FILE_USE: break; default: (void)fprintf(stderr, "Bad type %d\n", m->type); abort(); } switch (m->reln) { case 'x': /* matches anything penalize */ case '!': /* matches almost anything penalize */ val = 0; break; case '=': /* Exact match, prefer */ val += MULT; break; case '>': case '<': /* comparison match reduce strength */ val -= 2 * MULT; break; case '^': case '&': /* masking bits, we could count them too */ val -= MULT; break; default: (void)fprintf(stderr, "Bad relation %c\n", m->reln); abort(); } if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */ val = 1; switch (m->factor_op) { case FILE_FACTOR_OP_NONE: break; case FILE_FACTOR_OP_PLUS: val += m->factor; break; case FILE_FACTOR_OP_MINUS: val -= m->factor; break; case FILE_FACTOR_OP_TIMES: val *= m->factor; break; case FILE_FACTOR_OP_DIV: val /= m->factor; break; default: abort(); } /* * Magic entries with no description get a bonus because they depend * on subsequent magic entries to print something. */ if (m->desc[0] == '\0') val++; return val; } Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible. CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderFrameDevToolsAgentHost::UpdateFrameHost( RenderFrameHostImpl* frame_host) { if (frame_host == frame_host_) { if (frame_host && !render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); MaybeReattachToRenderFrame(); } return; } if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) { DestroyOnRenderFrameGone(); return; } if (IsAttached()) RevokePolicy(); frame_host_ = frame_host; agent_ptr_.reset(); if (!render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); } if (IsAttached()) { GrantPolicy(); for (DevToolsSession* session : sessions()) { session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1, frame_host); } MaybeReattachToRenderFrame(); } } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20 Target: 1 Example 2: Code: bool SendGetChromeDriverAutomationVersion( AutomationMessageSender* sender, int* version, std::string* error_msg) { DictionaryValue dict; dict.SetString("command", "GetChromeDriverAutomationVersion"); DictionaryValue reply_dict; if (!SendAutomationJSONRequest(sender, dict, &reply_dict, error_msg)) return false; return reply_dict.GetInteger("version", version); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo) { unsigned int i; jp2_cdefchan_t *cdefent; for (i = 0; i < cdef->numchans; ++i) { cdefent = &cdef->ents[i]; if (cdefent->channo == JAS_CAST(unsigned int, channo)) { return cdefent; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (*p) + datalen >= max) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: int nfc_llcp_send_dm(struct nfc_llcp_local *local, u8 ssap, u8 dsap, u8 reason) { struct sk_buff *skb; struct nfc_dev *dev; u16 size = 1; /* Reason code */ pr_debug("Sending DM reason 0x%x\n", reason); if (local == NULL) return -ENODEV; dev = local->dev; if (dev == NULL) return -ENODEV; size += LLCP_HEADER_SIZE; size += dev->tx_headroom + dev->tx_tailroom + NFC_HEADER_SIZE; skb = alloc_skb(size, GFP_KERNEL); if (skb == NULL) return -ENOMEM; skb_reserve(skb, dev->tx_headroom + NFC_HEADER_SIZE); skb = llcp_add_header(skb, dsap, ssap, LLCP_PDU_DM); skb_put_data(skb, &reason, 1); skb_queue_head(&local->tx_queue, skb); return 0; } Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails KASAN report this: BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc] Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401 CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 kasan_report+0x171/0x18d mm/kasan/report.c:321 memcpy+0x1f/0x50 mm/kasan/common.c:130 nfc_llcp_build_gb+0x37f/0x540 [nfc] nfc_llcp_register_device+0x6eb/0xb50 [nfc] nfc_register_device+0x50/0x1d0 [nfc] nfcsim_device_new+0x394/0x67d [nfcsim] ? 0xffffffffc1080000 nfcsim_init+0x6b/0x1000 [nfcsim] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 nfc_llcp_build_tlv will return NULL on fails, caller should check it, otherwise will trigger a NULL dereference. Reported-by: Hulk Robot <[email protected]> Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames") Fixes: d646960f7986 ("NFC: Initial LLCP support") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe( RenderFrameHostImpl* render_frame_host, const GURL& default_url) { NavigationEntryImpl* entry = GetEntryWithUniqueID(render_frame_host->nav_entry_id()); if (!entry) return false; FrameNavigationEntry* frame_entry = entry->GetFrameEntry(render_frame_host->frame_tree_node()); if (!frame_entry) return false; bool restoring_different_url = frame_entry->url() != default_url; UMA_HISTOGRAM_BOOLEAN("SessionRestore.RestoredSubframeURL", restoring_different_url); if (restoring_different_url) { const std::string& unique_name = render_frame_host->frame_tree_node()->unique_name(); const char kFramePathPrefix[] = "<!--framePath "; if (base::StartsWith(unique_name, kFramePathPrefix, base::CompareCase::SENSITIVE)) { UMA_HISTOGRAM_COUNTS("SessionRestore.RestoreSubframeFramePathLength", unique_name.size()); } } std::unique_ptr<NavigationRequest> request = CreateNavigationRequest( render_frame_host->frame_tree_node(), *entry, frame_entry, ReloadType::NONE, false /* is_same_document_history_load */, true /* is_history_navigation_in_new_child */, nullptr, nullptr); if (!request) return false; render_frame_host->frame_tree_node()->navigator()->Navigate( std::move(request), ReloadType::NONE, RestoreType::NONE); return true; } Commit Message: Preserve renderer-initiated bit when reloading in a new process. BUG=847718 TEST=See bug for repro steps. Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227 Reviewed-on: https://chromium-review.googlesource.com/1080235 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#563312} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } 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 Target: 1 Example 2: Code: std::unique_ptr<HistogramSamples> SparseHistogram::SnapshotFinalDelta() const { DCHECK(!final_delta_created_); final_delta_created_ = true; std::unique_ptr<SampleMap> snapshot(new SampleMap(name_hash())); base::AutoLock auto_lock(lock_); snapshot->Add(*samples_); snapshot->Subtract(*logged_samples_); return std::move(snapshot); } Commit Message: Convert DCHECKs to CHECKs for histogram types When a histogram is looked up by name, there is currently a DCHECK that verifies the type of the stored histogram matches the expected type. A mismatch represents a significant problem because the returned HistogramBase is cast to a Histogram in ValidateRangeChecksum, potentially causing a crash. This CL converts the DCHECK to a CHECK to prevent the possibility of type confusion in release builds. BUG=651443 [email protected] Review-Url: https://codereview.chromium.org/2381893003 Cr-Commit-Position: refs/heads/master@{#421929} CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff; XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff; this->width(width); this->height(height); parent->vp8x = this; } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; } Commit Message: Revert "arm64: Introduce execute-only page access permissions" This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08. While the aim is increased security for --x memory maps, it does not protect against kernel level reads. Until SECCOMP is implemented for arm64, revert this patch to avoid giving a false idea of execute-only mappings. Signed-off-by: Catalin Marinas <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: void SiteInstanceImpl::AddObserver(Observer* observer) { observers_.AddObserver(observer); } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int oidc_check_user_id(request_rec *r) { oidc_cfg *c = ap_get_module_config(r->server->module_config, &auth_openidc_module); /* log some stuff about the incoming HTTP request */ oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d", r->parsed_uri.path, r->args, ap_is_initial_req(r)); /* see if any authentication has been defined at all */ if (ap_auth_type(r) == NULL) return DECLINED; /* see if we've configured OpenID Connect user authentication for this request */ if (apr_strnatcasecmp((const char *) ap_auth_type(r), "openid-connect") == 0) return oidc_check_userid_openidc(r, c); /* see if we've configured OAuth 2.0 access control for this request */ if (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0) return oidc_oauth_check_userid(r, c); /* this is not for us but for some other handler */ return DECLINED; } Commit Message: release 2.1.6 : security fix: scrub headers for "AuthType oauth20" Signed-off-by: Hans Zandbelt <[email protected]> CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int xen_netbk_get_extras(struct xenvif *vif, struct xen_netif_extra_info *extras, int work_to_do) { struct xen_netif_extra_info extra; RING_IDX cons = vif->tx.req_cons; do { if (unlikely(work_to_do-- <= 0)) { netdev_dbg(vif->dev, "Missing extra info\n"); return -EBADR; } memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons), sizeof(extra)); if (unlikely(!extra.type || extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) { vif->tx.req_cons = ++cons; netdev_dbg(vif->dev, "Invalid extra type: %d\n", extra.type); return -EINVAL; } memcpy(&extras[extra.type - 1], &extra, sizeof(extra)); vif->tx.req_cons = ++cons; } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE); return work_to_do; } Commit Message: xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: xsltCheckInstructionElement(xsltStylesheetPtr style, xmlNodePtr inst) { xmlNodePtr parent; int has_ext; if ((style == NULL) || (inst == NULL) || (inst->ns == NULL) || (style->literal_result)) return; has_ext = (style->extInfos != NULL); parent = inst->parent; if (parent == NULL) { xsltTransformError(NULL, style, inst, "internal problem: element has no parent\n"); style->errors++; return; } while ((parent != NULL) && (parent->type != XML_DOCUMENT_NODE)) { if (((parent->ns == inst->ns) || ((parent->ns != NULL) && (xmlStrEqual(parent->ns->href, inst->ns->href)))) && ((xmlStrEqual(parent->name, BAD_CAST "template")) || (xmlStrEqual(parent->name, BAD_CAST "param")) || (xmlStrEqual(parent->name, BAD_CAST "attribute")) || (xmlStrEqual(parent->name, BAD_CAST "variable")))) { return; } /* * if we are within an extension element all bets are off * about the semantic there e.g. xsl:param within func:function */ if ((has_ext) && (parent->ns != NULL) && (xmlHashLookup(style->extInfos, parent->ns->href) != NULL)) return; parent = parent->parent; } xsltTransformError(NULL, style, inst, "element %s only allowed within a template, variable or param\n", inst->name); style->errors++; } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void logi_dj_remove(struct hid_device *hdev) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_device *dj_dev; int i; dbg_hid("%s\n", __func__); cancel_work_sync(&djrcv_dev->work); hid_hw_close(hdev); hid_hw_stop(hdev); /* I suppose that at this point the only context that can access * the djrecv_data is this thread as the work item is guaranteed to * have finished and no more raw_event callbacks should arrive after * the remove callback was triggered so no locks are put around the * code below */ for (i = 0; i < (DJ_MAX_PAIRED_DEVICES + DJ_DEVICE_INDEX_MIN); i++) { dj_dev = djrcv_dev->paired_dj_devices[i]; if (dj_dev != NULL) { hid_destroy_device(dj_dev->hdev); kfree(dj_dev); djrcv_dev->paired_dj_devices[i] = NULL; } } kfifo_free(&djrcv_dev->notif_fifo); kfree(djrcv_dev); hid_set_drvdata(hdev, NULL); } Commit Message: HID: logitech: fix bounds checking on LED report size The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request() is wrong; the current check doesn't make any sense -- the report allocated by HID core in hid_hw_raw_request() can be much larger than DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't handle this properly at all. Fix the check by actually trimming down the report size properly if it is too large. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> methodWithNonOptionalArgAndTwoOptionalArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndTwoOptionalArgs"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (args.Length() <= 1) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); if (args.Length() <= 2) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: sd_store_manage_start_stop(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; if (!capable(CAP_SYS_ADMIN)) return -EACCES; sdp->manage_start_stop = simple_strtoul(buf, NULL, 10); return count; } Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int apparmor_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot) { return common_mmap(OP_FMPROT, vma->vm_file, prot, !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0); } Commit Message: AppArmor: fix oops in apparmor_setprocattr When invalid parameters are passed to apparmor_setprocattr a NULL deref oops occurs when it tries to record an audit message. This is because it is passing NULL for the profile parameter for aa_audit. But aa_audit now requires that the profile passed is not NULL. Fix this by passing the current profile on the task that is trying to setprocattr. Signed-off-by: Kees Cook <[email protected]> Signed-off-by: John Johansen <[email protected]> Cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } Commit Message: jpeg2000: check log2_cblk dimensions Fixes out of array access Fixes Ticket2895 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: TestContentBrowserClient() {} Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <[email protected]> Reviewed-by: Michael Wasserman <[email protected]> Reviewed-by: Jeffrey Yasskin <[email protected]> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void irda_selective_discovery_indication(discinfo_t *discovery, DISCOVERY_MODE mode, void *priv) { struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); self = priv; if (!self) { IRDA_WARNING("%s: lost myself!\n", __func__); return; } /* Pass parameter to the caller */ self->cachedaddr = discovery->daddr; /* Wake up process if its waiting for device to be discovered */ wake_up_interruptible(&self->query_wait); } Commit Message: irda: Fix missing msg_namelen update in irda_recvmsg_dgram() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about irda_recvmsg_dgram() not filling the msg_name in case it was set. Cc: Samuel Ortiz <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int raw_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name; err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { static int complained; if (!complained++) printk(KERN_INFO "%s forgot to set AF_INET in " "raw sendmsg. Fix it!\n", current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sock_net(sk), msg, &ipc); if (err) goto out; if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) ipc.opt = inet->opt; if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (inet->hdrincl) goto done; if (ipc.opt->srr) { if (!daddr) goto done; daddr = ipc.opt->faddr; } } tos = RT_CONN_FLAGS(sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } { struct flowi4 fl4; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, FLOWI_FLAG_CAN_SLEEP, daddr, saddr, 0, 0); if (!inet->hdrincl) { err = raw_probe_proto_opt(&fl4, msg); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = raw_send_hdrinc(sk, msg->msg_iov, len, &rt, msg->msg_flags); else { if (!ipc.addr) ipc.addr = rt->rt_dst; lock_sock(sk); err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } 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 Target: 1 Example 2: Code: static int __shrink_ple_window(int val, int modifier, int minimum) { if (modifier < 1) return ple_window; if (modifier < ple_window) val /= modifier; else val -= modifier; return max(val, minimum); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) { resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); } else if (IsHTMLObjectElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextObject); } else if (IsHTMLEmbedElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed); } bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); } Commit Message: service worker: Disable interception when OBJECT/EMBED uses ImageLoader. Per the specification, service worker should not intercept requests for OBJECT/EMBED elements. R=kinuko Bug: 771933 Change-Id: Ia6da6107dc5c68aa2c2efffde14bd2c51251fbd4 Reviewed-on: https://chromium-review.googlesource.com/927303 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#538027} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) { struct grub_ext2_data *data = node->data; struct grub_ext2_inode *inode = &node->inode; int blknr = -1; unsigned int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) { #ifndef _MSC_VER char buf[EXT2_BLOCK_SIZE (data)]; #else char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); #endif struct grub_ext4_extent_header *leaf; struct grub_ext4_extent *ext; int i; leaf = grub_ext4_find_leaf (data, buf, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, fileblock); if (! leaf) { grub_error (GRUB_ERR_BAD_FS, "invalid extent"); return -1; } ext = (struct grub_ext4_extent *) (leaf + 1); for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) { if (fileblock < grub_le_to_cpu32 (ext[i].block)) break; } if (--i >= 0) { fileblock -= grub_le_to_cpu32 (ext[i].block); if (fileblock >= grub_le_to_cpu16 (ext[i].len)) return 0; else { grub_disk_addr_t start; start = grub_le_to_cpu16 (ext[i].start_hi); start = (start << 32) + grub_le_to_cpu32 (ext[i].start); return fileblock + start; } } else { grub_error (GRUB_ERR_BAD_FS, "something wrong with extent"); return -1; } } /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); /* Indirect. */ else if (fileblock < INDIRECT_BLOCKS + blksz / 4) { grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); grub_free (indir); } /* Double indirect. */ else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ * (grub_disk_addr_t)(blksz / 4 + 1)) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.double_indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (indir[rblock / perblock])) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[rblock % perblock]); grub_free (indir); } /* triple indirect. */ else { grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "ext2fs doesn't support triple indirect blocks"); } return blknr; } Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove CWE ID: CWE-787 Target: 1 Example 2: Code: tt_cmap14_char_index( TT_CMap cmap, FT_UInt32 char_code ) { FT_UNUSED( cmap ); FT_UNUSED( char_code ); /* This can't happen */ return 0; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cuse_parse_devinfo(char *p, size_t len, struct cuse_devinfo *devinfo) { char *end = p + len; char *uninitialized_var(key), *uninitialized_var(val); int rc; while (true) { rc = cuse_parse_one(&p, end, &key, &val); if (rc < 0) return rc; if (!rc) break; if (strcmp(key, "DEVNAME") == 0) devinfo->name = val; else printk(KERN_WARNING "CUSE: unknown device info \"%s\"\n", key); } if (!devinfo->name || !strlen(devinfo->name)) { printk(KERN_ERR "CUSE: DEVNAME unspecified\n"); return -EINVAL; } return 0; } Commit Message: cuse: fix memory leak The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc, and the original ref count is never dropped. Reported-by: Colin Ian King <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure") Cc: <[email protected]> # v4.2+ CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: rm_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) { char * name = NULL; int rtnVal = FALSE; int rc; bool found_cred; CredentialWrapper * cred_wrapper = NULL; char * owner = NULL; const char * user; ReliSock * socket = (ReliSock*)stream; if (!socket->triedAuthentication()) { CondorError errstack; if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) { dprintf (D_ALWAYS, "Unable to authenticate, qutting\n"); goto EXIT; } } socket->decode(); if (!socket->code(name)) { dprintf (D_ALWAYS, "Error receiving credential name\n"); goto EXIT; } user = socket->getFullyQualifiedUser(); dprintf (D_ALWAYS, "Authenticated as %s\n", user); if (strchr (name, ':')) { owner = strdup (name); char * pColon = strchr (owner, ':'); *pColon = '\0'; sprintf (name, (char*)(pColon+sizeof(char))); if (strcmp (owner, user) != 0) { dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name); if (!isSuperUser (user)) { dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user); goto EXIT; } else { dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user); } } } else { owner = strdup (user); } dprintf (D_ALWAYS, "Attempting to delete cred %s for user %s\n", name, owner); found_cred=false; credentials.Rewind(); while (credentials.Next(cred_wrapper)) { if (cred_wrapper->cred->GetType() == X509_CREDENTIAL_TYPE) { if ((strcmp(cred_wrapper->cred->GetName(), name) == 0) && (strcmp(cred_wrapper->cred->GetOwner(), owner) == 0)) { credentials.DeleteCurrent(); found_cred=true; break; // found it } } } if (found_cred) { priv_state priv = set_root_priv(); unlink (cred_wrapper->GetStorageName()); SaveCredentialList(); set_priv(priv); delete cred_wrapper; dprintf (D_ALWAYS, "Removed credential %s for owner %s\n", name, owner); } else { dprintf (D_ALWAYS, "Unable to remove credential %s:%s (not found)\n", owner, name); } free (owner); socket->encode(); rc = (found_cred)?CREDD_SUCCESS:CREDD_CREDENTIAL_NOT_FOUND; socket->code(rc); rtnVal = TRUE; EXIT: if (name != NULL) { free (name); } return rtnVal; } Commit Message: CWE ID: CWE-134 Target: 1 Example 2: Code: static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p) { /* * (tty == real_tty) is a cheap way of * testing if the tty is NOT a master pty. */ if (tty == real_tty && current->signal->tty != real_tty) return -ENOTTY; if (!real_tty->session) return -ENOTTY; return put_user(pid_vnr(real_tty->session), p); } Commit Message: tty: Fix unsafe ldisc reference via ioctl(TIOCGETD) ioctl(TIOCGETD) retrieves the line discipline id directly from the ldisc because the line discipline id (c_line) in termios is untrustworthy; userspace may have set termios via ioctl(TCSETS*) without actually changing the line discipline via ioctl(TIOCSETD). However, directly accessing the current ldisc via tty->ldisc is unsafe; the ldisc ptr dereferenced may be stale if the line discipline is changing via ioctl(TIOCSETD) or hangup. Wait for the line discipline reference (just like read() or write()) to retrieve the "current" line discipline id. Cc: <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_get_context(struct inode *inode, void *ctx, size_t len) { return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION, EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len); } Commit Message: ext4: validate s_first_meta_bg at mount time Ralf Spenneberg reported that he hit a kernel crash when mounting a modified ext4 image. And it turns out that kernel crashed when calculating fs overhead (ext4_calculate_overhead()), this is because the image has very large s_first_meta_bg (debug code shows it's 842150400), and ext4 overruns the memory in count_overhead() when setting bitmap buffer, which is PAGE_SIZE. ext4_calculate_overhead(): buf = get_zeroed_page(GFP_NOFS); <=== PAGE_SIZE buffer blks = count_overhead(sb, i, buf); count_overhead(): for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) { <=== j = 842150400 ext4_set_bit(EXT4_B2C(sbi, s++), buf); <=== buffer overrun count++; } This can be reproduced easily for me by this script: #!/bin/bash rm -f fs.img mkdir -p /mnt/ext4 fallocate -l 16M fs.img mke2fs -t ext4 -O bigalloc,meta_bg,^resize_inode -F fs.img debugfs -w -R "ssv first_meta_bg 842150400" fs.img mount -o loop fs.img /mnt/ext4 Fix it by validating s_first_meta_bg first at mount time, and refusing to mount if its value exceeds the largest possible meta_bg number. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Eryu Guan <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Reviewed-by: Andreas Dilger <[email protected]> CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof (unsigned char *), sy)) { return NULL; } if (overflow2(sizeof (unsigned char), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); if (!im) { return NULL; } /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy); if (!im->pixels) { gdFree(im); return NULL; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char)); if (!im->pixels[i]) { for (--i ; i >= 0; i--) { gdFree(im->pixels[i]); } gdFree(im->pixels); gdFree(im); return NULL; } } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; for (i = 0; (i < gdMaxColors); i++) { im->open[i] = 1; }; im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } Commit Message: Fix #340: System frozen gdImageCreate() doesn't check for oversized images and as such is prone to DoS vulnerabilities. We fix that by applying the same overflow check that is already in place for gdImageCreateTrueColor(). CVE-2016-9317 CWE ID: CWE-20 Target: 1 Example 2: Code: void BackendIO::OpenEntry(const std::string& key, Entry** entry) { operation_ = OP_OPEN; key_ = key; entry_ptr_ = entry; } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TranslateInfoBarDelegate::AlwaysTranslatePageLanguage() { DCHECK(!ui_delegate_.ShouldAlwaysTranslate()); ui_delegate_.SetAlwaysTranslate(true); Translate(); } Commit Message: Remove dependency of TranslateInfobarDelegate on profile This CL uses TranslateTabHelper instead of Profile and also cleans up some unused code and irrelevant dependencies. BUG=371845 Review URL: https://codereview.chromium.org/286973003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: lmp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct lmp_common_header *lmp_com_header; const struct lmp_object_header *lmp_obj_header; const u_char *tptr,*obj_tptr; u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen; int hexdump, ret; u_int offset; u_int link_type; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; tptr=pptr; lmp_com_header = (const struct lmp_common_header *)pptr; ND_TCHECK(*lmp_com_header); /* * Sanity checking of the header. */ if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) { ND_PRINT((ndo, "LMP version %u packet not supported", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LMPv%u %s Message, length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lmp_com_header->length); ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type), bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags), tlen)); if (tlen < sizeof(const struct lmp_common_header)) { ND_PRINT((ndo, " (too short)")); return; } if (tlen > len) { ND_PRINT((ndo, " (too long)")); tlen = len; } tptr+=sizeof(const struct lmp_common_header); tlen-=sizeof(const struct lmp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct lmp_object_header)); lmp_obj_header = (const struct lmp_object_header *)tptr; lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length); lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f; ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u", tok2str(lmp_obj_values, "Unknown", lmp_obj_header->class_num), lmp_obj_header->class_num, tok2str(lmp_ctype_values, "Unknown", ((lmp_obj_header->class_num)<<8)+lmp_obj_ctype), lmp_obj_ctype, (lmp_obj_header->ctype)&0x80 ? "" : "non-", lmp_obj_len)); if (lmp_obj_len < 4) { ND_PRINT((ndo, " (too short)")); return; } if ((lmp_obj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); return; } obj_tptr=tptr+sizeof(struct lmp_object_header); obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, lmp_obj_len); hexdump=FALSE; switch(lmp_obj_header->class_num) { case LMP_OBJ_CC_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_LINK_ID: case LMP_OBJ_INTERFACE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4_LOC: case LMP_CTYPE_IPV4_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_IPV6_LOC: case LMP_CTYPE_IPV6_RMT: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_UNMD_LOC: case LMP_CTYPE_UNMD_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_MESSAGE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_2: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_NODE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CONFIG: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO_CONFIG: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_HELLO: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr+4))); break; default: hexdump=TRUE; } break; case LMP_OBJ_TE_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; case LMP_CTYPE_IPV6: if (obj_tlen != 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); break; case LMP_CTYPE_UNMD: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)" "\n\t Remote Link-ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; default: hexdump=TRUE; } break; case LMP_OBJ_DATA_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; case LMP_CTYPE_IPV6: if (obj_tlen < 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; case LMP_CTYPE_UNMD: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)" "\n\t Remote Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); ret = lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12); if (ret == -1) goto trunc; if (ret == TRUE) hexdump=TRUE; break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 20) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_begin_verify_flag_values, "none", EXTRACT_16BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Verify Interval: %u", EXTRACT_16BITS(obj_tptr+2))); ND_PRINT((ndo, "\n\t Data links: %u", EXTRACT_32BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Encoding type: %s", tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8)))); ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s", EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : "")); bw.i = EXTRACT_32BITS(obj_tptr+12); ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000)); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+16))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN_ACK: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify Dead Interval: %u" "\n\t Verify Transport Response: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify ID: %u", EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; case LMP_CTYPE_IPV6: offset = 0; /* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */ while (offset+20 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+16)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF)); offset+=20; } break; case LMP_CTYPE_UNMD: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS_REQ: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; case LMP_CTYPE_IPV6: offset = 0; while (offset+16 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=16; } break; case LMP_CTYPE_UNMD: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; default: hexdump=TRUE; } break; case LMP_OBJ_ERROR_CODE: switch(lmp_obj_ctype) { case LMP_CTYPE_BEGIN_VERIFY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_begin_verify_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; case LMP_CTYPE_LINK_SUMMARY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_link_summary_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; default: hexdump=TRUE; } break; case LMP_OBJ_SERVICE_CONFIG: switch (lmp_obj_ctype) { case LMP_CTYPE_SERVICE_CONFIG_SP: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_service_config_sp_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t UNI Version: %u", EXTRACT_8BITS(obj_tptr + 1))); break; case LMP_CTYPE_SERVICE_CONFIG_CPSA: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } link_type = EXTRACT_8BITS(obj_tptr); ND_PRINT((ndo, "\n\t Link Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_link_type_values, "Unknown", link_type), link_type)); switch (link_type) { case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values, "Unknown", EXTRACT_8BITS(obj_tptr + 1)), EXTRACT_8BITS(obj_tptr + 1))); break; case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values, "Unknown", EXTRACT_8BITS(obj_tptr + 1)), EXTRACT_8BITS(obj_tptr + 1))); break; } ND_PRINT((ndo, "\n\t Transparency: %s", bittok2str(lmp_obj_service_config_cpsa_tp_flag_values, "none", EXTRACT_8BITS(obj_tptr + 2)))); ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s", bittok2str(lmp_obj_service_config_cpsa_cct_flag_values, "none", EXTRACT_8BITS(obj_tptr + 3)))); ND_PRINT((ndo, "\n\t Minimum NCC: %u", EXTRACT_16BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Maximum NCC: %u", EXTRACT_16BITS(obj_tptr+6))); ND_PRINT((ndo, "\n\t Minimum NVC:%u", EXTRACT_16BITS(obj_tptr+8))); ND_PRINT((ndo, "\n\t Maximum NVC:%u", EXTRACT_16BITS(obj_tptr+10))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+12), EXTRACT_32BITS(obj_tptr+12))); break; case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Transparency Flags: %s", bittok2str( lmp_obj_service_config_nsa_transparency_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s", bittok2str( lmp_obj_service_config_nsa_tcm_flag_values, "none", EXTRACT_8BITS(obj_tptr + 7)))); break; case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Diversity: Flags: %s", bittok2str( lmp_obj_service_config_nsa_network_diversity_flag_values, "none", EXTRACT_8BITS(obj_tptr + 3)))); break; default: hexdump = TRUE; } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ", lmp_obj_len-sizeof(struct lmp_object_header)); tptr+=lmp_obj_len; tlen-=lmp_obj_len; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } Commit Message: (for 4.9.3) LMP: Add some missing bounds checks In lmp_print_data_link_subobjs(), these problems were identified through code review. Moreover: Add and use tstr[]. Update two tests outputs accordingly. CWE ID: CWE-20 Target: 1 Example 2: Code: GLuint SetupColoredVertexProgram() { static const char* v_shader_str = SHADER( attribute vec4 a_position; attribute vec4 a_color; varying vec4 v_color; void main() { gl_Position = a_position; v_color = a_color; } ); static const char* f_shader_str = SHADER( precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ); GLuint program = GLTestHelper::LoadProgram(v_shader_str, f_shader_str); glUseProgram(program); return program; } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <[email protected]> Commit-Queue: vikas soni <[email protected]> Cr-Commit-Position: refs/heads/master@{#539111} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags, u32 ext_filter_mask) { struct ifinfomsg *ifm; struct nlmsghdr *nlh; struct rtnl_link_stats64 temp; const struct rtnl_link_stats64 *stats; struct nlattr *attr, *af_spec; struct rtnl_af_ops *af_ops; struct net_device *upper_dev = netdev_master_upper_dev_get(dev); ASSERT_RTNL(); nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_UNSPEC; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = change; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) || nla_put_u8(skb, IFLA_OPERSTATE, netif_running(dev) ? dev->operstate : IF_OPER_DOWN) || nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u32(skb, IFLA_GROUP, dev->group) || nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) || nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) || #ifdef CONFIG_RPS nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) || #endif (dev->ifindex != dev->iflink && nla_put_u32(skb, IFLA_LINK, dev->iflink)) || (upper_dev && nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) || nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) || (dev->qdisc && nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) || (dev->ifalias && nla_put_string(skb, IFLA_IFALIAS, dev->ifalias))) goto nla_put_failure; if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) goto nla_put_failure; } if (dev->addr_len) { if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) || nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast)) goto nla_put_failure; } attr = nla_reserve(skb, IFLA_STATS, sizeof(struct rtnl_link_stats)); if (attr == NULL) goto nla_put_failure; stats = dev_get_stats(dev, &temp); copy_rtnl_link_stats(nla_data(attr), stats); attr = nla_reserve(skb, IFLA_STATS64, sizeof(struct rtnl_link_stats64)); if (attr == NULL) goto nla_put_failure; copy_rtnl_link_stats64(nla_data(attr), stats); if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) && nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent))) goto nla_put_failure; if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF)) { int i; struct nlattr *vfinfo, *vf; int num_vfs = dev_num_vf(dev->dev.parent); vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST); if (!vfinfo) goto nla_put_failure; for (i = 0; i < num_vfs; i++) { struct ifla_vf_info ivi; struct ifla_vf_mac vf_mac; struct ifla_vf_vlan vf_vlan; struct ifla_vf_tx_rate vf_tx_rate; struct ifla_vf_spoofchk vf_spoofchk; /* * Not all SR-IOV capable drivers support the * spoofcheck query. Preset to -1 so the user * space tool can detect that the driver didn't * report anything. */ ivi.spoofchk = -1; if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi)) break; vf_mac.vf = vf_vlan.vf = vf_tx_rate.vf = vf_spoofchk.vf = ivi.vf; memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac)); vf_vlan.vlan = ivi.vlan; vf_vlan.qos = ivi.qos; vf_tx_rate.rate = ivi.tx_rate; vf_spoofchk.setting = ivi.spoofchk; vf = nla_nest_start(skb, IFLA_VF_INFO); if (!vf) { nla_nest_cancel(skb, vfinfo); goto nla_put_failure; } if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) || nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) || nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate) || nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk), &vf_spoofchk)) goto nla_put_failure; nla_nest_end(skb, vf); } nla_nest_end(skb, vfinfo); } if (rtnl_port_fill(skb, dev)) goto nla_put_failure; if (dev->rtnl_link_ops) { if (rtnl_link_fill(skb, dev) < 0) goto nla_put_failure; } if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC))) goto nla_put_failure; list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->fill_link_af) { struct nlattr *af; int err; if (!(af = nla_nest_start(skb, af_ops->family))) goto nla_put_failure; err = af_ops->fill_link_af(skb, dev); /* * Caller may return ENODATA to indicate that there * was no data to be dumped. This is not an error, it * means we should trim the attribute header and * continue. */ if (err == -ENODATA) nla_nest_cancel(skb, af); else if (err < 0) goto nla_put_failure; nla_nest_end(skb, af); } } nla_nest_end(skb, af_spec); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } Commit Message: rtnl: fix info leak on RTM_GETLINK request for VF devices Initialize the mac address buffer with 0 as the driver specific function will probably not fill the whole buffer. In fact, all in-kernel drivers fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible bytes. Therefore we currently leak 26 bytes of stack memory to userland via the netlink interface. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *restrict webp_image = &configure.output; WebPBitstreamFeatures *restrict features = &configure.input; /* 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); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; 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++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); return(image); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void CopyOutputRequestCallbackRunsOnceCallback( int* n_called, std::unique_ptr<CopyOutputResult> result) { ++*n_called; } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long Block::GetTrackNumber() const { return m_track; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR("%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_remove_unpaired(config); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR("%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20 Target: 1 Example 2: Code: pch_c_function (void) { return p_c_function; } Commit Message: CWE ID: CWE-78 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PDFiumEngine::SelectAll() { SelectionChangeInvalidator selection_invalidator(this); selection_.clear(); for (const auto& page : pages_) { if (page->available()) selection_.push_back(PDFiumRange(page, 0, page->GetCharCount())); } } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_emit_signal2 (MyObject *obj, GError **error) { GHashTable *table; table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (table, "baz", "cow"); g_hash_table_insert (table, "bar", "foo"); g_signal_emit (obj, signals[SIG2], 0, table); g_hash_table_destroy (table); return TRUE; } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: static void sock_diag_rcv(struct sk_buff *skb) { mutex_lock(&sock_diag_mutex); netlink_rcv_skb(skb, &sock_diag_rcv_msg); mutex_unlock(&sock_diag_mutex); } Commit Message: sock_diag: Fix out-of-bounds access to sock_diag_handlers[] Userland can send a netlink message requesting SOCK_DIAG_BY_FAMILY with a family greater or equal then AF_MAX -- the array size of sock_diag_handlers[]. The current code does not test for this condition therefore is vulnerable to an out-of-bound access opening doors for a privilege escalation. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: copy_move_file (CopyMoveJob *copy_job, GFile *src, GFile *dest_dir, gboolean same_fs, gboolean unique_names, char **dest_fs_type, SourceInfo *source_info, TransferInfo *transfer_info, GHashTable *debuting_files, GdkPoint *position, gboolean overwrite, gboolean *skipped_file, gboolean readonly_source_fs) { GFile *dest, *new_dest; g_autofree gchar *dest_uri = NULL; GError *error; GFileCopyFlags flags; char *primary, *secondary, *details; int response; ProgressData pdata; gboolean would_recurse, is_merge; CommonJob *job; gboolean res; int unique_name_nr; gboolean handled_invalid_filename; job = (CommonJob *) copy_job; if (should_skip_file (job, src)) { *skipped_file = TRUE; return; } unique_name_nr = 1; /* another file in the same directory might have handled the invalid * filename condition for us */ handled_invalid_filename = *dest_fs_type != NULL; if (unique_names) { dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++); } else if (copy_job->target_name != NULL) { dest = get_target_file_with_custom_name (src, dest_dir, *dest_fs_type, same_fs, copy_job->target_name); } else { dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs); } /* Don't allow recursive move/copy into itself. * (We would get a file system error if we proceeded but it is nicer to * detect and report it at this level) */ if (test_dir_is_parent (dest_dir, src)) { if (job->skip_all_error) { goto out; } /* the run_warning() frees all strings passed in automatically */ primary = copy_job->is_move ? g_strdup (_("You cannot move a folder into itself.")) : g_strdup (_("You cannot copy a folder into itself.")); secondary = g_strdup (_("The destination folder is inside the source folder.")); response = run_cancel_or_skip_warning (job, primary, secondary, NULL, source_info->num_files, source_info->num_files - transfer_info->num_files); if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (job); } else if (response == 1) /* skip all */ { job->skip_all_error = TRUE; } else if (response == 2) /* skip */ { /* do nothing */ } else { g_assert_not_reached (); } goto out; } /* Don't allow copying over the source or one of the parents of the source. */ if (test_dir_is_parent (src, dest)) { if (job->skip_all_error) { goto out; } /* the run_warning() frees all strings passed in automatically */ primary = copy_job->is_move ? g_strdup (_("You cannot move a file over itself.")) : g_strdup (_("You cannot copy a file over itself.")); secondary = g_strdup (_("The source file would be overwritten by the destination.")); response = run_cancel_or_skip_warning (job, primary, secondary, NULL, source_info->num_files, source_info->num_files - transfer_info->num_files); if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (job); } else if (response == 1) /* skip all */ { job->skip_all_error = TRUE; } else if (response == 2) /* skip */ { /* do nothing */ } else { g_assert_not_reached (); } goto out; } retry: error = NULL; flags = G_FILE_COPY_NOFOLLOW_SYMLINKS; if (overwrite) { flags |= G_FILE_COPY_OVERWRITE; } if (readonly_source_fs) { flags |= G_FILE_COPY_TARGET_DEFAULT_PERMS; } pdata.job = copy_job; pdata.last_size = 0; pdata.source_info = source_info; pdata.transfer_info = transfer_info; if (copy_job->is_move) { res = g_file_move (src, dest, flags, job->cancellable, copy_file_progress_callback, &pdata, &error); } else { res = g_file_copy (src, dest, flags, job->cancellable, copy_file_progress_callback, &pdata, &error); } if (res) { GFile *real; real = map_possibly_volatile_file_to_real (dest, job->cancellable, &error); if (real == NULL) { res = FALSE; } else { g_object_unref (dest); dest = real; } } if (res) { transfer_info->num_files++; report_copy_progress (copy_job, source_info, transfer_info); if (debuting_files) { dest_uri = g_file_get_uri (dest); if (position) { nautilus_file_changes_queue_schedule_position_set (dest, *position, job->screen_num); } else if (eel_uri_is_desktop (dest_uri)) { nautilus_file_changes_queue_schedule_position_remove (dest); } g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE)); } if (copy_job->is_move) { nautilus_file_changes_queue_file_moved (src, dest); } else { nautilus_file_changes_queue_file_added (dest); } /* If copying a trusted desktop file to the desktop, * mark it as trusted. */ if (copy_job->desktop_location != NULL && g_file_equal (copy_job->desktop_location, dest_dir) && is_trusted_desktop_file (src, job->cancellable)) { mark_desktop_file_trusted (job, job->cancellable, dest, FALSE); } if (job->undo_info != NULL) { nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info), src, dest); } g_object_unref (dest); return; } if (!handled_invalid_filename && IS_IO_ERROR (error, INVALID_FILENAME)) { handled_invalid_filename = TRUE; g_assert (*dest_fs_type == NULL); *dest_fs_type = query_fs_type (dest_dir, job->cancellable); if (unique_names) { new_dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr); } else { new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs); } if (!g_file_equal (dest, new_dest)) { g_object_unref (dest); dest = new_dest; g_error_free (error); goto retry; } else { g_object_unref (new_dest); } } /* Conflict */ if (!overwrite && IS_IO_ERROR (error, EXISTS)) { gboolean is_merge; FileConflictResponse *response; g_error_free (error); if (unique_names) { g_object_unref (dest); dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++); goto retry; } is_merge = FALSE; if (is_dir (dest) && is_dir (src)) { is_merge = TRUE; } if ((is_merge && job->merge_all) || (!is_merge && job->replace_all)) { overwrite = TRUE; goto retry; } if (job->skip_all_conflict) { goto out; } response = handle_copy_move_conflict (job, src, dest, dest_dir); if (response->id == GTK_RESPONSE_CANCEL || response->id == GTK_RESPONSE_DELETE_EVENT) { file_conflict_response_free (response); abort_job (job); } else if (response->id == CONFLICT_RESPONSE_SKIP) { if (response->apply_to_all) { job->skip_all_conflict = TRUE; } file_conflict_response_free (response); } else if (response->id == CONFLICT_RESPONSE_REPLACE) /* merge/replace */ { if (response->apply_to_all) { if (is_merge) { job->merge_all = TRUE; } else { job->replace_all = TRUE; } } overwrite = TRUE; file_conflict_response_free (response); goto retry; } else if (response->id == CONFLICT_RESPONSE_RENAME) { g_object_unref (dest); dest = get_target_file_for_display_name (dest_dir, response->new_name); file_conflict_response_free (response); goto retry; } else { g_assert_not_reached (); } } else if (overwrite && IS_IO_ERROR (error, IS_DIRECTORY)) { gboolean existing_file_deleted; DeleteExistingFileData data; g_error_free (error); data.job = job; data.source = src; existing_file_deleted = delete_file_recursively (dest, job->cancellable, existing_file_removed_callback, &data); if (existing_file_deleted) { goto retry; } } /* Needs to recurse */ else if (IS_IO_ERROR (error, WOULD_RECURSE) || IS_IO_ERROR (error, WOULD_MERGE)) { is_merge = error->code == G_IO_ERROR_WOULD_MERGE; would_recurse = error->code == G_IO_ERROR_WOULD_RECURSE; g_error_free (error); if (overwrite && would_recurse) { error = NULL; /* Copying a dir onto file, first remove the file */ if (!g_file_delete (dest, job->cancellable, &error) && !IS_IO_ERROR (error, NOT_FOUND)) { if (job->skip_all_error) { g_error_free (error); goto out; } if (copy_job->is_move) { primary = f (_("Error while moving “%B”."), src); } else { primary = f (_("Error while copying “%B”."), src); } secondary = f (_("Could not remove the already existing file with the same name in %F."), dest_dir); details = error->message; /* setting TRUE on show_all here, as we could have * another error on the same file later. */ response = run_warning (job, primary, secondary, details, TRUE, CANCEL, SKIP_ALL, SKIP, NULL); g_error_free (error); if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (job); } else if (response == 1) /* skip all */ { job->skip_all_error = TRUE; } else if (response == 2) /* skip */ { /* do nothing */ } else { g_assert_not_reached (); } goto out; } if (error) { g_error_free (error); error = NULL; } nautilus_file_changes_queue_file_removed (dest); } if (is_merge) { /* On merge we now write in the target directory, which may not * be in the same directory as the source, even if the parent is * (if the merged directory is a mountpoint). This could cause * problems as we then don't transcode filenames. * We just set same_fs to FALSE which is safe but a bit slower. */ same_fs = FALSE; } if (!copy_move_directory (copy_job, src, &dest, same_fs, would_recurse, dest_fs_type, source_info, transfer_info, debuting_files, skipped_file, readonly_source_fs)) { /* destination changed, since it was an invalid file name */ g_assert (*dest_fs_type != NULL); handled_invalid_filename = TRUE; goto retry; } g_object_unref (dest); return; } else if (IS_IO_ERROR (error, CANCELLED)) { g_error_free (error); } /* Other error */ else { if (job->skip_all_error) { g_error_free (error); goto out; } primary = f (_("Error while copying “%B”."), src); secondary = f (_("There was an error copying the file into %F."), dest_dir); details = error->message; response = run_cancel_or_skip_warning (job, primary, secondary, details, source_info->num_files, source_info->num_files - transfer_info->num_files); g_error_free (error); if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT) { abort_job (job); } else if (response == 1) /* skip all */ { job->skip_all_error = TRUE; } else if (response == 2) /* skip */ { /* do nothing */ } else { g_assert_not_reached (); } } out: *skipped_file = TRUE; /* Or aborted, but same-same */ g_object_unref (dest); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadCLIPBOARDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; register ssize_t x; register PixelPacket *q; ssize_t y; 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); { HBITMAP bitmapH; HPALETTE hPal; OpenClipboard(NULL); bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP); hPal=(HPALETTE) GetClipboardData(CF_PALETTE); CloseClipboard(); if ( bitmapH == NULL ) ThrowReaderException(CoderError,"NoBitmapOnClipboard"); { BITMAPINFO DIBinfo; BITMAP bitmap; HBITMAP hBitmap, hOldBitmap; HDC hDC, hMemDC; RGBQUAD *pBits, *ppBits; /* create an offscreen DC for the source */ hMemDC=CreateCompatibleDC(NULL); hOldBitmap=(HBITMAP) SelectObject(hMemDC,bitmapH); GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap); if ((image->columns == 0) || (image->rows == 0)) { image->rows=bitmap.bmHeight; image->columns=bitmap.bmWidth; } /* Initialize the bitmap header info. */ (void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO)); DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); DIBinfo.bmiHeader.biWidth=(LONG) image->columns; DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows; DIBinfo.bmiHeader.biPlanes=1; DIBinfo.bmiHeader.biBitCount=32; DIBinfo.bmiHeader.biCompression=BI_RGB; hDC=GetDC(NULL); if (hDC == 0) ThrowReaderException(CoderError,"UnableToCreateADC"); hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits, NULL,0); ReleaseDC(NULL,hDC); if (hBitmap == 0) ThrowReaderException(CoderError,"UnableToCreateBitmap"); /* create an offscreen DC */ hDC=CreateCompatibleDC(NULL); if (hDC == 0) { DeleteObject(hBitmap); ThrowReaderException(CoderError,"UnableToCreateADC"); } hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap); if (hOldBitmap == 0) { DeleteDC(hDC); DeleteObject(hBitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } if (hPal != NULL) { /* Kenichi Masuko says this needed */ SelectPalette(hDC, hPal, FALSE); RealizePalette(hDC); } /* bitblt from the memory to the DIB-based one */ BitBlt(hDC,0,0,(int) image->columns,(int) image->rows,hMemDC,0,0,SRCCOPY); /* finally copy the pixels! */ pBits=ppBits; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed)); SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen)); SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue)); SetPixelOpacity(q,OpaqueOpacity); pBits++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteObject(hBitmap); } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void out_flush_domain_queues(s2s_t s2s, const char *domain) { char *rkey; int rkeylen; char *c; int c_len; if (xhash_iter_first(s2s->outq)) { do { xhash_iter_get(s2s->outq, (const char **) &rkey, &rkeylen, NULL); c = memchr(rkey, '/', rkeylen); c++; c_len = rkeylen - (c - rkey); if (strncmp(domain, c, c_len) == 0) out_flush_route_queue(s2s, rkey, rkeylen); } while(xhash_iter_next(s2s->outq)); } } Commit Message: Fixed possibility of Unsolicited Dialback Attacks CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static vpx_codec_err_t vp8_destroy(vpx_codec_alg_priv_t *ctx) { vp8_remove_decoder_instances(&ctx->yv12_frame_buffers); vpx_free(ctx); return VPX_CODEC_OK; } Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream Description from upstream: vp8: fix decoder crash with invalid leading keyframes decoding the same invalid keyframe twice would result in a crash as the second time through the decoder would be assumed to have been initialized as there was no resolution change. in this case the resolution was itself invalid (0x6), but vp8_peek_si() was only failing in the case of 0x0. invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by duplicating the first keyframe and additionally adds a valid one to ensure decoding can resume without error. Bug: 30593765 Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507 (cherry picked from commit fc0466b695dce03e10390101844caa374848d903) (cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136) CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mojo::ScopedSharedBufferMapping FakePlatformSensorProvider::GetMapping( mojom::SensorType type) { return CreateSharedBufferIfNeeded() ? MapSharedBufferForType(type) : nullptr; } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: void RenderView::OnDragTargetDragOver(const gfx::Point& client_point, const gfx::Point& screen_point, WebDragOperationsMask ops) { WebDragOperation operation = webview()->dragTargetDragOver( client_point, screen_point, ops); Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation)); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction) const { SecurityOrigin* securityOrigin = options.securityOrigin.get(); if (!securityOrigin && document()) securityOrigin = document()->securityOrigin(); if (securityOrigin && !securityOrigin->canDisplay(url)) { if (!forPreload) context().reportLocalLoadFailed(url); WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay"); return 0; } bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy); switch (type) { case Resource::MainResource: case Resource::Image: case Resource::CSSStyleSheet: case Resource::Script: case Resource::Font: case Resource::Raw: case Resource::LinkPrefetch: case Resource::LinkSubresource: case Resource::TextTrack: case Resource::ImportResource: case Resource::Media: if (originRestriction == FetchRequest::RestrictToSameOrigin && !securityOrigin->canRequest(url)) { printAccessDeniedMessage(url); return false; } break; case Resource::XSLStyleSheet: ASSERT(RuntimeEnabledFeatures::xsltEnabled()); case Resource::SVGDocument: if (!securityOrigin->canRequest(url)) { printAccessDeniedMessage(url); return false; } break; } ContentSecurityPolicy::ReportingStatus cspReporting = forPreload ? ContentSecurityPolicy::SuppressReport : ContentSecurityPolicy::SendReport; switch (type) { case Resource::XSLStyleSheet: ASSERT(RuntimeEnabledFeatures::xsltEnabled()); if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting)) return false; break; case Resource::Script: case Resource::ImportResource: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting)) return false; if (frame()) { Settings* settings = frame()->settings(); if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->scriptEnabled(), url)) { frame()->loader().client()->didNotAllowScript(); return false; } } break; case Resource::CSSStyleSheet: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowStyleFromSource(url, cspReporting)) return false; break; case Resource::SVGDocument: case Resource::Image: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowImageFromSource(url, cspReporting)) return false; break; case Resource::Font: { if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowFontFromSource(url, cspReporting)) return false; break; } case Resource::MainResource: case Resource::Raw: case Resource::LinkPrefetch: case Resource::LinkSubresource: break; case Resource::Media: case Resource::TextTrack: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url, cspReporting)) return false; break; } if (!checkInsecureContent(type, url, options.mixedContentBlockingTreatment)) return false; return true; } Commit Message: Enforce SVG image security rules SVG images have unique security rules that prevent them from loading any external resources. This patch enforces these rules in ResourceFetcher::canRequest for all non-data-uri resources. This locks down our SVG resource handling and fixes two security bugs. In the case of SVG images that reference other images, we had a bug where a cached subresource would be used directly from the cache. This has been fixed because the canRequest check occurs before we use cached resources. In the case of SVG images that use CSS imports, we had a bug where imports were blindly requested. This has been fixed by stopping all non-data-uri requests in SVG images. With this patch we now match Gecko's behavior on both testcases. BUG=380885, 382296 Review URL: https://codereview.chromium.org/320763002 git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(up, &kts); return err; } Commit Message: Fix order of arguments to compat_put_time[spec|val] Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in net/socket.c") introduced a bug where the helper functions to take either a 64-bit or compat time[spec|val] got the arguments in the wrong order, passing the kernel stack pointer off as a user pointer (and vice versa). Because of the user address range check, that in turn then causes an EFAULT due to the user pointer range checking failing for the kernel address. Incorrectly resuling in a failed system call for 32-bit processes with a 64-bit kernel. On odder architectures like HP-PA (with separate user/kernel address spaces), it can be used read kernel memory. Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: char *am_get_assertion_consumer_service_by_binding(LassoProvider *provider, const char *binding) { GList *descriptors; char *url; char *selected_descriptor; char *descriptor; char **tokens; guint n_tokens; GList *i; char *endptr; long descriptor_index, min_index; url = NULL; selected_descriptor = NULL; min_index = LONG_MAX; /* The descriptor list is unordered */ descriptors = lasso_provider_get_metadata_keys_for_role(provider, LASSO_PROVIDER_ROLE_SP); for (i = g_list_first(descriptors), tokens=NULL; i; i = g_list_next(i), g_strfreev(tokens)) { descriptor = i->data; descriptor_index = LONG_MAX; /* * Split the descriptor into tokens, only consider descriptors * which have at least 3 tokens and whose first token is * AssertionConsumerService */ tokens = g_strsplit(descriptor, " ", 0); n_tokens = g_strv_length(tokens); if (n_tokens < 3) continue; if (!g_str_equal(tokens[0], "AssertionConsumerService")) continue; if (!g_str_equal(tokens[1], binding)) continue; descriptor_index = strtol(tokens[2], &endptr, 10); if (tokens[2] == endptr) continue; /* could not parse int */ if (descriptor_index < min_index) { selected_descriptor = descriptor; min_index = descriptor_index; } } if (selected_descriptor) { url = lasso_provider_get_metadata_one_for_role(provider, LASSO_PROVIDER_ROLE_SP, selected_descriptor); } lasso_release_list_of_strings(descriptors); return url; } Commit Message: Fix redirect URL validation bypass It turns out that browsers silently convert backslash characters into forward slashes, while apr_uri_parse() does not. This mismatch allows an attacker to bypass the redirect URL validation by using an URL like: https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/ mod_auth_mellon will assume that it is a relative URL and allow the request to pass through, while the browsers will use it as an absolute url and redirect to https://malicious.example.org/ . This patch fixes this issue by rejecting all redirect URLs with backslashes. CWE ID: CWE-601 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: do_prefetch_tables (const void *gcmM, size_t gcmM_size) { prefetch_table(gcmM, gcmM_size); prefetch_table(gcmR, sizeof(gcmR)); } Commit Message: GCM: move look-up table to .data section and unshare between processes * cipher/cipher-gcm.c (ATTR_ALIGNED_64): New. (gcmR): Move to 'gcm_table' structure. (gcm_table): New structure for look-up table with counters before and after. (gcmR): New macro. (prefetch_table): Handle input with length not multiple of 256. (do_prefetch_tables): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: void DocumentLoader::SetSourceLocation( std::unique_ptr<SourceLocation> source_location) { source_location_ = std::move(source_location); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebMediaPlayerImpl::DidGetOpaqueResponseFromServiceWorker() const { if (data_source_) return data_source_->DidGetOpaqueResponseViaServiceWorker(); return false; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); ops->destroy(dev); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; } Commit Message: kvm: fix kvm_ioctl_create_device() reference counting (CVE-2019-6974) kvm_ioctl_create_device() does the following: 1. creates a device that holds a reference to the VM object (with a borrowed reference, the VM's refcount has not been bumped yet) 2. initializes the device 3. transfers the reference to the device to the caller's file descriptor table 4. calls kvm_get_kvm() to turn the borrowed reference to the VM into a real reference The ownership transfer in step 3 must not happen before the reference to the VM becomes a proper, non-borrowed reference, which only happens in step 4. After step 3, an attacker can close the file descriptor and drop the borrowed reference, which can cause the refcount of the kvm object to drop to zero. This means that we need to grab a reference for the device before anon_inode_getfd(), otherwise the VM can disappear from under us. Fixes: 852b6d57dc7f ("kvm: add device control API") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static void arcmsr_hbaA_flush_cache(struct AdapterControlBlock *acb) { struct MessageUnit_A __iomem *reg = acb->pmuA; int retry_count = 30; writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, &reg->inbound_msgaddr0); do { if (arcmsr_hbaA_wait_msgint_ready(acb)) break; else { retry_count--; printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \ timeout, retry count down = %d \n", acb->host->host_no, retry_count); } } while (retry_count != 0); } Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer() We need to put an upper bound on "user_len" so the memcpy() doesn't overflow. Cc: <[email protected]> Reported-by: Marco Grassi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Tomas Henzl <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (context_.fragment_clip) { OnUpdateClip(properties_->UpdateFragmentClip( context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, ToClipRect(*context_.fragment_clip)})); } else { OnClearClip(properties_->ClearFragmentClip()); } } if (properties_->FragmentClip()) context_.current.clip = properties_->FragmentClip(); } 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: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: spnego_gss_process_context_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t token_buffer) { OM_uint32 ret; ret = gss_process_context_token(minor_status, context_handle, token_buffer); 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 Target: 1 Example 2: Code: ft_validator_run( FT_Validator valid ) { /* This function doesn't work! None should call it. */ FT_UNUSED( valid ); return -1; } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)param); case OMX_IndexParamVideoVp8: return internalSetVp8Params( (const OMX_VIDEO_PARAM_VP8TYPE *)param); case OMX_IndexParamVideoAndroidVp8Encoder: return internalSetAndroidVp8Params( (const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param); default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, param); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ regs[value_regno].var_off = tnum_cast(regs[value_regno].var_off, size); __update_reg_bounds(&regs[value_regno]); } return err; } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Err fdsa_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_HintSample *ptr = (GF_HintSample *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_array_write(s, ptr->packetTable, bs); if (e) return e; if (ptr->extra_data) { e = gf_isom_box_write((GF_Box *)ptr->extra_data, bs); if (e) return e; } return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: do_local_notify(xmlNode * notify_src, const char *client_id, gboolean sync_reply, gboolean from_peer) { /* send callback to originating child */ cib_client_t *client_obj = NULL; int local_rc = pcmk_ok; if (client_id != NULL) { client_obj = g_hash_table_lookup(client_list, client_id); } else { crm_trace("No client to sent the response to. F_CIB_CLIENTID not set."); } if (client_obj == NULL) { local_rc = -ECONNRESET; } else { int rid = 0; if(sync_reply) { CRM_LOG_ASSERT(client_obj->request_id); rid = client_obj->request_id; client_obj->request_id = 0; crm_trace("Sending response %d to %s %s", rid, client_obj->name, from_peer?"(originator of delegated request)":""); } else { crm_trace("Sending an event to %s %s", client_obj->name, from_peer?"(originator of delegated request)":""); } if (client_obj->ipc && crm_ipcs_send(client_obj->ipc, rid, notify_src, !sync_reply) < 0) { local_rc = -ENOMSG; #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client_obj->session) { crm_send_remote_msg(client_obj->session, notify_src, client_obj->encrypted); #endif } else if(client_obj->ipc == NULL) { crm_err("Unknown transport for %s", client_obj->name); } } if (local_rc != pcmk_ok && client_obj != NULL) { crm_warn("%sSync reply to %s failed: %s", sync_reply ? "" : "A-", client_obj ? client_obj->name : "<unknown>", pcmk_strerror(local_rc)); } } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int handle_unaligned_access(insn_size_t instruction, struct pt_regs *regs, struct mem_access *ma, int expected, unsigned long address) { u_int rm; int ret, index; /* * XXX: We can't handle mixed 16/32-bit instructions yet */ if (instruction_size(instruction) != 2) return -EINVAL; index = (instruction>>8)&15; /* 0x0F00 */ rm = regs->regs[index]; /* * Log the unexpected fixups, and then pass them on to perf. * * We intentionally don't report the expected cases to perf as * otherwise the trapped I/O case will skew the results too much * to be useful. */ if (!expected) { unaligned_fixups_notify(current, instruction, regs); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address); } ret = -EFAULT; switch (instruction&0xF000) { case 0x0000: if (instruction==0x000B) { /* rts */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) regs->pc = regs->pr; } else if ((instruction&0x00FF)==0x0023) { /* braf @Rm */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) regs->pc += rm + 4; } else if ((instruction&0x00FF)==0x0003) { /* bsrf @Rm */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) { regs->pr = regs->pc + 4; regs->pc += rm + 4; } } else { /* mov.[bwl] to/from memory via r0+rn */ goto simple; } break; case 0x1000: /* mov.l Rm,@(disp,Rn) */ goto simple; case 0x2000: /* mov.[bwl] to memory, possibly with pre-decrement */ goto simple; case 0x4000: if ((instruction&0x00FF)==0x002B) { /* jmp @Rm */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) regs->pc = rm; } else if ((instruction&0x00FF)==0x000B) { /* jsr @Rm */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) { regs->pr = regs->pc + 4; regs->pc = rm; } } else { /* mov.[bwl] to/from memory via r0+rn */ goto simple; } break; case 0x5000: /* mov.l @(disp,Rm),Rn */ goto simple; case 0x6000: /* mov.[bwl] from memory, possibly with post-increment */ goto simple; case 0x8000: /* bf lab, bf/s lab, bt lab, bt/s lab */ switch (instruction&0x0F00) { case 0x0100: /* mov.w R0,@(disp,Rm) */ goto simple; case 0x0500: /* mov.w @(disp,Rm),R0 */ goto simple; case 0x0B00: /* bf lab - no delayslot*/ break; case 0x0F00: /* bf/s lab */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) { #if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB) if ((regs->sr & 0x00000001) != 0) regs->pc += 4; /* next after slot */ else #endif regs->pc += SH_PC_8BIT_OFFSET(instruction); } break; case 0x0900: /* bt lab - no delayslot */ break; case 0x0D00: /* bt/s lab */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) { #if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB) if ((regs->sr & 0x00000001) == 0) regs->pc += 4; /* next after slot */ else #endif regs->pc += SH_PC_8BIT_OFFSET(instruction); } break; } break; case 0xA000: /* bra label */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) regs->pc += SH_PC_12BIT_OFFSET(instruction); break; case 0xB000: /* bsr label */ ret = handle_delayslot(regs, instruction, ma); if (ret==0) { regs->pr = regs->pc + 4; regs->pc += SH_PC_12BIT_OFFSET(instruction); } break; } return ret; /* handle non-delay-slot instruction */ simple: ret = handle_unaligned_ins(instruction, regs, ma); if (ret==0) regs->pc += instruction_size(instruction); return ret; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: stringprep_unichar_to_utf8 (uint32_t c, char *outbuf) { return g_unichar_to_utf8 (c, outbuf); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int sgi_timer_set(struct k_itimer *timr, int flags, struct itimerspec * new_setting, struct itimerspec * old_setting) { unsigned long when, period, irqflags; int err = 0; cnodeid_t nodeid; struct mmtimer *base; struct rb_node *n; if (old_setting) sgi_timer_get(timr, old_setting); sgi_timer_del(timr); when = timespec_to_ns(new_setting->it_value); period = timespec_to_ns(new_setting->it_interval); if (when == 0) /* Clear timer */ return 0; base = kmalloc(sizeof(struct mmtimer), GFP_KERNEL); if (base == NULL) return -ENOMEM; if (flags & TIMER_ABSTIME) { struct timespec n; unsigned long now; getnstimeofday(&n); now = timespec_to_ns(n); if (when > now) when -= now; else /* Fire the timer immediately */ when = 0; } /* * Convert to sgi clock period. Need to keep rtc_time() as near as possible * to getnstimeofday() in order to be as faithful as possible to the time * specified. */ when = (when + sgi_clock_period - 1) / sgi_clock_period + rtc_time(); period = (period + sgi_clock_period - 1) / sgi_clock_period; /* * We are allocating a local SHub comparator. If we would be moved to another * cpu then another SHub may be local to us. Prohibit that by switching off * preemption. */ preempt_disable(); nodeid = cpu_to_node(smp_processor_id()); /* Lock the node timer structure */ spin_lock_irqsave(&timers[nodeid].lock, irqflags); base->timer = timr; base->cpu = smp_processor_id(); timr->it.mmtimer.clock = TIMER_SET; timr->it.mmtimer.node = nodeid; timr->it.mmtimer.incr = period; timr->it.mmtimer.expires = when; n = timers[nodeid].next; /* Add the new struct mmtimer to node's timer list */ mmtimer_add_list(base); if (timers[nodeid].next == n) { /* No need to reprogram comparator for now */ spin_unlock_irqrestore(&timers[nodeid].lock, irqflags); preempt_enable(); return err; } /* We need to reprogram the comparator */ if (n) mmtimer_disable_int(cnodeid_to_nasid(nodeid), COMPARATOR); mmtimer_set_next_timer(nodeid); /* Unlock the node timer structure */ spin_unlock_irqrestore(&timers[nodeid].lock, irqflags); preempt_enable(); return err; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION( msgfmt_format_message ) { zval *args; UChar *spattern = NULL; int spattern_len = 0; char *pattern = NULL; int pattern_len = 0; const char *slocale = NULL; int slocale_len = 0; MessageFormatter_object mf = {0}; MessageFormatter_object *mfo = &mf; /* Parse parameters. */ if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa", &slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } msgformat_data_init(&mfo->mf_data TSRMLS_CC); if(pattern && pattern_len) { intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo)); if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC ); RETURN_FALSE; } } else { spattern_len = 0; spattern = NULL; } if(slocale_len == 0) { slocale = intl_locale_get_default(TSRMLS_C); } #ifdef MSG_FORMAT_QUOTE_APOS if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) { intl_error_set( NULL, U_INVALID_FORMAT_ERROR, "msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC ); RETURN_FALSE; } #endif /* Create an ICU message formatter. */ MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo)); if(spattern && spattern_len) { efree(spattern); } INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed"); msgfmt_do_format(mfo, args, return_value TSRMLS_CC); /* drop the temporary formatter */ msgformat_data_free(&mfo->mf_data TSRMLS_CC); } Commit Message: Fix bug #73007: add locale length check CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Err fecr_dump(GF_Box *a, FILE * trace) { u32 i; char *box_name; FECReservoirBox *ptr = (FECReservoirBox *) a; if (a->type==GF_ISOM_BOX_TYPE_FIRE) { box_name = "FILEReservoirBox"; } else { box_name = "FECReservoirBox"; } gf_isom_box_dump_start(a, box_name, trace); fprintf(trace, ">\n"); for (i=0; i<ptr->nb_entries; i++) { fprintf(trace, "<%sEntry itemID=\"%d\" symbol_count=\"%d\"/>\n", box_name, ptr->entries[i].item_id, ptr->entries[i].symbol_count); } if (!ptr->size) { fprintf(trace, "<%sEntry itemID=\"\" symbol_count=\"\"/>\n", box_name); } gf_isom_box_dump_done(box_name, a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int Session_ReleaseEffect(preproc_session_t *session, preproc_effect_t *fx) { ALOGW_IF(Effect_Release(fx) != 0, " Effect_Release() failed for proc ID %d", fx->procId); session->createdMsk &= ~(1<<fx->procId); if (session->createdMsk == 0) { webrtc::AudioProcessing::Destroy(session->apm); session->apm = NULL; delete session->procFrame; session->procFrame = NULL; delete session->revFrame; session->revFrame = NULL; if (session->inResampler != NULL) { speex_resampler_destroy(session->inResampler); session->inResampler = NULL; } if (session->outResampler != NULL) { speex_resampler_destroy(session->outResampler); session->outResampler = NULL; } if (session->revResampler != NULL) { speex_resampler_destroy(session->revResampler); session->revResampler = NULL; } delete session->inBuf; session->inBuf = NULL; delete session->outBuf; session->outBuf = NULL; delete session->revBuf; session->revBuf = NULL; session->io = 0; } return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: process_demand_active(STREAM s) { uint8 type; uint16 len_src_descriptor, len_combined_caps; /* at this point we need to ensure that we have ui created */ rd_create_ui(); in_uint32_le(s, g_rdp_shareid); in_uint16_le(s, len_src_descriptor); in_uint16_le(s, len_combined_caps); in_uint8s(s, len_src_descriptor); logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid); rdp_process_server_caps(s, len_combined_caps); rdp_send_confirm_active(); rdp_send_synchronise(); rdp_send_control(RDP_CTL_COOPERATE); rdp_send_control(RDP_CTL_REQUEST_CONTROL); rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */ rdp_recv(&type); /* RDP_CTL_COOPERATE */ rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */ rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0, g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0); if (g_rdp_version >= RDP_V5) { rdp_enum_bmpcache2(); rdp_send_fonts(3); } else { rdp_send_fonts(1); rdp_send_fonts(2); } rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */ reset_order_state(); } 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 Target: 1 Example 2: Code: ProcRenderCreateGlyphSet (ClientPtr client) { GlyphSetPtr glyphSet; PictFormatPtr format; int rc, f; REQUEST(xRenderCreateGlyphSetReq); REQUEST_SIZE_MATCH(xRenderCreateGlyphSetReq); LEGAL_NEW_RESOURCE(stuff->gsid, client); rc = dixLookupResourceByType((pointer *)&format, stuff->format, PictFormatType, client, DixReadAccess); if (rc != Success) return rc; switch (format->depth) { case 1: f = GlyphFormat1; break; case 4: f = GlyphFormat4; break; case 8: f = GlyphFormat8; break; case 16: f = GlyphFormat16; break; case 32: f = GlyphFormat32; break; default: return BadMatch; } if (format->type != PictTypeDirect) return BadMatch; glyphSet = AllocateGlyphSet (f, format); if (!glyphSet) return BadAlloc; /* security creation/labeling check */ rc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->gsid, GlyphSetType, glyphSet, RT_NONE, NULL, DixCreateAccess); if (rc != Success) return rc; if (!AddResource (stuff->gsid, GlyphSetType, (pointer)glyphSet)) return BadAlloc; return Success; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: CairoImage::~CairoImage () { if (image) cairo_surface_destroy (image); } Commit Message: CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start, unsigned long end, unsigned long vmflag) { unsigned long addr; /* do a global flush by default */ unsigned long base_pages_to_flush = TLB_FLUSH_ALL; preempt_disable(); if (current->active_mm != mm) goto out; if (!current->mm) { leave_mm(smp_processor_id()); goto out; } if ((end != TLB_FLUSH_ALL) && !(vmflag & VM_HUGETLB)) base_pages_to_flush = (end - start) >> PAGE_SHIFT; if (base_pages_to_flush > tlb_single_page_flush_ceiling) { base_pages_to_flush = TLB_FLUSH_ALL; count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL); local_flush_tlb(); } else { /* flush range by one by one 'invlpg' */ for (addr = start; addr < end; addr += PAGE_SIZE) { count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE); __flush_tlb_single(addr); } } trace_tlb_flush(TLB_LOCAL_MM_SHOOTDOWN, base_pages_to_flush); out: if (base_pages_to_flush == TLB_FLUSH_ALL) { start = 0UL; end = TLB_FLUSH_ALL; } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, end); preempt_enable(); } Commit Message: x86/mm: Add barriers and document switch_mm()-vs-flush synchronization When switch_mm() activates a new PGD, it also sets a bit that tells other CPUs that the PGD is in use so that TLB flush IPIs will be sent. In order for that to work correctly, the bit needs to be visible prior to loading the PGD and therefore starting to fill the local TLB. Document all the barriers that make this work correctly and add a couple that were missing. Signed-off-by: Andy Lutomirski <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Borislav Petkov <[email protected]> Cc: Brian Gerst <[email protected]> Cc: Dave Hansen <[email protected]> Cc: Denys Vlasenko <[email protected]> Cc: H. Peter Anvin <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: [email protected] Cc: [email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: struct crypto_async_request *crypto_dequeue_request(struct crypto_queue *queue) { return __crypto_dequeue_request(queue, 0); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool net_tx_pkt_send_loopback(struct NetTxPkt *pkt, NetClientState *nc) { bool res; pkt->is_loopback = true; res = net_tx_pkt_send(pkt, nc); pkt->is_loopback = false; return res; } Commit Message: CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) { BufferInfo *inInfo = NULL; OMX_BUFFERHEADERTYPE *inHeader = NULL; if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nFlags = 0; if (inHeader) { if (inHeader->nOffset == 0 && inHeader->nFilledLen) { mAnchorTimeUs = inHeader->nTimeStamp; mNumFramesOutput = 0; } if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { mSawInputEos = true; } mConfig->pInputBuffer = inHeader->pBuffer + inHeader->nOffset; mConfig->inputBufferCurrentLength = inHeader->nFilledLen; } else { mConfig->pInputBuffer = NULL; mConfig->inputBufferCurrentLength = 0; } mConfig->inputBufferMaxLength = 0; mConfig->inputBufferUsedLength = 0; mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); mConfig->pOutputBuffer = reinterpret_cast<int16_t *>(outHeader->pBuffer); ERROR_CODE decoderErr; if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf)) != NO_DECODING_ERROR) { ALOGV("mp3 decoder returned error %d", decoderErr); if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR && decoderErr != SIDE_INFO_ERROR) { ALOGE("mp3 decoder returned error %d", decoderErr); notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); mSignalledError = true; return; } if (mConfig->outputFrameSize == 0) { mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); } if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) { if (!mIsFirst) { outHeader->nOffset = 0; outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); memset(outHeader->pBuffer, 0, outHeader->nFilledLen); } outHeader->nFlags = OMX_BUFFERFLAG_EOS; mSignalledOutputEos = true; } else { ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence"); memset(outHeader->pBuffer, 0, mConfig->outputFrameSize * sizeof(int16_t)); if (inHeader) { mConfig->inputBufferUsedLength = inHeader->nFilledLen; } } } else if (mConfig->samplingRate != mSamplingRate || mConfig->num_channels != mNumChannels) { mSamplingRate = mConfig->samplingRate; mNumChannels = mConfig->num_channels; notify(OMX_EventPortSettingsChanged, 1, 0, NULL); mOutputPortSettingsChange = AWAITING_DISABLED; return; } if (mIsFirst) { mIsFirst = false; outHeader->nOffset = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset; } else if (!mSignalledOutputEos) { outHeader->nOffset = 0; outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t); } outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate; if (inHeader) { CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength); inHeader->nOffset += mConfig->inputBufferUsedLength; inHeader->nFilledLen -= mConfig->inputBufferUsedLength; if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } mNumFramesOutput += mConfig->outputFrameSize / mNumChannels; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } Commit Message: Check mp3 output buffer size Bug: 27793371 Change-Id: I0fe40a4cfd0a5b488f93d3f3ba6f9495235926ac CWE ID: CWE-20 Target: 1 Example 2: Code: synth_body(const char *len, int rnd) { int i, j, k, l; char *b; AN(len); i = strtoul(len, NULL, 0); assert(i > 0); b = malloc(i + 1L); AN(b); l = k = '!'; for (j = 0; j < i; j++) { if ((j % 64) == 63) { b[j] = '\n'; k++; if (k == '~') k = '!'; l = k; } else if (rnd) { b[j] = (random() % 95) + ' '; } else { b[j] = (char)l; if (++l == '~') l = '!'; } } b[i - 1] = '\n'; b[i] = '\0'; return (b); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ExtensionWebContentsObserver::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { InitializeRenderFrame(render_frame_host); } Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs. BUG=528505,226927 Review URL: https://codereview.chromium.org/1362433002 Cr-Commit-Position: refs/heads/master@{#351705} CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); __uint128_t tmp; void *valp = &tmp; u64 off; int err = 0; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (KVM_REG_SIZE(reg->id) > sizeof(tmp)) return -EINVAL; if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) { err = -EFAULT; goto out; } if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) { u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK; switch (mode) { case PSR_AA32_MODE_USR: case PSR_AA32_MODE_FIQ: case PSR_AA32_MODE_IRQ: case PSR_AA32_MODE_SVC: case PSR_AA32_MODE_ABT: case PSR_AA32_MODE_UND: case PSR_MODE_EL0t: case PSR_MODE_EL1t: case PSR_MODE_EL1h: break; default: err = -EINVAL; goto out; } } memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id)); out: return err; } Commit Message: arm64: KVM: Tighten guest core register access from userspace We currently allow userspace to access the core register file in about any possible way, including straddling multiple registers and doing unaligned accesses. This is not the expected use of the ABI, and nobody is actually using it that way. Let's tighten it by explicitly checking the size and alignment for each field of the register file. Cc: <[email protected]> Fixes: 2f4a07c5f9fe ("arm64: KVM: guest one-reg interface") Reviewed-by: Christoffer Dall <[email protected]> Reviewed-by: Mark Rutland <[email protected]> Signed-off-by: Dave Martin <[email protected]> [maz: rewrote Dave's initial patch to be more easily backported] Signed-off-by: Marc Zyngier <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static void op32_tx_suspend(struct b43_dmaring *ring) { b43_dma_write(ring, B43_DMA32_TXCTL, b43_dma_read(ring, B43_DMA32_TXCTL) | B43_DMA32_TXSUSPEND); } Commit Message: b43: allocate receive buffers big enough for max frame len + offset Otherwise, skb_put inside of dma_rx can fail... https://bugzilla.kernel.org/show_bug.cgi?id=32042 Signed-off-by: John W. Linville <[email protected]> Acked-by: Larry Finger <[email protected]> Cc: [email protected] CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool InputHandler::shouldRequestSpellCheckingOptionsForPoint(Platform::IntPoint& point, const Element* touchedElement, imf_sp_text_t& spellCheckingOptionRequest) { if (!isActiveTextEdit()) return false; Element* currentFocusElement = m_currentFocusElement.get(); if (!currentFocusElement || !currentFocusElement->isElementNode()) return false; while (!currentFocusElement->isRootEditableElement()) { Element* parentElement = currentFocusElement->parentElement(); if (!parentElement) break; currentFocusElement = parentElement; } if (touchedElement != currentFocusElement) return false; LayoutPoint contentPos(m_webPage->mapFromViewportToContents(point)); contentPos = DOMSupport::convertPointToFrame(m_webPage->mainFrame(), m_webPage->focusedOrMainFrame(), roundedIntPoint(contentPos)); Document* document = currentFocusElement->document(); ASSERT(document); RenderedDocumentMarker* marker = document->markers()->renderedMarkerContainingPoint(contentPos, DocumentMarker::Spelling); if (!marker) return false; m_didSpellCheckWord = true; spellCheckingOptionRequest.startTextPosition = marker->startOffset(); spellCheckingOptionRequest.endTextPosition = marker->endOffset(); m_spellCheckingOptionsRequest.startTextPosition = 0; m_spellCheckingOptionsRequest.endTextPosition = 0; SpellingLog(LogLevelInfo, "InputHandler::shouldRequestSpellCheckingOptionsForPoint Found spelling marker at point %d, %d\nMarker start %d end %d", point.x(), point.y(), spellCheckingOptionRequest.startTextPosition, spellCheckingOptionRequest.endTextPosition); return true; } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Local<v8::Value> ModuleSystem::RequireForJsInner( v8::Local<v8::String> module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Object> global(context()->v8_context()->Global()); v8::Local<v8::Value> modules_value; if (!GetPrivate(global, kModulesField, &modules_value) || modules_value->IsUndefined()) { Warn(GetIsolate(), "Extension view no longer exists"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); v8::Local<v8::Value> exports; if (!GetProperty(v8_context, modules, module_name, &exports) || !exports->IsUndefined()) return handle_scope.Escape(exports); exports = LoadModule(*v8::String::Utf8Value(module_name)); SetProperty(v8_context, modules, module_name, exports); return handle_scope.Escape(exports); } Commit Message: [Extensions] Harden against bindings interception There's more we can do but this is a start. BUG=590275 BUG=590118 Review URL: https://codereview.chromium.org/1748943002 Cr-Commit-Position: refs/heads/master@{#378621} CWE ID: CWE-284 Target: 1 Example 2: Code: static ssize_t ucma_write(struct file *filp, const char __user *buf, size_t len, loff_t *pos) { struct ucma_file *file = filp->private_data; struct rdma_ucm_cmd_hdr hdr; ssize_t ret; if (!ib_safe_file_access(filp)) { pr_err_once("ucma_write: process %d (%s) changed security contexts after opening file descriptor, this is not allowed.\n", task_tgid_vnr(current), current->comm); return -EACCES; } if (len < sizeof(hdr)) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; if (hdr.cmd >= ARRAY_SIZE(ucma_cmd_table)) return -EINVAL; if (hdr.in + sizeof(hdr) > len) return -EINVAL; if (!ucma_cmd_table[hdr.cmd]) return -ENOSYS; ret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out); if (!ret) ret = len; return ret; } Commit Message: infiniband: fix a possible use-after-free bug ucma_process_join() will free the new allocated "mc" struct, if there is any error after that, especially the copy_to_user(). But in parallel, ucma_leave_multicast() could find this "mc" through idr_find() before ucma_process_join() frees it, since it is already published. So "mc" could be used in ucma_leave_multicast() after it is been allocated and freed in ucma_process_join(), since we don't refcnt it. Fix this by separating "publish" from ID allocation, so that we can get an ID first and publish it later after copy_to_user(). Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support") Reported-by: Noam Rathaus <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c) { int j, c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = c1; } } else { c = getc(IN); if (c == EOF) { return OPJ_FALSE; } if (c == 0x00) { /* EOL */ x = 0; ++y; pix = pData + y * stride + x; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } x += (OPJ_UINT32)c; c = getc(IN); if (c == EOF) { return OPJ_FALSE; } y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 */ int j; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { int c1_int; OPJ_UINT8 c1; c1_int = getc(IN); if (c1_int == EOF) { return OPJ_FALSE; } c1 = (OPJ_UINT8)c1_int; *pix = c1; } if ((OPJ_UINT32)c & 1U) { /* skip padding byte */ c = getc(IN); if (c == EOF) { return OPJ_FALSE; } } } } }/* while() */ return OPJ_TRUE; } Commit Message: convertbmp: detect invalid file dimensions early width/length dimensions read from bmp headers are not necessarily valid. For instance they may have been maliciously set to very large values with the intention to cause DoS (large memory allocation, stack overflow). In these cases we want to detect the invalid size as early as possible. This commit introduces a counter which verifies that the number of written bytes corresponds to the advertized width/length. Fixes #1059 (CVE-2018-6616). CWE ID: CWE-400 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title) : valid_(true), native_dialog_(NULL), title_(title), web_contents_(web_contents) { } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: bool InspectorController::deviceEmulationEnabled() { if (InspectorPageAgent* pageAgent = m_instrumentingAgents->inspectorPageAgent()) return pageAgent->deviceMetricsOverrideEnabled(); return false; } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Cluster::HasBlockEntries( const Segment* pSegment, long long off, //relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); //relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; //absolute if ((total >= 0) && (pos >= total)) return 0; //we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; //interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id != 0x0F43B675) //weird: not cluster ID return -1; //generic error pos += len; //consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); if (size == 0) return 0; //cluster does not have entries pos += len; //consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; //cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; //no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0x0F43B675) //Cluster ID return 0; //no entries found if (id == 0x0C53BB6B) //Cues ID return 0; //no entries found pos += len; //consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) //BlockGroup ID return 1; //have at least one entry if (id == 0x23) //SimpleBlock ID return 1; //have at least one entry pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } } 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 Target: 1 Example 2: Code: RenderFrameObserverNatives::~RenderFrameObserverNatives() {} Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; set_acl_inode(inode, inode->i_mode); if (error == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::Release() { DCHECK(agent_.get()); DCHECK(pairing_delegate_); VLOG(1) << object_path_.value() << ": Release"; pincode_callback_.Reset(); passkey_callback_.Reset(); confirmation_callback_.Reset(); UnregisterAgent(); } 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: Target: 1 Example 2: Code: static int floppy_grab_irq_and_dma(void) { if (atomic_inc_return(&usage_count) > 1) return 0; /* * We might have scheduled a free_irq(), wait it to * drain first: */ flush_workqueue(floppy_wq); if (fd_request_irq()) { DPRINT("Unable to grab IRQ%d for the floppy driver\n", FLOPPY_IRQ); atomic_dec(&usage_count); return -1; } if (fd_request_dma()) { DPRINT("Unable to grab DMA%d for the floppy driver\n", FLOPPY_DMA); if (can_use_virtual_dma & 2) use_virtual_dma = can_use_virtual_dma = 1; if (!(can_use_virtual_dma & 1)) { fd_free_irq(); atomic_dec(&usage_count); return -1; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { if (floppy_request_regions(fdc)) goto cleanup; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { reset_fdc_info(1); fd_outb(FDCS->dor, FD_DOR); } } fdc = 0; set_dor(0, ~0, 8); /* avoid immediate interrupt */ for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) fd_outb(FDCS->dor, FD_DOR); /* * The driver will try and free resources and relies on us * to know if they were allocated or not. */ fdc = 0; irqdma_allocated = 1; return 0; cleanup: fd_free_irq(); fd_free_dma(); while (--fdc >= 0) floppy_release_regions(fdc); atomic_dec(&usage_count); return -1; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int PDFiumEngine::GetCharCount(int page_index) { DCHECK(PageIndexInBounds(page_index)); return pages_[page_index]->GetCharCount(); } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#515056} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) { EXPECT_TRUE(fb != NULL); const int idx = FindFreeBufferIndex(); if (idx == num_buffers_) return -1; if (ext_fb_list_[idx].size < min_size) { delete [] ext_fb_list_[idx].data; ext_fb_list_[idx].data = new uint8_t[min_size]; ext_fb_list_[idx].size = min_size; } SetFrameBuffer(idx, fb); return 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 Target: 1 Example 2: Code: void BackendImpl::InternalDoomEntry(EntryImpl* entry) { uint32_t hash = entry->GetHash(); std::string key = entry->GetKey(); Addr entry_addr = entry->entry()->address(); bool error; scoped_refptr<EntryImpl> parent_entry = MatchEntry(key, hash, true, entry_addr, &error); CacheAddr child(entry->GetNextAddress()); Trace("Doom entry 0x%p", entry); if (!entry->doomed()) { eviction_.OnDoomEntry(entry); entry->InternalDoom(); if (!new_eviction_) { DecreaseNumEntries(); } stats_.OnEvent(Stats::DOOM_ENTRY); } if (parent_entry) { parent_entry->SetNextAddress(Addr(child)); parent_entry = nullptr; } else if (!error) { data_->table[hash & mask_] = child; } FlushIndex(); } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void on_read(h2o_socket_t *sock, int status) { h2o_http2_conn_t *conn = sock->data; if (status != 0) { h2o_socket_read_stop(conn->sock); close_connection(conn); return; } update_idle_timeout(conn); parse_input(conn); /* write immediately, if there is no write in flight and if pending write exists */ if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) { h2o_timeout_unlink(&conn->_write.timeout_entry); do_emit_writereq(conn); } } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT16 count; BITMAP_DATA* newdata; count = bitmapUpdate->number * 2; newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } Commit Message: Fixed CVE-2018-8786 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119 Target: 1 Example 2: Code: BGD_DECLARE(void) gdImageSetThickness (gdImagePtr im, int thickness) { im->thick = thickness; } Commit Message: Fix #340: System frozen gdImageCreate() doesn't check for oversized images and as such is prone to DoS vulnerabilities. We fix that by applying the same overflow check that is already in place for gdImageCreateTrueColor(). CVE-2016-9317 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ProfilingProcessHost::Mode ProfilingProcessHost::GetCurrentMode() { const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); #if BUILDFLAG(USE_ALLOCATOR_SHIM) if (cmdline->HasSwitch(switches::kMemlog) || base::FeatureList::IsEnabled(kOOPHeapProfilingFeature)) { if (cmdline->HasSwitch(switches::kEnableHeapProfiling)) { LOG(ERROR) << "--" << switches::kEnableHeapProfiling << " specified with --" << switches::kMemlog << "which are not compatible. Memlog will be disabled."; return Mode::kNone; } std::string mode; if (cmdline->HasSwitch(switches::kMemlog)) { mode = cmdline->GetSwitchValueASCII(switches::kMemlog); } else { mode = base::GetFieldTrialParamValueByFeature( kOOPHeapProfilingFeature, kOOPHeapProfilingFeatureMode); } if (mode == switches::kMemlogModeAll) return Mode::kAll; if (mode == switches::kMemlogModeMinimal) return Mode::kMinimal; if (mode == switches::kMemlogModeBrowser) return Mode::kBrowser; if (mode == switches::kMemlogModeGpu) return Mode::kGpu; if (mode == switches::kMemlogModeRendererSampling) return Mode::kRendererSampling; DLOG(ERROR) << "Unsupported value: \"" << mode << "\" passed to --" << switches::kMemlog; } return Mode::kNone; #else LOG_IF(ERROR, cmdline->HasSwitch(switches::kMemlog)) << "--" << switches::kMemlog << " specified but it will have no effect because the use_allocator_shim " << "is not available in this build."; return Mode::kNone; #endif } Commit Message: [Reland #1] Add Android OOP HP end-to-end tests. The original CL added a javatest and its dependencies to the apk_under_test. This causes the dependencies to be stripped from the instrumentation_apk, which causes issue. This CL updates the build configuration so that the javatest and its dependencies are only added to the instrumentation_apk. This is a reland of e0b4355f0651adb1ebc2c513dc4410471af712f5 Original change's description: > Add Android OOP HP end-to-end tests. > > This CL has three components: > 1) The bulk of the logic in OOP HP was refactored into ProfilingTestDriver. > 2) Adds a java instrumentation test, along with a JNI shim that forwards into > ProfilingTestDriver. > 3) Creates a new apk: chrome_public_apk_for_test that contains the same > content as chrome_public_apk, as well as native files needed for (2). > chrome_public_apk_test now targets chrome_public_apk_for_test instead of > chrome_public_apk. > > Other ideas, discarded: > * Originally, I attempted to make the browser_tests target runnable on > Android. The primary problem is that native test harness cannot fork > or spawn processes. This is difficult to solve. > > More details on each of the components: > (1) ProfilingTestDriver > * The TracingController test was migrated to use ProfilingTestDriver, but the > write-to-file test was left as-is. The latter behavior will likely be phased > out, but I'll clean that up in a future CL. > * gtest isn't supported for Android instrumentation tests. ProfilingTestDriver > has a single function RunTest that returns a 'bool' indicating success. On > failure, the class uses LOG(ERROR) to print the nature of the error. This will > cause the error to be printed out on browser_test error. On instrumentation > test failure, the error will be forwarded to logcat, which is available on all > infra bot test runs. > (2) Instrumentation test > * For now, I only added a single test for the "browser" mode. Furthermore, I'm > only testing the start with command-line path. > (3) New apk > * libchromefortest is a new shared library that contains all content from > libchrome, but also contains native sources for the JNI shim. > * chrome_public_apk_for_test is a new apk that contains all content from > chrome_public_apk, but uses a single shared library libchromefortest rather > than libchrome. This also contains java sources for the JNI shim. > * There is no way to just add a second shared library to chrome_public_apk > that just contains the native sources from the JNI shim without causing ODR > issues. > * chrome_public_test_apk now has apk_under_test = chrome_public_apk_for_test. > * There is no way to add native JNI sources as a shared library to > chrome_public_test_apk without causing ODR issues. > > Finally, this CL drastically increases the timeout to wait for native > initialization. The previous timeout was 2 * > CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL, which flakily failed for this test. > This suggests that this step/timeout is generally flaky. I increased the timeout > to 20 * CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL. > > Bug: 753218 > Change-Id: Ic224b7314fff57f1770a4048aa5753f54e040b55 > Reviewed-on: https://chromium-review.googlesource.com/770148 > Commit-Queue: Erik Chen <[email protected]> > Reviewed-by: John Budorick <[email protected]> > Reviewed-by: Brett Wilson <[email protected]> > Cr-Commit-Position: refs/heads/master@{#517541} Bug: 753218 TBR: [email protected] Change-Id: Ic6aafb34c2467253f75cc85da48200d19f3bc9af Reviewed-on: https://chromium-review.googlesource.com/777697 Commit-Queue: Erik Chen <[email protected]> Reviewed-by: John Budorick <[email protected]> Cr-Commit-Position: refs/heads/master@{#517850} CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ieee80211_if_setup(struct net_device *dev) { ether_setup(dev); dev->netdev_ops = &ieee80211_dataif_ops; dev->destructor = free_netdev; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: status_t MediaPlayer::setAudioStreamType(audio_stream_type_t type) { ALOGV("MediaPlayer::setAudioStreamType"); Mutex::Autolock _l(mLock); if (mStreamType == type) return NO_ERROR; if (mCurrentState & ( MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) { ALOGE("setAudioStream called in state %d", mCurrentState); return INVALID_OPERATION; } mStreamType = type; return OK; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_show_options(struct seq_file *seq, struct vfsmount *vfs) { int def_errors; unsigned long def_mount_opts; struct super_block *sb = vfs->mnt_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; def_mount_opts = le32_to_cpu(es->s_default_mount_opts); def_errors = le16_to_cpu(es->s_errors); if (sbi->s_sb_block != 1) seq_printf(seq, ",sb=%llu", sbi->s_sb_block); if (test_opt(sb, MINIX_DF)) seq_puts(seq, ",minixdf"); if (test_opt(sb, GRPID) && !(def_mount_opts & EXT4_DEFM_BSDGROUPS)) seq_puts(seq, ",grpid"); if (!test_opt(sb, GRPID) && (def_mount_opts & EXT4_DEFM_BSDGROUPS)) seq_puts(seq, ",nogrpid"); if (sbi->s_resuid != EXT4_DEF_RESUID || le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID) { seq_printf(seq, ",resuid=%u", sbi->s_resuid); } if (sbi->s_resgid != EXT4_DEF_RESGID || le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID) { seq_printf(seq, ",resgid=%u", sbi->s_resgid); } if (test_opt(sb, ERRORS_RO)) { if (def_errors == EXT4_ERRORS_PANIC || def_errors == EXT4_ERRORS_CONTINUE) { seq_puts(seq, ",errors=remount-ro"); } } if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE) seq_puts(seq, ",errors=continue"); if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC) seq_puts(seq, ",errors=panic"); if (test_opt(sb, NO_UID32) && !(def_mount_opts & EXT4_DEFM_UID16)) seq_puts(seq, ",nouid32"); if (test_opt(sb, DEBUG) && !(def_mount_opts & EXT4_DEFM_DEBUG)) seq_puts(seq, ",debug"); if (test_opt(sb, OLDALLOC)) seq_puts(seq, ",oldalloc"); #ifdef CONFIG_EXT4_FS_XATTR if (test_opt(sb, XATTR_USER) && !(def_mount_opts & EXT4_DEFM_XATTR_USER)) seq_puts(seq, ",user_xattr"); if (!test_opt(sb, XATTR_USER) && (def_mount_opts & EXT4_DEFM_XATTR_USER)) { seq_puts(seq, ",nouser_xattr"); } #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (test_opt(sb, POSIX_ACL) && !(def_mount_opts & EXT4_DEFM_ACL)) seq_puts(seq, ",acl"); if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT4_DEFM_ACL)) seq_puts(seq, ",noacl"); #endif if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) { seq_printf(seq, ",commit=%u", (unsigned) (sbi->s_commit_interval / HZ)); } if (sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME) { seq_printf(seq, ",min_batch_time=%u", (unsigned) sbi->s_min_batch_time); } if (sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME) { seq_printf(seq, ",max_batch_time=%u", (unsigned) sbi->s_min_batch_time); } /* * We're changing the default of barrier mount option, so * let's always display its mount state so it's clear what its * status is. */ seq_puts(seq, ",barrier="); seq_puts(seq, test_opt(sb, BARRIER) ? "1" : "0"); if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) seq_puts(seq, ",journal_async_commit"); if (test_opt(sb, NOBH)) seq_puts(seq, ",nobh"); if (test_opt(sb, I_VERSION)) seq_puts(seq, ",i_version"); if (!test_opt(sb, DELALLOC)) seq_puts(seq, ",nodelalloc"); if (sbi->s_stripe) seq_printf(seq, ",stripe=%lu", sbi->s_stripe); /* * journal mode get enabled in different ways * So just print the value even if we didn't specify it */ if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) seq_puts(seq, ",data=journal"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) seq_puts(seq, ",data=ordered"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA) seq_puts(seq, ",data=writeback"); if (sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS) seq_printf(seq, ",inode_readahead_blks=%u", sbi->s_inode_readahead_blks); if (test_opt(sb, DATA_ERR_ABORT)) seq_puts(seq, ",data_err=abort"); if (test_opt(sb, NO_AUTO_DA_ALLOC)) seq_puts(seq, ",noauto_da_alloc"); if (test_opt(sb, DISCARD)) seq_puts(seq, ",discard"); if (test_opt(sb, NOLOAD)) seq_puts(seq, ",norecovery"); ext4_show_quota_options(seq, sb); return 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item ) { cJSON_AddItemToObject( object, string, create_reference( item ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void OnWebIntentDispatchCompleted( const FilePath& file_path, webkit_glue::WebIntentReplyType intent_reply) { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&DeleteFile, file_path)); } Commit Message: For "Dangerous" file type, no user gesture will bypass the download warning. BUG=170569 Review URL: https://codereview.chromium.org/12039015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178072 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void kvm_arch_hardware_disable(void *garbage) { long status; int slot; unsigned long pte; unsigned long saved_psr; unsigned long host_iva = ia64_getreg(_IA64_REG_CR_IVA); pte = pte_val(mk_pte_phys(__pa(kvm_vmm_base), PAGE_KERNEL)); local_irq_save(saved_psr); slot = ia64_itr_entry(0x3, KVM_VMM_BASE, pte, KVM_VMM_SHIFT); local_irq_restore(saved_psr); if (slot < 0) return; status = ia64_pal_vp_exit_env(host_iva); if (status) printk(KERN_DEBUG"kvm: Failed to disable VT support! :%ld\n", status); ia64_ptr_entry(0x3, slot); } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <[email protected]> Signed-off-by: Avi Kivity <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IsAllowed(const scoped_refptr<const Extension>& extension, const GURL& url, PermittedFeature feature, int tab_id) { const PermissionsData* permissions_data = extension->permissions_data(); bool script = permissions_data->CanAccessPage(url, tab_id, nullptr) && permissions_data->CanRunContentScriptOnPage(url, tab_id, nullptr); bool capture = permissions_data->CanCaptureVisiblePage(url, tab_id, NULL); switch (feature) { case PERMITTED_SCRIPT_ONLY: return script && !capture; case PERMITTED_CAPTURE_ONLY: return capture && !script; case PERMITTED_BOTH: return script && capture; case PERMITTED_NONE: return !script && !capture; } NOTREACHED(); return false; } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} CWE ID: CWE-20 Target: 1 Example 2: Code: DrawingBuffer::ColorBuffer::ColorBuffer( DrawingBuffer* drawing_buffer, const ColorBufferParameters& parameters, const IntSize& size, GLuint texture_id, GLuint image_id, std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer) : drawing_buffer(drawing_buffer), parameters(parameters), size(size), texture_id(texture_id), image_id(image_id), gpu_memory_buffer(std::move(gpu_memory_buffer)) { drawing_buffer->ContextGL()->GenMailboxCHROMIUM(mailbox.name); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ps_parser_to_token( PS_Parser parser, T1_Token token ) { FT_Byte* cur; FT_Byte* limit; FT_Int embed; token->type = T1_TOKEN_TYPE_NONE; token->start = NULL; token->limit = NULL; /* first of all, skip leading whitespace */ ps_parser_skip_spaces( parser ); cur = parser->cursor; limit = parser->limit; if ( cur >= limit ) return; switch ( *cur ) { /************* check for literal string *****************/ case '(': token->type = T1_TOKEN_TYPE_STRING; token->start = cur; if ( skip_literal_string( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for programs/array *****************/ case '{': token->type = T1_TOKEN_TYPE_ARRAY; token->start = cur; if ( skip_procedure( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for table/array ********************/ /* XXX: in theory we should also look for "<<" */ /* since this is semantically equivalent to "["; */ /* in practice it doesn't matter (?) */ case '[': token->type = T1_TOKEN_TYPE_ARRAY; embed = 1; token->start = cur++; /* we need this to catch `[ ]' */ parser->cursor = cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; while ( cur < limit && !parser->error ) { /* XXX: this is wrong because it does not */ /* skip comments, procedures, and strings */ if ( *cur == '[' ) embed++; else if ( *cur == ']' ) { embed--; if ( embed <= 0 ) { token->limit = ++cur; break; } } parser->cursor = cur; ps_parser_skip_PS_token( parser ); /* we need this to catch `[XXX ]' */ ps_parser_skip_spaces ( parser ); cur = parser->cursor; } break; /* ************ otherwise, it is any token **************/ default: token->start = cur; token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY; ps_parser_skip_PS_token( parser ); cur = parser->cursor; if ( !parser->error ) token->limit = cur; } if ( !token->limit ) { token->start = NULL; token->type = T1_TOKEN_TYPE_NONE; } parser->cursor = cur; } /* NB: `tokens' can be NULL if we only want to count */ /* the number of array elements */ FT_LOCAL_DEF( void ) ps_parser_to_token_array( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ) { T1_TokenRec master; *pnum_tokens = -1; /* this also handles leading whitespace */ ps_parser_to_token( parser, &master ); if ( master.type == T1_TOKEN_TYPE_ARRAY ) { FT_Byte* old_cursor = parser->cursor; FT_Byte* old_limit = parser->limit; T1_Token cur = tokens; T1_Token limit = cur + max_tokens; /* don't include outermost delimiters */ parser->cursor = master.start + 1; parser->limit = master.limit - 1; while ( parser->cursor < parser->limit ) { T1_TokenRec token; ps_parser_to_token( parser, &token ); if ( !token.type ) break; if ( tokens && cur < limit ) *cur = token; cur++; } *pnum_tokens = (FT_Int)( cur - tokens ); parser->cursor = old_cursor; parser->limit = old_limit; } } /* first character must be a delimiter or a part of a number */ /* NB: `coords' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_coords' */ static FT_Int ps_tocoordarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_coords, FT_Short* coords ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* check for the beginning of an array; otherwise, only one number */ /* will be read */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the coordinates */ while ( cur < limit ) { FT_Short dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( coords && count >= max_coords ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( coords ? &coords[count] : &dummy ) = (FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } /* first character must be a delimiter or a part of a number */ /* NB: `values' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_values' */ /* */ /* return number of successfully parsed values */ static FT_Int ps_tofixedarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* Check for the beginning of an array. Otherwise, only one number */ /* will be read. */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the values */ while ( cur < limit ) { FT_Fixed dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( values && count >= max_values ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( values ? &values[count] : &dummy ) = PS_Conv_ToFixed( &cur, limit, power_ten ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } #if 0 static FT_String* ps_tostring( FT_Byte** cursor, FT_Byte* limit, FT_Memory memory ) { FT_Byte* cur = *cursor; FT_UInt len = 0; FT_Int count; FT_String* result; FT_Error error; /* XXX: some stupid fonts have a `Notice' or `Copyright' string */ /* that simply doesn't begin with an opening parenthesis, even */ /* though they have a closing one! E.g. "amuncial.pfb" */ /* */ /* We must deal with these ill-fated cases there. Note that */ /* these fonts didn't work with the old Type 1 driver as the */ /* notice/copyright was not recognized as a valid string token */ /* and made the old token parser commit errors. */ while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) ) cur++; if ( cur + 1 >= limit ) return 0; if ( *cur == '(' ) cur++; /* skip the opening parenthesis, if there is one */ *cursor = cur; count = 0; /* then, count its length */ for ( ; cur < limit; cur++ ) { if ( *cur == '(' ) count++; else if ( *cur == ')' ) { count--; if ( count < 0 ) break; } } len = (FT_UInt)( cur - *cursor ); if ( cur >= limit || FT_ALLOC( result, len + 1 ) ) return 0; /* now copy the string */ FT_MEM_COPY( result, *cursor, len ); result[len] = '\0'; *cursor = cur; return result; } #endif /* 0 */ static int ps_tobool( FT_Byte* *acur, FT_Byte* limit ) { FT_Byte* cur = *acur; FT_Bool result = 0; /* return 1 if we find `true', 0 otherwise */ if ( cur + 3 < limit && cur[0] == 't' && cur[1] == 'r' && cur[2] == 'u' && cur[3] == 'e' ) { result = 1; cur += 5; } else if ( cur + 4 < limit && cur[0] == 'f' && cur[1] == 'a' && cur[2] == 'l' && cur[3] == 's' && cur[4] == 'e' ) { result = 0; cur += 6; } *acur = cur; return result; } /* load a simple field (i.e. non-table) into the current list of objects */ FT_LOCAL_DEF( FT_Error ) ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } #define T1_MAX_TABLE_ELEMENTS 32 FT_LOCAL_DEF( FT_Error ) ps_parser_load_field_table( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS]; T1_Token token; FT_Int num_elements; FT_Error error = FT_Err_Ok; FT_Byte* old_cursor; FT_Byte* old_limit; T1_FieldRec fieldrec = *(T1_Field)field; fieldrec.type = T1_FIELD_TYPE_INTEGER; if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY || field->type == T1_FIELD_TYPE_BBOX ) fieldrec.type = T1_FIELD_TYPE_FIXED; ps_parser_to_token_array( parser, elements, T1_MAX_TABLE_ELEMENTS, &num_elements ); if ( num_elements < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( (FT_UInt)num_elements > field->array_max ) num_elements = (FT_Int)field->array_max; old_cursor = parser->cursor; old_limit = parser->limit; /* we store the elements count if necessary; */ /* we further assume that `count_offset' can't be zero */ if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 ) *(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) = (FT_Byte)num_elements; /* we now load each element, adjusting the field.offset on each one */ token = elements; for ( ; num_elements > 0; num_elements--, token++ ) { parser->cursor = token->start; parser->limit = token->limit; error = ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 ); if ( error ) break; fieldrec.offset += fieldrec.size; } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif parser->cursor = old_cursor; parser->limit = old_limit; Exit: return error; } FT_LOCAL_DEF( FT_Long ) ps_parser_to_int( PS_Parser parser ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToInt( &parser->cursor, parser->limit ); } /* first character must be `<' if `delimiters' is non-zero */ FT_LOCAL_DEF( FT_Error ) ps_parser_to_bytes( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_ULong* pnum_bytes, FT_Bool delimiters ) { FT_Error error = FT_Err_Ok; FT_Byte* cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; if ( cur >= parser->limit ) goto Exit; if ( delimiters ) { if ( *cur != '<' ) { FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } *pnum_bytes = PS_Conv_ASCIIHexDecode( &cur, parser->limit, bytes, max_bytes ); if ( delimiters ) { if ( cur < parser->limit && *cur != '>' ) { FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } parser->cursor = cur; Exit: return error; } FT_LOCAL_DEF( FT_Fixed ) ps_parser_to_fixed( PS_Parser parser, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_coord_array( PS_Parser parser, FT_Int max_coords, FT_Short* coords ) { ps_parser_skip_spaces( parser ); return ps_tocoordarray( &parser->cursor, parser->limit, max_coords, coords ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } #if 0 FT_LOCAL_DEF( FT_String* ) T1_ToString( PS_Parser parser ) { return ps_tostring( &parser->cursor, parser->limit, parser->memory ); } FT_LOCAL_DEF( FT_Bool ) T1_ToBool( PS_Parser parser ) { return ps_tobool( &parser->cursor, parser->limit ); } #endif /* 0 */ FT_LOCAL_DEF( void ) ps_parser_init( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ) { parser->error = FT_Err_Ok; parser->base = base; parser->limit = limit; parser->cursor = base; parser->memory = memory; parser->funcs = ps_parser_funcs; } FT_LOCAL_DEF( void ) ps_parser_done( PS_Parser parser ) { FT_UNUSED( parser ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting should be applied. */ /* */ FT_LOCAL_DEF( void ) t1_builder_init( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot glyph, FT_Bool hinting ) { builder->parse_state = T1_Parse_Start; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->memory; if ( glyph ) { FT_GlyphLoader loader = glyph->internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = size->internal; builder->hints_funcs = NULL; if ( hinting ) builder->hints_funcs = glyph->internal->glyph_hints; } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; builder->funcs = t1_builder_funcs; } /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ FT_LOCAL_DEF( void ) t1_builder_done( T1_Builder builder ) { FT_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->outline = *builder->base; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) t1_builder_check_points( T1_Builder builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) t1_builder_add_point( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; point->x = FIXED_TO_INT( x ); point->y = FIXED_TO_INT( y ); *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_point1( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = t1_builder_check_points( builder, 1 ); if ( !error ) t1_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Error error; /* this might happen in invalid fonts */ if ( !outline ) { FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" )); return FT_THROW( Invalid_File_Format ); } if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) t1_builder_start_point( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_ERR( Invalid_File_Format ); /* test whether we are building a new contour */ if ( builder->parse_state == T1_Parse_Have_Path ) error = FT_Err_Ok; else { builder->parse_state = T1_Parse_Have_Path; error = t1_builder_add_contour( builder ); if ( !error ) error = t1_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) t1_builder_close_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether the first and the last point is the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t MediaHTTP::connect( const char *uri, const KeyedVector<String8, String8> *headers, off64_t /* offset */) { if (mInitCheck != OK) { return mInitCheck; } KeyedVector<String8, String8> extHeaders; if (headers != NULL) { extHeaders = *headers; } if (extHeaders.indexOfKey(String8("User-Agent")) < 0) { extHeaders.add(String8("User-Agent"), String8(MakeUserAgent().c_str())); } bool success = mHTTPConnection->connect(uri, &extHeaders); mLastHeaders = extHeaders; mLastURI = uri; mCachedSizeValid = false; if (success) { AString sanitized = uriDebugString(uri); mName = String8::format("MediaHTTP(%s)", sanitized.c_str()); } return success ? OK : UNKNOWN_ERROR; } Commit Message: Fix free-after-use for MediaHTTP fix free-after-use when we reconnect to an HTTP media source. Change-Id: I96da5a79f5382409a545f8b4e22a24523f287464 Tests: compilation and eyeballs Bug: 31373622 (cherry picked from commit dd81e1592ffa77812998b05761eb840b70fed121) CWE ID: CWE-119 Target: 1 Example 2: Code: void av_memcpy_backptr(uint8_t *dst, int back, int cnt) { const uint8_t *src = &dst[-back]; if (!back) return; if (back == 1) { memset(dst, *src, cnt); } else if (back == 2) { fill16(dst, cnt); } else if (back == 3) { fill24(dst, cnt); } else if (back == 4) { fill32(dst, cnt); } else { if (cnt >= 16) { int blocklen = back; while (cnt > blocklen) { memcpy(dst, src, blocklen); dst += blocklen; cnt -= blocklen; blocklen <<= 1; } memcpy(dst, src, cnt); return; } if (cnt >= 8) { AV_COPY32U(dst, src); AV_COPY32U(dst + 4, src + 4); src += 8; dst += 8; cnt -= 8; } if (cnt >= 4) { AV_COPY32U(dst, src); src += 4; dst += 4; cnt -= 4; } if (cnt >= 2) { AV_COPY16U(dst, src); src += 2; dst += 2; cnt -= 2; } if (cnt) *dst = *src; } } Commit Message: avutil/mem: Fix flipped condition Fixes return code and later null pointer dereference Found-by: Laurent Butti <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void perf_event_switch(struct task_struct *task, struct task_struct *next_prev, bool sched_in) { struct perf_switch_event switch_event; /* N.B. caller checks nr_switch_events != 0 */ switch_event = (struct perf_switch_event){ .task = task, .next_prev = next_prev, .event_id = { .header = { /* .type */ .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT, /* .size */ }, /* .next_prev_pid */ /* .next_prev_tid */ }, }; perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Kees Cook <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Min Chong <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { unsigned key_ref; if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; key_ref = e->key_ref & ~OBERTHUR_PIN_LOCAL; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, 0); case SC_AC_CHV: if (key_ref > 0 && key_ref < 6) LOG_FUNC_RETURN(card->ctx, (0x20 | key_ref)); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); case SC_AC_PRO: if (((key_ref & 0xE0) != 0x60) || ((key_ref & 0x18) == 0)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); else LOG_FUNC_RETURN(card->ctx, key_ref); case SC_AC_NEVER: return 0xff; } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AddAboutStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"aboutProductLogoAlt", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT}, {"aboutPageTitle", IDS_SETTINGS_ABOUT_PROGRAM}, #if defined(OS_CHROMEOS) {"aboutProductTitle", IDS_PRODUCT_OS_NAME}, #else {"aboutProductTitle", IDS_PRODUCT_NAME}, #endif {"aboutGetHelpUsingChrome", IDS_SETTINGS_GET_HELP_USING_CHROME}, #if defined(GOOGLE_CHROME_BUILD) {"aboutReportAnIssue", IDS_SETTINGS_ABOUT_PAGE_REPORT_AN_ISSUE}, #endif {"aboutRelaunch", IDS_SETTINGS_ABOUT_PAGE_RELAUNCH}, {"aboutUpgradeCheckStarted", IDS_SETTINGS_ABOUT_UPGRADE_CHECK_STARTED}, {"aboutUpgradeRelaunch", IDS_SETTINGS_UPGRADE_SUCCESSFUL_RELAUNCH}, {"aboutUpgradeUpdating", IDS_SETTINGS_UPGRADE_UPDATING}, {"aboutUpgradeUpdatingPercent", IDS_SETTINGS_UPGRADE_UPDATING_PERCENT}, #if defined(OS_CHROMEOS) {"aboutArcVersionLabel", IDS_SETTINGS_ABOUT_PAGE_ARC_VERSION}, {"aboutBuildDateLabel", IDS_VERSION_UI_BUILD_DATE}, {"aboutChannelBeta", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_BETA}, {"aboutChannelCanary", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_CANARY}, {"aboutChannelDev", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_DEV}, {"aboutChannelLabel", IDS_SETTINGS_ABOUT_PAGE_CHANNEL}, {"aboutChannelStable", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL_STABLE}, {"aboutCheckForUpdates", IDS_SETTINGS_ABOUT_PAGE_CHECK_FOR_UPDATES}, {"aboutCommandLineLabel", IDS_VERSION_UI_COMMAND_LINE}, {"aboutCurrentlyOnChannel", IDS_SETTINGS_ABOUT_PAGE_CURRENT_CHANNEL}, {"aboutDetailedBuildInfo", IDS_SETTINGS_ABOUT_PAGE_DETAILED_BUILD_INFO}, {"aboutFirmwareLabel", IDS_SETTINGS_ABOUT_PAGE_FIRMWARE}, {"aboutPlatformLabel", IDS_SETTINGS_ABOUT_PAGE_PLATFORM}, {"aboutRelaunchAndPowerwash", IDS_SETTINGS_ABOUT_PAGE_RELAUNCH_AND_POWERWASH}, {"aboutUpgradeUpdatingChannelSwitch", IDS_SETTINGS_UPGRADE_UPDATING_CHANNEL_SWITCH}, {"aboutUpgradeSuccessChannelSwitch", IDS_SETTINGS_UPGRADE_SUCCESSFUL_CHANNEL_SWITCH}, {"aboutUserAgentLabel", IDS_VERSION_UI_USER_AGENT}, {"aboutTPMFirmwareUpdateTitle", IDS_SETTINGS_ABOUT_TPM_FIRMWARE_UPDATE_TITLE}, {"aboutTPMFirmwareUpdateDescription", IDS_SETTINGS_ABOUT_TPM_FIRMWARE_UPDATE_DESCRIPTION}, {"aboutChangeChannel", IDS_SETTINGS_ABOUT_PAGE_CHANGE_CHANNEL}, {"aboutChangeChannelAndPowerwash", IDS_SETTINGS_ABOUT_PAGE_CHANGE_CHANNEL_AND_POWERWASH}, {"aboutDelayedWarningMessage", IDS_SETTINGS_ABOUT_PAGE_DELAYED_WARNING_MESSAGE}, {"aboutDelayedWarningTitle", IDS_SETTINGS_ABOUT_PAGE_DELAYED_WARNING_TITLE}, {"aboutPowerwashWarningMessage", IDS_SETTINGS_ABOUT_PAGE_POWERWASH_WARNING_MESSAGE}, {"aboutPowerwashWarningTitle", IDS_SETTINGS_ABOUT_PAGE_POWERWASH_WARNING_TITLE}, {"aboutUnstableWarningMessage", IDS_SETTINGS_ABOUT_PAGE_UNSTABLE_WARNING_MESSAGE}, {"aboutUnstableWarningTitle", IDS_SETTINGS_ABOUT_PAGE_UNSTABLE_WARNING_TITLE}, {"aboutChannelDialogBeta", IDS_SETTINGS_ABOUT_PAGE_DIALOG_CHANNEL_BETA}, {"aboutChannelDialogDev", IDS_SETTINGS_ABOUT_PAGE_DIALOG_CHANNEL_DEV}, {"aboutChannelDialogStable", IDS_SETTINGS_ABOUT_PAGE_DIALOG_CHANNEL_STABLE}, {"aboutUpdateWarningMessage", IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_MESSAGE}, {"aboutUpdateWarningTitle", IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_TITLE}, {"aboutUpdateWarningContinue", IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_CONTINUE_BUTTON}, #endif // defined(OS_CHROMEOS) }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); html_source->AddString( "aboutUpgradeUpToDate", #if defined(OS_CHROMEOS) ui::SubstituteChromeOSDeviceType(IDS_SETTINGS_UPGRADE_UP_TO_DATE)); #else l10n_util::GetStringUTF16(IDS_SETTINGS_UPGRADE_UP_TO_DATE)); #endif #if defined(OS_CHROMEOS) html_source->AddString("aboutTPMFirmwareUpdateLearnMoreURL", chrome::kTPMFirmwareUpdateLearnMoreURL); #endif } Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles This change clarifies the wording around the password saving and autofill toggles. Bug: 822465 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670 Reviewed-on: https://chromium-review.googlesource.com/970541 Commit-Queue: Jan Wilken Dörrie <[email protected]> Reviewed-by: Vaclav Brozek <[email protected]> Reviewed-by: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#544661} CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _gnutls_server_name_recv_params (gnutls_session_t session, const opaque * data, size_t _data_size) { int i; const unsigned char *p; uint16_t len, type; ssize_t data_size = _data_size; int server_names = 0; if (session->security_parameters.entity == GNUTLS_SERVER) { DECR_LENGTH_RET (data_size, 2, 0); len = _gnutls_read_uint16 (data); if (len != data_size) { /* This is unexpected packet length, but * just ignore it, for now. */ gnutls_assert (); return 0; } p = data + 2; /* Count all server_names in the packet. */ while (data_size > 0) { DECR_LENGTH_RET (data_size, 1, 0); p++; DECR_LEN (data_size, 2); len = _gnutls_read_uint16 (p); p += 2; DECR_LENGTH_RET (data_size, len, 0); server_names++; p += len; } session->security_parameters.extensions.server_names_size = if (server_names == 0) return 0; /* no names found */ /* we cannot accept more server names. */ if (server_names > MAX_SERVER_NAME_EXTENSIONS) server_names = MAX_SERVER_NAME_EXTENSIONS; p = data + 2; for (i = 0; i < server_names; i++) server_names[i].name, p, len); session->security_parameters.extensions. server_names[i].name_length = len; session->security_parameters.extensions. server_names[i].type = GNUTLS_NAME_DNS; break; } } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static int __init crypto_xcbc_module_init(void) { return crypto_register_template(&crypto_xcbc_tmpl); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn, pfn_t pfn, unsigned access, int *ret_val) { bool ret = true; /* The pfn is invalid, report the error! */ if (unlikely(is_error_pfn(pfn))) { *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn); goto exit; } if (unlikely(is_noslot_pfn(pfn))) vcpu_cache_mmio_info(vcpu, gva, gfn, access); ret = false; exit: return ret; } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); free(name); return 0; } Commit Message: fsck: detect submodule paths starting with dash As with urls, submodule paths with dashes are ignored by git, but may end up confusing older versions. Detecting them via fsck lets us prevent modern versions of git from being a vector to spread broken .gitmodules to older versions. Compared to blocking leading-dash urls, though, this detection may be less of a good idea: 1. While such paths provide confusing and broken results, they don't seem to actually work as option injections against anything except "cd". In particular, the submodule code seems to canonicalize to an absolute path before running "git clone" (so it passes /your/clone/-sub). 2. It's more likely that we may one day make such names actually work correctly. Even after we revert this fsck check, it will continue to be a hassle until hosting servers are all updated. On the other hand, it's not entirely clear that the behavior in older versions is safe. And if we do want to eventually allow this, we may end up doing so with a special syntax anyway (e.g., writing "./-sub" in the .gitmodules file, and teaching the submodule code to canonicalize it when comparing). So on balance, this is probably a good protection. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static int khugepaged_wait_event(void) { return !list_empty(&khugepaged_scan.mm_head) || !khugepaged_enabled(); } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int opvmptrst(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_QWORD ) { data[l++] = 0x0f; data[l++] = 0xc7; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380) 0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL- leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: uint64 Clipboard::GetSequenceNumber(Buffer buffer) { return 0; } Commit Message: Use XFixes to update the clipboard sequence number. BUG=73478 TEST=manual testing Review URL: http://codereview.chromium.org/8501002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109528 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: cmsBool CMSEXPORT cmsIT8SetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample, const char *Val) { cmsIT8* it8 = (cmsIT8*) hIT8; int iField, iSet; TABLE* t; _cmsAssert(hIT8 != NULL); t = GetTable(it8); iField = LocateSample(it8, cSample); if (iField < 0) return FALSE; if (t-> nPatches == 0) { AllocateDataFormat(it8); AllocateDataSet(it8); CookPointers(it8); } if (cmsstrcasecmp(cSample, "SAMPLE_ID") == 0) { iSet = LocateEmptyPatch(it8); if (iSet < 0) { return SynError(it8, "Couldn't add more patches '%s'\n", cPatch); } iField = t -> SampleID; } else { iSet = LocatePatch(it8, cPatch); if (iSet < 0) { return FALSE; } } return SetData(it8, iSet, iField, Val); } Commit Message: Upgrade Visual studio 2017 15.8 - Upgrade to 15.8 - Add check on CGATS memory allocation (thanks to Quang Nguyen for pointing out this) CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: exsltCryptoRc4DecryptFunction (xmlXPathParserContextPtr ctxt, int nargs) { int key_len = 0, key_size = 0; int str_len = 0, bin_len = 0, ret_len = 0; xmlChar *key = NULL, *str = NULL, *padkey = NULL, *bin = NULL, *ret = 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); /* decode hex to binary */ bin_len = str_len; bin = xmlMallocAtomic (bin_len); if (bin == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate string\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } ret_len = exsltCryptoHex2Bin (str, str_len, bin, bin_len); /* decrypt the binary blob */ ret = xmlMallocAtomic (ret_len + 1); if (ret == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate result\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } PLATFORM_RC4_DECRYPT (ctxt, padkey, bin, ret_len, ret, ret_len); ret[ret_len] = 0; xmlXPathReturnString (ctxt, ret); 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; strcpy(the_url, url_arg); ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) strcpy(the_url, gf_dm_sess_get_cache_name(sess)); gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strcpy(the_url, "MP4Client "GPAC_FULL_VERSION); gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119 Target: 1 Example 2: Code: static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val, unsigned int bytes, struct x86_exception *exception) { struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt); u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0; return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access | PFERR_FETCH_MASK, exception); } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <[email protected]> Signed-off-by: Avi Kivity <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } Commit Message: Fix order of arguments to compat_put_time[spec|val] Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in net/socket.c") introduced a bug where the helper functions to take either a 64-bit or compat time[spec|val] got the arguments in the wrong order, passing the kernel stack pointer off as a user pointer (and vice versa). Because of the user address range check, that in turn then causes an EFAULT due to the user pointer range checking failing for the kernel address. Incorrectly resuling in a failed system call for 32-bit processes with a 64-bit kernel. On odder architectures like HP-PA (with separate user/kernel address spaces), it can be used read kernel memory. Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void update_open_stateflags(struct nfs4_state *state, mode_t open_flags) { switch (open_flags) { case FMODE_WRITE: state->n_wronly++; break; case FMODE_READ: state->n_rdonly++; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr++; } nfs4_state_set_mode_locked(state, state->state | open_flags); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Target: 1 Example 2: Code: EditorClient& Editor::client() const { if (Page* page = frame().page()) return page->editorClient(); return emptyEditorClient(); } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __init proc_caches_init(void) { sighand_cachep = kmem_cache_create("sighand_cache", sizeof(struct sighand_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU| SLAB_NOTRACK|SLAB_ACCOUNT, sighand_ctor); signal_cachep = kmem_cache_create("signal_cache", sizeof(struct signal_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL); files_cachep = kmem_cache_create("files_cache", sizeof(struct files_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL); fs_cachep = kmem_cache_create("fs_cache", sizeof(struct fs_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL); /* * FIXME! The "sizeof(struct mm_struct)" currently includes the * whole struct cpumask for the OFFSTACK case. We could change * this to *only* allocate as much of it as required by the * maximum number of CPU's we can ever have. The cpumask_allocation * is at the end of the structure, exactly for that reason. */ mm_cachep = kmem_cache_create("mm_struct", sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL); vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT); mmap_init(); nsproxy_cache_init(); } Commit Message: fork: fix incorrect fput of ->exe_file causing use-after-free Commit 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for write killable") made it possible to kill a forking task while it is waiting to acquire its ->mmap_sem for write, in dup_mmap(). However, it was overlooked that this introduced an new error path before a reference is taken on the mm_struct's ->exe_file. Since the ->exe_file of the new mm_struct was already set to the old ->exe_file by the memcpy() in dup_mm(), it was possible for the mmput() in the error path of dup_mm() to drop a reference to ->exe_file which was never taken. This caused the struct file to later be freed prematurely. Fix it by updating mm_init() to NULL out the ->exe_file, in the same place it clears other things like the list of mmaps. This bug was found by syzkaller. It can be reproduced using the following C program: #define _GNU_SOURCE #include <pthread.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/syscall.h> #include <sys/wait.h> #include <unistd.h> static void *mmap_thread(void *_arg) { for (;;) { mmap(NULL, 0x1000000, PROT_READ, MAP_POPULATE|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); } } static void *fork_thread(void *_arg) { usleep(rand() % 10000); fork(); } int main(void) { fork(); fork(); fork(); for (;;) { if (fork() == 0) { pthread_t t; pthread_create(&t, NULL, mmap_thread, NULL); pthread_create(&t, NULL, fork_thread, NULL); usleep(rand() % 10000); syscall(__NR_exit_group, 0); } wait(NULL); } } No special kernel config options are needed. It usually causes a NULL pointer dereference in __remove_shared_vm_struct() during exit, or in dup_mmap() (which is usually inlined into copy_process()) during fork. Both are due to a vm_area_struct's ->vm_file being used after it's already been freed. Google Bug Id: 64772007 Link: http://lkml.kernel.org/r/[email protected] Fixes: 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for write killable") Signed-off-by: Eric Biggers <[email protected]> Tested-by: Mark Rutland <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: Dmitry Vyukov <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Konstantin Khlebnikov <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Vlastimil Babka <[email protected]> Cc: <[email protected]> [v4.7+] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cypress_generic_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct cypress_private *priv; priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL); if (!priv) return -ENOMEM; priv->comm_is_ok = !0; spin_lock_init(&priv->lock); if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) { kfree(priv); return -ENOMEM; } /* Skip reset for FRWD device. It is a workaound: device hangs if it receives SET_CONFIGURE in Configured state. */ if (!is_frwd(serial->dev)) usb_reset_configuration(serial->dev); priv->cmd_ctrl = 0; priv->line_control = 0; priv->termios_initialized = 0; priv->rx_flags = 0; /* Default packet format setting is determined by packet size. Anything with a size larger then 9 must have a separate count field since the 3 bit count field is otherwise too small. Otherwise we can use the slightly more compact format. This is in accordance with the cypress_m8 serial converter app note. */ if (port->interrupt_out_size > 9) priv->pkt_fmt = packet_format_1; else priv->pkt_fmt = packet_format_2; if (interval > 0) { priv->write_urb_interval = interval; priv->read_urb_interval = interval; dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n", __func__, interval); } else { priv->write_urb_interval = port->interrupt_out_urb->interval; priv->read_urb_interval = port->interrupt_in_urb->interval; dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n", __func__, priv->read_urb_interval, priv->write_urb_interval); } usb_set_serial_port_data(port, priv); port->port.drain_delay = 256; return 0; } Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 1 Example 2: Code: void Part::loadArchive() { const QString fixedMimeType = arguments().metaData()[QStringLiteral("fixedMimeType")]; auto job = m_model->loadArchive(localFilePath(), fixedMimeType, m_model); if (job) { registerJob(job); job->start(); } else { updateActions(); } } Commit Message: CWE ID: CWE-78 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Chapters::Atom::ShallowCopy(Atom& rhs) const { rhs.m_string_uid = m_string_uid; rhs.m_uid = m_uid; rhs.m_start_timecode = m_start_timecode; rhs.m_stop_timecode = m_stop_timecode; rhs.m_displays = m_displays; rhs.m_displays_size = m_displays_size; rhs.m_displays_count = m_displays_count; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125 Target: 1 Example 2: Code: CIFSCreateHardLink(const int xid, struct cifs_tcon *tcon, const char *fromName, const char *toName, const struct nls_table *nls_codepage, int remap) { int rc = 0; NT_RENAME_REQ *pSMB = NULL; RENAME_RSP *pSMBr = NULL; int bytes_returned; int name_len, name_len2; __u16 count; cFYI(1, "In CIFSCreateHardLink"); winCreateHardLinkRetry: rc = smb_init(SMB_COM_NT_RENAME, 4, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; pSMB->SearchAttributes = cpu_to_le16(ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_DIRECTORY); pSMB->Flags = cpu_to_le16(CREATE_HARD_LINK); pSMB->ClusterCount = 0; pSMB->BufferFormat = 0x04; if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) { name_len = cifsConvertToUCS((__le16 *) pSMB->OldFileName, fromName, PATH_MAX, nls_codepage, remap); name_len++; /* trailing null */ name_len *= 2; /* protocol specifies ASCII buffer format (0x04) for unicode */ pSMB->OldFileName[name_len] = 0x04; pSMB->OldFileName[name_len + 1] = 0x00; /* pad */ name_len2 = cifsConvertToUCS((__le16 *)&pSMB->OldFileName[name_len + 2], toName, PATH_MAX, nls_codepage, remap); name_len2 += 1 /* trailing null */ + 1 /* Signature word */ ; name_len2 *= 2; /* convert to bytes */ } else { /* BB improve the check for buffer overruns BB */ name_len = strnlen(fromName, PATH_MAX); name_len++; /* trailing null */ strncpy(pSMB->OldFileName, fromName, name_len); name_len2 = strnlen(toName, PATH_MAX); name_len2++; /* trailing null */ pSMB->OldFileName[name_len] = 0x04; /* 2nd buffer format */ strncpy(&pSMB->OldFileName[name_len + 1], toName, name_len2); name_len2++; /* trailing null */ name_len2++; /* signature byte */ } count = 1 /* string type byte */ + name_len + name_len2; inc_rfc1001_len(pSMB, count); pSMB->ByteCount = cpu_to_le16(count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); cifs_stats_inc(&tcon->num_hardlinks); if (rc) cFYI(1, "Send error in hard link (NT rename) = %d", rc); cifs_buf_release(pSMB); if (rc == -EAGAIN) goto winCreateHardLinkRetry; return rc; } Commit Message: cifs: fix possible memory corruption in CIFSFindNext The name_len variable in CIFSFindNext is a signed int that gets set to the resume_name_len in the cifs_search_info. The resume_name_len however is unsigned and for some infolevels is populated directly from a 32 bit value sent by the server. If the server sends a very large value for this, then that value could look negative when converted to a signed int. That would make that value pass the PATH_MAX check later in CIFSFindNext. The name_len would then be used as a length value for a memcpy. It would then be treated as unsigned again, and the memcpy scribbles over a ton of memory. Fix this by making the name_len an unsigned value in CIFSFindNext. Cc: <[email protected]> Reported-by: Darren Lavender <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void cJSON_DeleteItemFromArray( cJSON *array, int which ) { cJSON_Delete( cJSON_DetachItemFromArray( array, which ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __jfs_set_acl(tid_t tid, struct inode *inode, int type, struct posix_acl *acl) { char *ea_name; int rc; int size = 0; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: ea_name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { rc = posix_acl_equiv_mode(acl, &inode->i_mode); if (rc < 0) return rc; inode->i_ctime = CURRENT_TIME; mark_inode_dirty(inode); if (rc == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: ea_name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; rc = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (rc < 0) goto out; } rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0); out: kfree(value); if (!rc) set_cached_acl(inode, type, acl); return rc; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 Target: 1 Example 2: Code: static int vmci_transport_send_conn_request2(struct sock *sk, size_t size, u16 version) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_REQUEST2, size, 0, NULL, version, VMCI_INVALID_HANDLE); } Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue() In case we received no data on the call to skb_recv_datagram(), i.e. skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0 without updating msg_namelen leading to net/socket.c leaking the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix this by moving the already existing msg_namelen assignment a few lines above. Cc: Andy King <[email protected]> Cc: Dmitry Torokhov <[email protected]> Cc: George Zhang <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ChromeRenderProcessHostBackgroundingTest() {} Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HttpAuthFilterWhitelist::AddRuleToBypassLocal() { rules_.AddRuleToBypassLocal(); } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20 Target: 1 Example 2: Code: static inline struct buffer *h2_get_buf(struct h2c *h2c, struct buffer **bptr) { struct buffer *buf = NULL; if (likely(LIST_ISEMPTY(&h2c->buf_wait.list)) && unlikely((buf = b_alloc_margin(bptr, 0)) == NULL)) { h2c->buf_wait.target = h2c; h2c->buf_wait.wakeup_cb = h2_buf_available; HA_SPIN_LOCK(BUF_WQ_LOCK, &buffer_wq_lock); LIST_ADDQ(&buffer_wq, &h2c->buf_wait.list); HA_SPIN_UNLOCK(BUF_WQ_LOCK, &buffer_wq_lock); __conn_xprt_stop_recv(h2c->conn); } return buf; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int aio_ring_mremap(struct vm_area_struct *vma) { struct file *file = vma->vm_file; struct mm_struct *mm = vma->vm_mm; struct kioctx_table *table; int i, res = -EINVAL; spin_lock(&mm->ioctx_lock); rcu_read_lock(); table = rcu_dereference(mm->ioctx_table); for (i = 0; i < table->nr; i++) { struct kioctx *ctx; ctx = table->table[i]; if (ctx && ctx->aio_ring_file == file) { if (!atomic_read(&ctx->dead)) { ctx->user_id = ctx->mmap_base = vma->vm_start; res = 0; } break; } } rcu_read_unlock(); spin_unlock(&mm->ioctx_lock); return res; } Commit Message: aio: mark AIO pseudo-fs noexec This ensures that do_mmap() won't implicitly make AIO memory mappings executable if the READ_IMPLIES_EXEC personality flag is set. Such behavior is problematic because the security_mmap_file LSM hook doesn't catch this case, potentially permitting an attacker to bypass a W^X policy enforced by SELinux. I have tested the patch on my machine. To test the behavior, compile and run this: #define _GNU_SOURCE #include <unistd.h> #include <sys/personality.h> #include <linux/aio_abi.h> #include <err.h> #include <stdlib.h> #include <stdio.h> #include <sys/syscall.h> int main(void) { personality(READ_IMPLIES_EXEC); aio_context_t ctx = 0; if (syscall(__NR_io_setup, 1, &ctx)) err(1, "io_setup"); char cmd[1000]; sprintf(cmd, "cat /proc/%d/maps | grep -F '/[aio]'", (int)getpid()); system(cmd); return 0; } In the output, "rw-s" is good, "rwxs" is bad. Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: make_transform_images(png_store *ps) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* This is in case of errors. */ safecat(ps->test, sizeof ps->test, 0, "make standard images"); /* Use next_format to enumerate all the combinations we test, including * generating multiple low bit depth palette images. */ while (next_format(&colour_type, &bit_depth, &palette_number, 0)) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, bit_depth, palette_number, interlace_type, 0, 0, 0); make_transform_image(ps, colour_type, bit_depth, palette_number, interlace_type, name); } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void HTMLFormElement::CollectListedElements( Node& root, ListedElement::List& elements) const { elements.clear(); for (HTMLElement& element : Traversal<HTMLElement>::StartsAfter(root)) { ListedElement* listed_element = nullptr; if (element.IsFormControlElement()) listed_element = ToHTMLFormControlElement(&element); else if (auto* object = ToHTMLObjectElementOrNull(element)) listed_element = object; else continue; if (listed_element->Form() == this) elements.push_back(listed_element); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AppCacheDatabase::InsertEntry(const EntryRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Entries (cache_id, url, flags, response_id, response_size)" " VALUES(?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindString(1, record->url.spec()); statement.BindInt(2, record->flags); statement.BindInt64(3, record->response_id); statement.BindInt64(4, record->response_size); return statement.Run(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SplashError Splash::drawImage(SplashImageSource src, void *srcData, SplashColorMode srcMode, GBool srcAlpha, int w, int h, SplashCoord *mat) { SplashPipe pipe; GBool ok, rot; SplashCoord xScale, yScale, xShear, yShear, yShear1; int tx, tx2, ty, ty2, scaledWidth, scaledHeight, xSign, ySign; int ulx, uly, llx, lly, urx, ury, lrx, lry; int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1; int xMin, xMax, yMin, yMax; SplashClipResult clipRes, clipRes2; int yp, yq, yt, yStep, lastYStep; int xp, xq, xt, xStep, xSrc; int k1, spanXMin, spanXMax, spanY; SplashColorPtr colorBuf, p; SplashColor pix; Guchar *alphaBuf, *q; #if SPLASH_CMYK int pixAcc0, pixAcc1, pixAcc2, pixAcc3; #else int pixAcc0, pixAcc1, pixAcc2; #endif int alphaAcc; SplashCoord pixMul, alphaMul, alpha; int x, y, x1, x2, y2; SplashCoord y1; int nComps, n, m, i, j; if (debugMode) { printf("drawImage: srcMode=%d srcAlpha=%d w=%d h=%d mat=[%.2f %.2f %.2f %.2f %.2f %.2f]\n", srcMode, srcAlpha, w, h, (double)mat[0], (double)mat[1], (double)mat[2], (double)mat[3], (double)mat[4], (double)mat[5]); } ok = gFalse; // make gcc happy nComps = 0; // make gcc happy switch (bitmap->mode) { case splashModeMono1: case splashModeMono8: ok = srcMode == splashModeMono8; nComps = 1; break; case splashModeRGB8: ok = srcMode == splashModeRGB8; nComps = 3; break; case splashModeXBGR8: ok = srcMode == splashModeXBGR8; nComps = 4; break; case splashModeBGR8: ok = srcMode == splashModeBGR8; nComps = 3; break; #if SPLASH_CMYK case splashModeCMYK8: ok = srcMode == splashModeCMYK8; nComps = 4; break; #endif } if (!ok) { return splashErrModeMismatch; } if (splashAbs(mat[0] * mat[3] - mat[1] * mat[2]) < 0.000001) { return splashErrSingularMatrix; } rot = splashAbs(mat[1]) > splashAbs(mat[0]); if (rot) { xScale = -mat[1]; yScale = mat[2] - (mat[0] * mat[3]) / mat[1]; xShear = -mat[3] / yScale; yShear = -mat[0] / mat[1]; } else { xScale = mat[0]; yScale = mat[3] - (mat[1] * mat[2]) / mat[0]; xShear = mat[2] / yScale; yShear = mat[1] / mat[0]; } if (xScale >= 0) { tx = splashFloor(mat[4] - 0.01); tx2 = splashFloor(mat[4] + xScale + 0.01); } else { tx = splashFloor(mat[4] + 0.01); tx2 = splashFloor(mat[4] + xScale - 0.01); } scaledWidth = abs(tx2 - tx) + 1; if (yScale >= 0) { ty = splashFloor(mat[5] - 0.01); ty2 = splashFloor(mat[5] + yScale + 0.01); } else { ty = splashFloor(mat[5] + 0.01); ty2 = splashFloor(mat[5] + yScale - 0.01); } scaledHeight = abs(ty2 - ty) + 1; xSign = (xScale < 0) ? -1 : 1; ySign = (yScale < 0) ? -1 : 1; yShear1 = (SplashCoord)xSign * yShear; ulx1 = 0; uly1 = 0; urx1 = xSign * (scaledWidth - 1); ury1 = (int)(yShear * urx1); llx1 = splashRound(xShear * ySign * (scaledHeight - 1)); lly1 = ySign * (scaledHeight - 1) + (int)(yShear * llx1); lrx1 = xSign * (scaledWidth - 1) + splashRound(xShear * ySign * (scaledHeight - 1)); lry1 = ySign * (scaledHeight - 1) + (int)(yShear * lrx1); if (rot) { ulx = tx + uly1; uly = ty - ulx1; urx = tx + ury1; ury = ty - urx1; llx = tx + lly1; lly = ty - llx1; lrx = tx + lry1; lry = ty - lrx1; } else { ulx = tx + ulx1; uly = ty + uly1; urx = tx + urx1; ury = ty + ury1; llx = tx + llx1; lly = ty + lly1; lrx = tx + lrx1; lry = ty + lry1; } xMin = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx : (llx < lrx) ? llx : lrx : (urx < llx) ? (urx < lrx) ? urx : lrx : (llx < lrx) ? llx : lrx; xMax = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx : (llx > lrx) ? llx : lrx : (urx > llx) ? (urx > lrx) ? urx : lrx : (llx > lrx) ? llx : lrx; yMin = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry : (lly < lry) ? lly : lry : (ury < lly) ? (ury < lry) ? ury : lry : (lly < lry) ? lly : lry; yMax = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry : (lly > lry) ? lly : lry : (ury > lly) ? (ury > lry) ? ury : lry : (lly > lry) ? lly : lry; clipRes = state->clip->testRect(xMin, yMin, xMax, yMax); opClipRes = clipRes; if (clipRes == splashClipAllOutside) { return splashOk; } yp = h / scaledHeight; yq = h % scaledHeight; xp = w / scaledWidth; xq = w % scaledWidth; colorBuf = (SplashColorPtr)gmalloc((yp + 1) * w * nComps); if (srcAlpha) { alphaBuf = (Guchar *)gmalloc((yp + 1) * w); } else { alphaBuf = NULL; } pixAcc0 = pixAcc1 = pixAcc2 = 0; // make gcc happy #if SPLASH_CMYK pixAcc3 = 0; // make gcc happy #endif pipeInit(&pipe, 0, 0, NULL, pix, state->fillAlpha, srcAlpha || (vectorAntialias && clipRes != splashClipAllInside), gFalse); if (vectorAntialias) { drawAAPixelInit(); } if (srcAlpha) { yt = 0; lastYStep = 1; for (y = 0; y < scaledHeight; ++y) { yStep = yp; yt += yq; if (yt >= scaledHeight) { yt -= scaledHeight; ++yStep; } n = (yp > 0) ? yStep : lastYStep; if (n > 0) { p = colorBuf; q = alphaBuf; for (i = 0; i < n; ++i) { (*src)(srcData, p, q); p += w * nComps; q += w; } } lastYStep = yStep; k1 = splashRound(xShear * ySign * y); if (clipRes != splashClipAllInside && !rot && (int)(yShear * k1) == (int)(yShear * (xSign * (scaledWidth - 1) + k1))) { if (xSign > 0) { spanXMin = tx + k1; spanXMax = spanXMin + (scaledWidth - 1); } else { spanXMax = tx + k1; spanXMin = spanXMax - (scaledWidth - 1); } spanY = ty + ySign * y + (int)(yShear * k1); clipRes2 = state->clip->testSpan(spanXMin, spanXMax, spanY); if (clipRes2 == splashClipAllOutside) { continue; } } else { clipRes2 = clipRes; } xt = 0; xSrc = 0; x1 = k1; y1 = (SplashCoord)ySign * y + yShear * x1; if (yShear1 < 0) { y1 += 0.999; } n = yStep > 0 ? yStep : 1; switch (srcMode) { case splashModeMono1: case splashModeMono8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; alphaAcc = 0; p = colorBuf + xSrc; q = alphaBuf + xSrc; pixAcc0 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; alphaAcc += *q++; } p += w - m; q += w - m; } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); alphaMul = pixMul * (1.0 / 255.0); alpha = (SplashCoord)alphaAcc * alphaMul; if (alpha > 0) { pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pipe.shape = alpha; if (vectorAntialias && clipRes != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; case splashModeRGB8: case splashModeBGR8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; alphaAcc = 0; p = colorBuf + xSrc * 3; q = alphaBuf + xSrc; pixAcc0 = pixAcc1 = pixAcc2 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; alphaAcc += *q++; } p += 3 * (w - m); q += w - m; } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); alphaMul = pixMul * (1.0 / 255.0); alpha = (SplashCoord)alphaAcc * alphaMul; if (alpha > 0) { pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); pipe.shape = alpha; if (vectorAntialias && clipRes != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; case splashModeXBGR8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; alphaAcc = 0; p = colorBuf + xSrc * 4; q = alphaBuf + xSrc; pixAcc0 = pixAcc1 = pixAcc2 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; *p++; alphaAcc += *q++; } p += 4 * (w - m); q += w - m; } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); alphaMul = pixMul * (1.0 / 255.0); alpha = (SplashCoord)alphaAcc * alphaMul; if (alpha > 0) { pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); pix[3] = 255; pipe.shape = alpha; if (vectorAntialias && clipRes != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; #if SPLASH_CMYK case splashModeCMYK8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; alphaAcc = 0; p = colorBuf + xSrc * 4; q = alphaBuf + xSrc; pixAcc0 = pixAcc1 = pixAcc2 = pixAcc3 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; pixAcc3 += *p++; alphaAcc += *q++; } p += 4 * (w - m); q += w - m; } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); alphaMul = pixMul * (1.0 / 255.0); alpha = (SplashCoord)alphaAcc * alphaMul; if (alpha > 0) { pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); pix[3] = (int)((SplashCoord)pixAcc3 * pixMul); pipe.shape = alpha; if (vectorAntialias && clipRes != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; #endif // SPLASH_CMYK } } } else { yt = 0; lastYStep = 1; for (y = 0; y < scaledHeight; ++y) { yStep = yp; yt += yq; if (yt >= scaledHeight) { yt -= scaledHeight; ++yStep; } n = (yp > 0) ? yStep : lastYStep; if (n > 0) { p = colorBuf; for (i = 0; i < n; ++i) { (*src)(srcData, p, NULL); p += w * nComps; } } lastYStep = yStep; k1 = splashRound(xShear * ySign * y); if (clipRes != splashClipAllInside && !rot && (int)(yShear * k1) == (int)(yShear * (xSign * (scaledWidth - 1) + k1))) { if (xSign > 0) { spanXMin = tx + k1; spanXMax = spanXMin + (scaledWidth - 1); } else { spanXMax = tx + k1; spanXMin = spanXMax - (scaledWidth - 1); } spanY = ty + ySign * y + (int)(yShear * k1); clipRes2 = state->clip->testSpan(spanXMin, spanXMax, spanY); if (clipRes2 == splashClipAllOutside) { continue; } } else { clipRes2 = clipRes; } xt = 0; xSrc = 0; x1 = k1; y1 = (SplashCoord)ySign * y + yShear * x1; if (yShear1 < 0) { y1 += 0.999; } n = yStep > 0 ? yStep : 1; switch (srcMode) { case splashModeMono1: case splashModeMono8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = colorBuf + xSrc; pixAcc0 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; } p += w - m; } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); if (vectorAntialias && clipRes != splashClipAllInside) { pipe.shape = (SplashCoord)1; drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; case splashModeRGB8: case splashModeBGR8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = colorBuf + xSrc * 3; pixAcc0 = pixAcc1 = pixAcc2 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; } p += 3 * (w - m); } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); if (vectorAntialias && clipRes != splashClipAllInside) { pipe.shape = (SplashCoord)1; drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; case splashModeXBGR8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = colorBuf + xSrc * 4; pixAcc0 = pixAcc1 = pixAcc2 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; *p++; } p += 4 * (w - m); } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); pix[3] = 255; if (vectorAntialias && clipRes != splashClipAllInside) { pipe.shape = (SplashCoord)1; drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; #if SPLASH_CMYK case splashModeCMYK8: for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = colorBuf + xSrc * 4; pixAcc0 = pixAcc1 = pixAcc2 = pixAcc3 = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc0 += *p++; pixAcc1 += *p++; pixAcc2 += *p++; pixAcc3 += *p++; } p += 4 * (w - m); } pixMul = (SplashCoord)1 / (SplashCoord)(n * m); pix[0] = (int)((SplashCoord)pixAcc0 * pixMul); pix[1] = (int)((SplashCoord)pixAcc1 * pixMul); pix[2] = (int)((SplashCoord)pixAcc2 * pixMul); pix[3] = (int)((SplashCoord)pixAcc3 * pixMul); if (vectorAntialias && clipRes != splashClipAllInside) { pipe.shape = (SplashCoord)1; drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } xSrc += xStep; x1 += xSign; y1 += yShear1; } break; #endif // SPLASH_CMYK } } } gfree(colorBuf); gfree(alphaBuf); return splashOk; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static void get_old_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct ip6t_entry *iter; unsigned int cpu, i; for_each_possible_cpu(cpu) { i = 0; xt_entry_foreach(iter, t->entries, t->size) { const struct xt_counters *tmp; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); ADD_COUNTER(counters[i], tmp->bcnt, tmp->pcnt); ++i; } cond_resched(); } } Commit Message: netfilter: add back stackpointer size checks The rationale for removing the check is only correct for rulesets generated by ip(6)tables. In iptables, a jump can only occur to a user-defined chain, i.e. because we size the stack based on number of user-defined chains we cannot exceed stack size. However, the underlying binary format has no such restriction, and the validation step only ensures that the jump target is a valid rule start point. IOW, its possible to build a rule blob that has no user-defined chains but does contain a jump. If this happens, no jump stack gets allocated and crash occurs because no jumpstack was allocated. Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset") Reported-by: [email protected] Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline) { vpx_codec_err_t res = VPX_CODEC_OK; unsigned int resolution_change = 0; unsigned int w, h; if (!ctx->fragments.enabled && (data == NULL && data_sz == 0)) { return 0; } /* Update the input fragment data */ if(update_fragments(ctx, data, data_sz, &res) <= 0) return res; /* Determine the stream parameters. Note that we rely on peek_si to * validate that we have a buffer that does not wrap around the top * of the heap. */ w = ctx->si.w; h = ctx->si.h; res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0], &ctx->si, ctx->decrypt_cb, ctx->decrypt_state); if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf) { /* the peek function returns an error for non keyframes, however for * this case, it is not an error */ res = VPX_CODEC_OK; } if(!ctx->decoder_init && !ctx->si.is_kf) res = VPX_CODEC_UNSUP_BITSTREAM; if ((ctx->si.h != h) || (ctx->si.w != w)) resolution_change = 1; /* Initialize the decoder instance on the first frame*/ if (!res && !ctx->decoder_init) { VP8D_CONFIG oxcf; oxcf.Width = ctx->si.w; oxcf.Height = ctx->si.h; oxcf.Version = 9; oxcf.postprocess = 0; oxcf.max_threads = ctx->cfg.threads; oxcf.error_concealment = (ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT); /* If postprocessing was enabled by the application and a * configuration has not been provided, default it. */ if (!ctx->postproc_cfg_set && (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) { ctx->postproc_cfg.post_proc_flag = VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE; ctx->postproc_cfg.deblocking_level = 4; ctx->postproc_cfg.noise_level = 0; } res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf); ctx->decoder_init = 1; } /* Set these even if already initialized. The caller may have changed the * decrypt config between frames. */ if (ctx->decoder_init) { ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb; ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state; } if (!res) { VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0]; if (resolution_change) { VP8_COMMON *const pc = & pbi->common; MACROBLOCKD *const xd = & pbi->mb; #if CONFIG_MULTITHREAD int i; #endif pc->Width = ctx->si.w; pc->Height = ctx->si.h; { int prev_mb_rows = pc->mb_rows; if (setjmp(pbi->common.error.jmp)) { pbi->common.error.setjmp = 0; vp8_clear_system_state(); /* same return value as used in vp8dx_receive_compressed_data */ return -1; } pbi->common.error.setjmp = 1; if (pc->Width <= 0) { pc->Width = w; vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, "Invalid frame width"); } if (pc->Height <= 0) { pc->Height = h; vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, "Invalid frame height"); } if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height)) vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate frame buffers"); xd->pre = pc->yv12_fb[pc->lst_fb_idx]; xd->dst = pc->yv12_fb[pc->new_fb_idx]; #if CONFIG_MULTITHREAD for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx]; vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd); } #endif vp8_build_block_doffsets(&pbi->mb); /* allocate memory for last frame MODE_INFO array */ #if CONFIG_ERROR_CONCEALMENT if (pbi->ec_enabled) { /* old prev_mip was released by vp8_de_alloc_frame_buffers() * called in vp8_alloc_frame_buffers() */ pc->prev_mip = vpx_calloc( (pc->mb_cols + 1) * (pc->mb_rows + 1), sizeof(MODE_INFO)); if (!pc->prev_mip) { vp8_de_alloc_frame_buffers(pc); vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate" "last frame MODE_INFO array"); } pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1; if (vp8_alloc_overlap_lists(pbi)) vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate overlap lists " "for error concealment"); } #endif #if CONFIG_MULTITHREAD if (pbi->b_multithreaded_rd) vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows); #else (void)prev_mb_rows; #endif } pbi->common.error.setjmp = 0; /* required to get past the first get_free_fb() call */ pbi->common.fb_idx_ref_cnt[0] = 0; } /* update the pbi fragment data */ pbi->fragments = ctx->fragments; ctx->user_priv = user_priv; if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline)) { res = update_error_state(ctx, &pbi->common.error); } /* get ready for the next series of fragments */ ctx->fragments.count = 0; } return res; } Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream Description from upstream: vp8: fix decoder crash with invalid leading keyframes decoding the same invalid keyframe twice would result in a crash as the second time through the decoder would be assumed to have been initialized as there was no resolution change. in this case the resolution was itself invalid (0x6), but vp8_peek_si() was only failing in the case of 0x0. invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by duplicating the first keyframe and additionally adds a valid one to ensure decoding can resume without error. Bug: 30593765 Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507 (cherry picked from commit fc0466b695dce03e10390101844caa374848d903) (cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136) CWE ID: CWE-20 Target: 1 Example 2: Code: ofputil_encode_ofp11_group_mod(enum ofp_version ofp_version, const struct ofputil_group_mod *gm) { struct ofpbuf *b; struct ofp11_group_mod *ogm; size_t start_ogm; struct ofputil_bucket *bucket; b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0); start_ogm = b->size; ofpbuf_put_zeros(b, sizeof *ogm); LIST_FOR_EACH (bucket, list_node, &gm->buckets) { ofputil_put_ofp11_bucket(bucket, b, ofp_version); } ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm); ogm->command = htons(gm->command); ogm->type = gm->type; ogm->group_id = htonl(gm->group_id); return b; } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <[email protected]> Reviewed-by: Yifeng Sun <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return "TRACE cannot be controlled by <Limit>, see TraceEnable"; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) <Limit>, else <LimitExcept> */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive excludes all methods", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive specifies methods already excluded", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; } Commit Message: core: Disallow Methods' registration at run time (.htaccess), they may be used only if registered at init time (httpd.conf). Calling ap_method_register() in children processes is not the right scope since it won't be shared for all requests. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) { Position start = startOfSelection.deepEquivalent().downstream(); if (isAtUnsplittableElement(start)) { RefPtr<Element> blockquote = createBlockElement(); insertNodeAt(blockquote, start); RefPtr<Element> placeholder = createBreakElement(document()); appendNode(placeholder, blockquote); setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional())); return; } RefPtr<Element> blockquoteForNextIndent; VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection); VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next()); m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent(); bool atEnd = false; Position end; while (endOfCurrentParagraph != endAfterSelection && !atEnd) { if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph) atEnd = true; rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); endOfCurrentParagraph = end; Position afterEnd = end.next(); Node* enclosingCell = enclosingNodeOfType(start, &isTableCell); VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent); if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell)) blockquoteForNextIndent = 0; if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument()) break; if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) { ASSERT_NOT_REACHED(); return; } endOfCurrentParagraph = endOfNextParagraph; } } Commit Message: Remove false assertion in ApplyBlockElementCommand::formatSelection() Note: This patch is preparation of fixing issue 294456. This patch removes false assertion in ApplyBlockElementCommand::formatSelection(), when contents of being indent is modified, e.g. mutation event, |endOfNextParagraph| can hold removed contents. BUG=294456 TEST=n/a [email protected] Review URL: https://codereview.chromium.org/25657004 git-svn-id: svn://svn.chromium.org/blink/trunk@158701 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: void MockPrinter::ScriptedPrint(int cookie, int expected_pages_count, bool has_selection, PrintMsg_PrintPages_Params* settings) { EXPECT_EQ(document_cookie_, cookie); settings->Reset(); settings->params.dpi = dpi_; settings->params.max_shrink = max_shrink_; settings->params.min_shrink = min_shrink_; settings->params.desired_dpi = desired_dpi_; settings->params.selection_only = selection_only_; settings->params.document_cookie = document_cookie_; settings->params.page_size = page_size_; settings->params.printable_size = printable_size_; settings->params.is_first_request = is_first_request_; settings->params.preview_request_id = preview_request_id_; settings->params.display_header_footer = display_header_footer_; settings->params.date = date_; settings->params.title = title_; settings->params.url = url_; printer_status_ = PRINTER_PRINTING; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void emitstring(JF, int opcode, const char *str) { emit(J, F, opcode); emitarg(J, F, addstring(J, F, str)); } Commit Message: Bug 700947: Add missing ENDTRY opcode in try/catch/finally byte code. In one of the code branches in handling exceptions in the catch block we forgot to call the ENDTRY opcode to pop the inner hidden try. This leads to an unbalanced exception stack which can cause a crash due to us jumping to a stack frame that has already been exited. CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 Target: 1 Example 2: Code: void ScreenLayoutObserver::CreateOrUpdateNotification( const base::string16& message, const base::string16& additional_message) { message_center::MessageCenter::Get()->RemoveNotification(kNotificationId, false /* by_user */); if (message.empty() && additional_message.empty()) return; if (Shell::Get() ->screen_orientation_controller() ->ignore_display_configuration_updates()) { return; } ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); std::unique_ptr<Notification> notification(new Notification( message_center::NOTIFICATION_TYPE_SIMPLE, kNotificationId, message, additional_message, bundle.GetImageNamed(IDR_AURA_NOTIFICATION_DISPLAY), base::string16(), // display_source GURL(), message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT, system_notifier::kNotifierDisplay), message_center::RichNotificationData(), new message_center::HandleNotificationClickedDelegate( base::Bind(&OpenSettingsFromNotification)))); ShellPort::Get()->RecordUserMetricsAction( UMA_STATUS_AREA_DISPLAY_NOTIFICATION_CREATED); message_center::MessageCenter::Get()->AddNotification( std::move(notification)); } Commit Message: Avoid Showing rotation change notification when source is accelerometer BUG=717252 TEST=Manually rotate device with accelerometer and observe there's no notification Review-Url: https://codereview.chromium.org/2853113005 Cr-Commit-Position: refs/heads/master@{#469058} CWE ID: CWE-17 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { q = (const uint8_t *)(const void *) ((const char *)(const void *)p + CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%d) id=%x type=%x offs=%x,%d\n", i, inp[i].pi_id, inp[i].pi_type, q - p, CDF_GETUINT32(p, (i << 1) + 1))); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %d\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %d, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); l = 4 + (uint32_t)CDF_ROUND(l, sizeof(l)); o += l >> 2; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); goto out; } } return 0; out: free(*info); return -1; } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20 Target: 1 Example 2: Code: ScriptPromise BluetoothRemoteGATTCharacteristic::writeValue( ScriptState* scriptState, const DOMArrayPiece& value) { if (!getGatt()->connected()) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected)); } if (!getGatt()->device()->isValidCharacteristic( m_characteristic->instance_id)) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic)); } if (value.byteLength() > 512) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidModificationError, "Value can't exceed 512 bytes.")); Vector<uint8_t> valueVector; valueVector.append(value.bytes(), value.byteLength()); ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); getGatt()->AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); service->RemoteCharacteristicWriteValue( m_characteristic->instance_id, valueVector, convertToBaseCallback(WTF::bind( &BluetoothRemoteGATTCharacteristic::WriteValueCallback, wrapPersistent(this), wrapPersistent(resolver), valueVector))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: zsetstrokecolor(i_ctx_t * i_ctx_p) { int code; code = zswapcolors(i_ctx_p); if (code < 0) /* Set up for the continuation procedure which will finish by restoring the fill colour space */ /* Make sure the exec stack has enough space */ check_estack(1); /* Now, the actual continuation routine */ push_op_estack(setstrokecolor_cont); code = zsetcolor(i_ctx_p); if (code >= 0) if (code >= 0) return o_push_estack; return code; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: Fix iommu map/unmap to handle memory slot moves The iommu integration into memory slots expects memory slots to be added or removed and doesn't handle the move case. We can unmap slots from the iommu after we mark them invalid and map them before installing the final memslot array. Also re-order the kmemdup vs map so we don't leave iommu mappings if we get ENOMEM. Reviewed-by: Gleb Natapov <[email protected]> Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static int x25_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct sock *newsk; struct sk_buff *skb; int rc = -EINVAL; if (!sk) goto out; rc = -EOPNOTSUPP; if (sk->sk_type != SOCK_SEQPACKET) goto out; lock_sock(sk); rc = -EINVAL; if (sk->sk_state != TCP_LISTEN) goto out2; rc = x25_wait_for_data(sk, sk->sk_rcvtimeo); if (rc) goto out2; skb = skb_dequeue(&sk->sk_receive_queue); rc = -EINVAL; if (!skb->sk) goto out2; newsk = skb->sk; sock_graft(newsk, newsock); /* Now attach up the new socket */ skb->sk = NULL; kfree_skb(skb); sk->sk_ack_backlog--; newsock->state = SS_CONNECTED; rc = 0; out2: release_sock(sk); out: return rc; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int vm_munmap(unsigned long start, size_t len) { return __vm_munmap(start, len, false); } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); image2 = (Image *) NULL; status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ quantum_info=(QuantumInfo *) NULL; clone_info=(ImageInfo *) NULL; if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image=ReadMATImageV4(image_info,image,exception); if (image == NULL) { if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); return((Image *) NULL); } goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else { MATLAB_KO: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; if (filepos != (unsigned int) filepos) break; if(SeekBlob(image,filepos,SEEK_SET) != filepos) break; /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) goto MATLAB_KO; filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4; if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); clone_info=CloneImageInfo(image_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if (MATLAB_HDR.DataType != miMATRIX) { clone_info=DestroyImageInfo(clone_info); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (image2 != image) DeleteImageFromList(&image2); #endif continue; /* skip another objects. */ } MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } Frames = ReadBlobXXXLong(image2); if (Frames == 0) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit"); } break; default: if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ { if ((image2 != (Image*) NULL) && (image2 != image)) { CloseBlob(image2); DeleteImageFromList(&image2); } if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); } switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (((size_t) size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); /* data size */ if (ReadBlob(image2, 4, (unsigned char *) &size) != 4) goto MATLAB_KO; NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); } if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; image->colors = GetQuantumRange(image->depth); if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image,exception); quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) { if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY, CellType,ldblk,BImgBuff,&quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: if (i != (long) MATLAB_HDR.SizeY) goto END_OF_READING; /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); if (EOFBlob(image) != MagickFalse) break; InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); if (EOFBlob(image) != MagickFalse) break; InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; rotated_image->colors = image->colors; DestroyBlob(rotated_image); rotated_image->blob=ReferenceBlob(image->blob); AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } if (EOFBlob(image) != MagickFalse) break; /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; if(!EOFBlob(image) && TellBlob(image)<filepos) goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } if (clone_info) clone_info=DestroyImageInfo(clone_info); } END_OF_READING: RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; if (tmp == image2) image2=(Image *) NULL; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (image == (Image *) NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader") return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1554 CWE ID: CWE-416 Target: 1 Example 2: Code: static void sock_rmem_free(struct sk_buff *skb) { struct sock *sk = skb->sk; atomic_sub(skb->truesize, &sk->sk_rmem_alloc); } Commit Message: tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class"); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags = mrb_obj_ptr(self)->flags; return clone; } Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036 Copying all flags from the original object may overwrite the clone's flags e.g. the embedded flag. CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) { ALOGE("input buffer too large (%d).", inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } if(((inHeader->nFilledLen / kMSGSMFrameSize) * kMSGSMFrameSize) != inHeader->nFilledLen) { ALOGE("input buffer not multiple of %d (%d).", kMSGSMFrameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset; int n = mSignalledError ? 0 : DecodeGSM(mGsm, reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen); outHeader->nTimeStamp = inHeader->nTimeStamp; outHeader->nOffset = 0; outHeader->nFilledLen = n * sizeof(int16_t); outHeader->nFlags = 0; inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec Bug: 27793163 Bug: 27793367 Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c CWE ID: CWE-119 Target: 1 Example 2: Code: static int aesni_cbc_hmac_sha256_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_AES_HMAC_SHA256 *key = data(ctx); switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg > (int)sizeof(hmac_key)) { SHA256_Init(&key->head); SHA256_Update(&key->head, ptr, arg); SHA256_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ SHA256_Init(&key->head); SHA256_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ SHA256_Init(&key->tail); SHA256_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len = p[arg - 2] << 8 | p[arg - 1]; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; if (ctx->encrypt) { key->payload_length = len; if ((key->aux.tls_ver = p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) { len -= AES_BLOCK_SIZE; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->md = key->head; SHA256_Update(&key->md, p, arg); return (int)(((len + SHA256_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE) - len); } else { memcpy(key->aux.tls_aad, ptr, arg); key->payload_length = arg; return SHA256_DIGEST_LENGTH; } } # if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE: return (int)(5 + 16 + ((arg + 32 + 16) & -16)); case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; unsigned int n4x = 1, x4; unsigned int frag, last, packlen, inp_len; if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM)) return -1; inp_len = param->inp[11] << 8 | param->inp[12]; if (ctx->encrypt) { if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION) return -1; if (inp_len) { if (inp_len < 4096) return 0; /* too short */ if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5)) n4x = 2; /* AVX2 */ } else if ((n4x = param->interleave / 4) && n4x <= 2) inp_len = param->len; else return -1; key->md = key->head; SHA256_Update(&key->md, param->inp, 13); x4 = 4 * n4x; n4x += 1; frag = inp_len >> n4x; last = inp_len + frag - (frag << n4x); if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) { frag++; last -= x4 - 1; } packlen = 5 + 16 + ((frag + 32 + 16) & -16); packlen = (packlen << n4x) - packlen; packlen += 5 + 16 + ((last + 32 + 16) & -16); param->interleave = x4; return (int)packlen; } else return -1; /* not yet */ } case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; return (int)tls1_1_multi_block_encrypt(key, param->out, param->inp, param->len, param->interleave / 4); } case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT: # endif default: return -1; } } Commit Message: CWE ID: CWE-310 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, unsigned long arg) { struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev, *cur; int ret; struct uffdio_range uffdio_unregister; unsigned long new_flags; bool found; unsigned long start, end, vma_end; const void __user *buf = (void __user *)arg; ret = -EFAULT; if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister))) goto out; ret = validate_range(mm, uffdio_unregister.start, uffdio_unregister.len); if (ret) goto out; start = uffdio_unregister.start; end = start + uffdio_unregister.len; ret = -ENOMEM; if (!mmget_not_zero(mm)) goto out; down_write(&mm->mmap_sem); vma = find_vma_prev(mm, start, &prev); if (!vma) goto out_unlock; /* check that there's at least one vma in the range */ ret = -EINVAL; if (vma->vm_start >= end) goto out_unlock; /* * If the first vma contains huge pages, make sure start address * is aligned to huge page size. */ if (is_vm_hugetlb_page(vma)) { unsigned long vma_hpagesize = vma_kernel_pagesize(vma); if (start & (vma_hpagesize - 1)) goto out_unlock; } /* * Search for not compatible vmas. */ found = false; ret = -EINVAL; for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { cond_resched(); BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); /* * Check not compatible vmas, not strictly required * here as not compatible vmas cannot have an * userfaultfd_ctx registered on them, but this * provides for more strict behavior to notice * unregistration errors. */ if (!vma_can_userfault(cur)) goto out_unlock; found = true; } BUG_ON(!found); if (vma->vm_start < start) prev = vma; ret = 0; do { cond_resched(); BUG_ON(!vma_can_userfault(vma)); /* * Nothing to do: this vma is already registered into this * userfaultfd and with the right tracking mode too. */ if (!vma->vm_userfaultfd_ctx.ctx) goto skip; WARN_ON(!(vma->vm_flags & VM_MAYWRITE)); if (vma->vm_start > start) start = vma->vm_start; vma_end = min(end, vma->vm_end); if (userfaultfd_missing(vma)) { /* * Wake any concurrent pending userfault while * we unregister, so they will not hang * permanently and it avoids userland to call * UFFDIO_WAKE explicitly. */ struct userfaultfd_wake_range range; range.start = start; range.len = vma_end - start; wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range); } new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); prev = vma_merge(mm, prev, start, vma_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), NULL_VM_UFFD_CTX); if (prev) { vma = prev; goto next; } if (vma->vm_start < start) { ret = split_vma(mm, vma, start, 1); if (ret) break; } if (vma->vm_end > end) { ret = split_vma(mm, vma, end, 0); if (ret) break; } next: /* * In the vma_merge() successful mprotect-like case 8: * the next vma was merged into the current one and * the current one has not been updated yet. */ vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; skip: prev = vma; start = vma->vm_end; vma = vma->vm_next; } while (vma && vma->vm_start < end); out_unlock: up_write(&mm->mmap_sem); mmput(mm); out: return ret; } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); int is_udp4; bool slow; if (addr_len) *addr_len = sizeof(struct sockaddr_in6); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; is_udp4 = (skb->protocol == htons(ETH_P_IP)); /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udpv6_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) { if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); } sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (msg->msg_name) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *) msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = udp_hdr(skb)->source; sin6->sin6_flowinfo = 0; if (is_udp4) { ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin6->sin6_addr); sin6->sin6_scope_id = 0; } else { sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } } if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); } err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { if (is_udp4) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } else { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_rgn_t *rgn = &ms->parms.rgn; uint_fast8_t tmp; if (cstate->numcomps <= 256) { if (jpc_getuint8(in, &tmp)) { return -1; } rgn->compno = tmp; } else { if (jpc_getuint16(in, &rgn->compno)) { return -1; } } if (jpc_getuint8(in, &rgn->roisty) || jpc_getuint8(in, &rgn->roishift)) { return -1; } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int mk_vhost_fdt_open(int id, unsigned int hash, struct session_request *sr) { int i; int fd; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return open(sr->real_path.data, sr->file_info.flags_read_only); } ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return open(sr->real_path.data, sr->file_info.flags_read_only); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and return the shared FD */ hc->readers++; return hc->fd; } /* * Get here means that no entry exists in the hash table for the * requested file descriptor and hash, we must try to open the file * and register the entry in the table. */ fd = open(sr->real_path.data, sr->file_info.flags_read_only); if (fd == -1) { return -1; } /* If chains are full, just return the new FD, bad luck... */ if (ht->av_slots <= 0) { return fd; } /* Register the new entry in an available slot */ for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) { hc = &ht->chain[i]; if (hc->fd == -1) { hc->fd = fd; hc->hash = hash; hc->readers++; ht->av_slots--; sr->vhost_fdt_id = id; sr->vhost_fdt_hash = hash; return fd; } } return -1; } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <[email protected]> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct device *dev = &intf->dev; struct usb_device *usbdev = interface_to_usbdev(intf); struct net_device *netdev; struct catc *catc; u8 broadcast[ETH_ALEN]; int i, pktsz, ret; if (usb_set_interface(usbdev, intf->altsetting->desc.bInterfaceNumber, 1)) { dev_err(dev, "Can't set altsetting 1.\n"); return -EIO; } netdev = alloc_etherdev(sizeof(struct catc)); if (!netdev) return -ENOMEM; catc = netdev_priv(netdev); netdev->netdev_ops = &catc_netdev_ops; netdev->watchdog_timeo = TX_TIMEOUT; netdev->ethtool_ops = &ops; catc->usbdev = usbdev; catc->netdev = netdev; spin_lock_init(&catc->tx_lock); spin_lock_init(&catc->ctrl_lock); init_timer(&catc->timer); catc->timer.data = (long) catc; catc->timer.function = catc_stats_timer; catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL); catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL); if ((!catc->ctrl_urb) || (!catc->tx_urb) || (!catc->rx_urb) || (!catc->irq_urb)) { dev_err(&intf->dev, "No free urbs available.\n"); ret = -ENOMEM; goto fail_free; } /* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */ if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 && le16_to_cpu(usbdev->descriptor.idProduct) == 0xa && le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) { dev_dbg(dev, "Testing for f5u011\n"); catc->is_f5u011 = 1; atomic_set(&catc->recq_sz, 0); pktsz = RX_PKT_SZ; } else { pktsz = RX_MAX_BURST * (PKT_SZ + 2); } usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0), NULL, NULL, 0, catc_ctrl_done, catc); usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1), NULL, 0, catc_tx_done, catc); usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1), catc->rx_buf, pktsz, catc_rx_done, catc); usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2), catc->irq_buf, 2, catc_irq_done, catc, 1); if (!catc->is_f5u011) { dev_dbg(dev, "Checking memory size\n"); i = 0x12345678; catc_write_mem(catc, 0x7a80, &i, 4); i = 0x87654321; catc_write_mem(catc, 0xfa80, &i, 4); catc_read_mem(catc, 0x7a80, &i, 4); switch (i) { case 0x12345678: catc_set_reg(catc, TxBufCount, 8); catc_set_reg(catc, RxBufCount, 32); dev_dbg(dev, "64k Memory\n"); break; default: dev_warn(&intf->dev, "Couldn't detect memory size, assuming 32k\n"); case 0x87654321: catc_set_reg(catc, TxBufCount, 4); catc_set_reg(catc, RxBufCount, 16); dev_dbg(dev, "32k Memory\n"); break; } dev_dbg(dev, "Getting MAC from SEEROM.\n"); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, "Setting MAC into registers.\n"); for (i = 0; i < 6; i++) catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]); dev_dbg(dev, "Filling the multicast list.\n"); eth_broadcast_addr(broadcast); catc_multicast(broadcast, catc->multicast); catc_multicast(netdev->dev_addr, catc->multicast); catc_write_mem(catc, 0xfa80, catc->multicast, 64); dev_dbg(dev, "Clearing error counters.\n"); for (i = 0; i < 8; i++) catc_set_reg(catc, EthStats + i, 0); catc->last_stats = jiffies; dev_dbg(dev, "Enabling.\n"); catc_set_reg(catc, MaxBurst, RX_MAX_BURST); catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits); catc_set_reg(catc, LEDCtrl, LEDLink); catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast); } else { dev_dbg(dev, "Performing reset\n"); catc_reset(catc); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, "Setting RX Mode\n"); catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast; catc->rxmode[1] = 0; f5u011_rxmode(catc, catc->rxmode); } dev_dbg(dev, "Init done.\n"); printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n", netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate", usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr); usb_set_intfdata(intf, catc); SET_NETDEV_DEV(netdev, &intf->dev); ret = register_netdev(netdev); if (ret) goto fail_clear_intfdata; return 0; fail_clear_intfdata: usb_set_intfdata(intf, NULL); fail_free: usb_free_urb(catc->ctrl_urb); usb_free_urb(catc->tx_urb); usb_free_urb(catc->rx_urb); usb_free_urb(catc->irq_urb); free_netdev(netdev); return ret; } Commit Message: catc: Use heap buffer for memory size test Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void VirtualKeyboardController::ToggleIgnoreExternalKeyboard() { ignore_external_keyboard_ = !ignore_external_keyboard_; UpdateKeyboardEnabled(); } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: free_hash_entry(struct ftrace_hash *hash, struct ftrace_func_entry *entry) { hlist_del(&entry->hlist); kfree(entry); hash->count--; } Commit Message: tracing: Fix possible NULL pointer dereferences Currently set_ftrace_pid and set_graph_function files use seq_lseek for their fops. However seq_open() is called only for FMODE_READ in the fops->open() so that if an user tries to seek one of those file when she open it for writing, it sees NULL seq_file and then panic. It can be easily reproduced with following command: $ cd /sys/kernel/debug/tracing $ echo 1234 | sudo tee -a set_ftrace_pid In this example, GNU coreutils' tee opens the file with fopen(, "a") and then the fopen() internally calls lseek(). Link: http://lkml.kernel.org/r/[email protected] Cc: Frederic Weisbecker <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Namhyung Kim <[email protected]> Cc: [email protected] Signed-off-by: Namhyung Kim <[email protected]> Signed-off-by: Steven Rostedt <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame, const GURL& url, GURL* new_url) { if (url.SchemeIs(chrome::kExtensionScheme) && !ExtensionResourceRequestPolicy::CanRequestResource( url, GURL(frame->document().url()), extension_dispatcher_->extensions())) { *new_url = GURL("chrome-extension://invalid/"); return true; } return false; } Commit Message: Do not require DevTools extension resources to be white-listed in manifest. Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is (a) trusted and (b) picky on the frames it loads. This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check. BUG=none TEST=DevToolsExtensionTest.* Review URL: https://chromiumcodereview.appspot.com/9663076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void CNB::SetupCSO(virtio_net_hdr_basic *VirtioHeader, ULONG L4HeaderOffset) const { u16 PriorityHdrLen = m_ParentNBL->TCI() ? ETH_PRIORITY_HEADER_SIZE : 0; VirtioHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VirtioHeader->csum_start = static_cast<u16>(L4HeaderOffset) + PriorityHdrLen; VirtioHeader->csum_offset = m_ParentNBL->IsTcpCSO() ? TCP_CHECKSUM_OFFSET : UDP_CHECKSUM_OFFSET; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ifb_setup(struct net_device *dev) { /* Initialize the device structure. */ dev->destructor = free_netdev; dev->netdev_ops = &ifb_netdev_ops; /* Fill in device structure with ethernet-generic values. */ ether_setup(dev); dev->tx_queue_len = TX_Q_LIMIT; dev->features |= IFB_FEATURES; dev->vlan_features |= IFB_FEATURES; dev->flags |= IFF_NOARP; dev->flags &= ~IFF_MULTICAST; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; random_ether_addr(dev->dev_addr); } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_host_hdr(hp); if (retval != 0) { WSP(sp, SLT_Error, "Duplicated Host header"); return (retval); } return (retval); } Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that. CWE ID: Target: 1 Example 2: Code: static bool ndp_msg_check_opts(struct ndp_msg *msg) { unsigned char *ptr = ndp_msg_payload_opts(msg); size_t len = ndp_msg_payload_opts_len(msg); struct ndp_msg_opt_type_info *info; while (len > 0) { uint8_t cur_opt_raw_type = ptr[0]; unsigned int cur_opt_len = ptr[1] << 3; /* convert to bytes */ if (!cur_opt_len) return false; if (len < cur_opt_len) break; info = ndp_msg_opt_type_info_by_raw_type(cur_opt_raw_type); if (info) { if (cur_opt_len < info->raw_struct_size || (info->check_valid && !info->check_valid(ptr))) ptr[0] = __INVALID_OPT_TYPE_MAGIC; } ptr += cur_opt_len; len -= cur_opt_len; } return true; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static scoped_refptr<ScrollPaintPropertyNode> CreateScroll( scoped_refptr<const ScrollPaintPropertyNode> parent, const ScrollPaintPropertyNode::State& state_arg, MainThreadScrollingReasons main_thread_scrolling_reasons = MainThreadScrollingReason::kNotScrollingOnMain, CompositorElementId scroll_element_id = CompositorElementId()) { ScrollPaintPropertyNode::State state = state_arg; state.main_thread_scrolling_reasons = main_thread_scrolling_reasons; state.compositor_element_id = scroll_element_id; return ScrollPaintPropertyNode::Create(parent, std::move(state)); } 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: Target: 1 Example 2: Code: void Browser::OpenURLOffTheRecord(Profile* profile, const GURL& url) { Browser* browser = GetOrCreateTabbedBrowser( profile->GetOffTheRecordProfile()); browser->AddSelectedTabWithURL(url, PageTransition::LINK); browser->window()->Show(); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else Commit Message: CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE omx_video::allocate_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; DEBUG_PRINT_HIGH("allocate_input_buffer()::"); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual); m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; (*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i]; #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); } (*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer; DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer); BITMASK_SET(&m_inp_bm_count,i); if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call" "for index [%d]", i); eRet = OMX_ErrorInsufficientResources; } return eRet; } Commit Message: DO NOT MERGE Fix wrong nAllocLen Set nAllocLen to the size of the opaque handle itself. Bug: 28816964 Bug: 28816827 Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099 CWE ID: CWE-119 Target: 1 Example 2: Code: static double get_final_sample_using_nc_tbl(struct iw_context *ctx, iw_tmpsample samp_lin) { unsigned int x; unsigned int d; x = 127; d = 64; while(1) { if(x>254 || ctx->nearest_color_table[x] > samp_lin) x -= d; else x += d; if(d==1) { if(x>254 || ctx->nearest_color_table[x] > samp_lin) return (double)(x); else return (double)(x+1); } d = d/2; } } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_scale_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PluginModule::InitAsProxiedNaCl( scoped_ptr<PluginDelegate::OutOfProcessProxy> out_of_process_proxy, PP_Instance instance) { nacl_ipc_proxy_ = true; InitAsProxied(out_of_process_proxy.release()); out_of_process_proxy_->AddInstance(instance); PluginInstance* plugin_instance = host_globals->GetInstance(instance); if (!plugin_instance) return; plugin_instance->ResetAsProxied(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER); if (!msr) return; /* * Force kernel_gs_base reloading before EFER changes, as control * of this msr depends on is_long_mode(). */ vmx_load_host_state(to_vmx(vcpu)); vcpu->arch.efer = efer; if (efer & EFER_LMA) { vmcs_write32(VM_ENTRY_CONTROLS, vmcs_read32(VM_ENTRY_CONTROLS) | VM_ENTRY_IA32E_MODE); msr->data = efer; } else { vmcs_write32(VM_ENTRY_CONTROLS, vmcs_read32(VM_ENTRY_CONTROLS) & ~VM_ENTRY_IA32E_MODE); msr->data = efer & ~EFER_LME; } setup_msrs(vmx); } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0) { double gray, err; if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); /* Image now has RGB channels... */ # if DIGITIZE { PNG_CONST png_modifier *pm = display->pm; const unsigned int sample_depth = that->sample_depth; const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 : sample_depth); const unsigned int gamma_depth = (sample_depth == 16 ? 16 : (pm->assume_16_bit_calculations ? PNG_MAX_GAMMA_8 : sample_depth)); int isgray; double r, g, b; double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi; /* Do this using interval arithmetic, otherwise it is too difficult to * handle the errors correctly. * * To handle the gamma correction work out the upper and lower bounds * of the digitized value. Assume rounding here - normally the values * will be identical after this operation if there is only one * transform, feel free to delete the png_error checks on this below in * the future (this is just me trying to ensure it works!) */ r = rlo = rhi = that->redf; rlo -= that->rede; rlo = digitize(rlo, calc_depth, 1/*round*/); rhi += that->rede; rhi = digitize(rhi, calc_depth, 1/*round*/); g = glo = ghi = that->greenf; glo -= that->greene; glo = digitize(glo, calc_depth, 1/*round*/); ghi += that->greene; ghi = digitize(ghi, calc_depth, 1/*round*/); b = blo = bhi = that->bluef; blo -= that->bluee; blo = digitize(blo, calc_depth, 1/*round*/); bhi += that->greene; bhi = digitize(bhi, calc_depth, 1/*round*/); isgray = r==g && g==b; if (data.gamma != 1) { PNG_CONST double power = 1/data.gamma; PNG_CONST double abse = calc_depth == 16 ? .5/65535 : .5/255; /* 'abse' is the absolute error permitted in linear calculations. It * is used here to capture the error permitted in the handling * (undoing) of the gamma encoding. Once again digitization occurs * to handle the upper and lower bounds of the values. This is * where the real errors are introduced. */ r = pow(r, power); rlo = digitize(pow(rlo, power)-abse, calc_depth, 1); rhi = digitize(pow(rhi, power)+abse, calc_depth, 1); g = pow(g, power); glo = digitize(pow(glo, power)-abse, calc_depth, 1); ghi = digitize(pow(ghi, power)+abse, calc_depth, 1); b = pow(b, power); blo = digitize(pow(blo, power)-abse, calc_depth, 1); bhi = digitize(pow(bhi, power)+abse, calc_depth, 1); } /* Now calculate the actual gray values. Although the error in the * coefficients depends on whether they were specified on the command * line (in which case truncation to 15 bits happened) or not (rounding * was used) the maxium error in an individual coefficient is always * 1/32768, because even in the rounding case the requirement that * coefficients add up to 32768 can cause a larger rounding error. * * The only time when rounding doesn't occur in 1.5.5 and later is when * the non-gamma code path is used for less than 16 bit data. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; { PNG_CONST int do_round = data.gamma != 1 || calc_depth == 16; PNG_CONST double ce = 1. / 32768; graylo = digitize(rlo * (data.red_coefficient-ce) + glo * (data.green_coefficient-ce) + blo * (data.blue_coefficient-ce), gamma_depth, do_round); if (graylo <= 0) graylo = 0; grayhi = digitize(rhi * (data.red_coefficient+ce) + ghi * (data.green_coefficient+ce) + bhi * (data.blue_coefficient+ce), gamma_depth, do_round); if (grayhi >= 1) grayhi = 1; } /* And invert the gamma. */ if (data.gamma != 1) { PNG_CONST double power = data.gamma; gray = pow(gray, power); graylo = digitize(pow(graylo, power), sample_depth, 1); grayhi = digitize(pow(grayhi, power), sample_depth, 1); } /* Now the error can be calculated. * * If r==g==b because there is no overall gamma correction libpng * currently preserves the original value. */ if (isgray) err = (that->rede + that->greene + that->bluee)/3; else { err = fabs(grayhi-gray); if (fabs(gray - graylo) > err) err = fabs(graylo-gray); /* Check that this worked: */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # else /* DIGITIZE */ { double r = that->redf; double re = that->rede; double g = that->greenf; double ge = that->greene; double b = that->bluef; double be = that->bluee; /* The true gray case involves no math. */ if (r == g && r == b) { gray = r; err = re; if (err < ge) err = ge; if (err < be) err = be; } else if (data.gamma == 1) { /* There is no need to do the conversions to and from linear space, * so the calculation should be a lot more accurate. There is a * built in 1/32768 error in the coefficients because they only have * 15 bits and are adjusted to make sure they add up to 32768, so * the result may have an additional error up to 1/32768. (Note * that adding the 1/32768 here avoids needing to increase the * global error limits to take this into account.) */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient; err = re * data.red_coefficient + ge * data.green_coefficient + be * data.blue_coefficient + 1./32768 + gray * 5 * DBL_EPSILON; } else { /* The calculation happens in linear space, and this produces much * wider errors in the encoded space. These are handled here by * factoring the errors in to the calculation. There are two table * lookups in the calculation and each introduces a quantization * error defined by the table size. */ PNG_CONST png_modifier *pm = display->pm; double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255); double out_qe = (that->sample_depth > 8 ? .5/65535 : (pm->assume_16_bit_calculations ? .5/(1<<PNG_MAX_GAMMA_8) : .5/255)); double rhi, ghi, bhi, grayhi; double g1 = 1/data.gamma; rhi = r + re + in_qe; if (rhi > 1) rhi = 1; r -= re + in_qe; if (r < 0) r = 0; ghi = g + ge + in_qe; if (ghi > 1) ghi = 1; g -= ge + in_qe; if (g < 0) g = 0; bhi = b + be + in_qe; if (bhi > 1) bhi = 1; b -= be + in_qe; if (b < 0) b = 0; r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON); g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON); b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON); /* Work out the lower and upper bounds for the gray value in the * encoded space, then work out an average and error. Remove the * previously added input quantization error at this point. */ gray = r * data.red_coefficient + g * data.green_coefficient + b * data.blue_coefficient - 1./32768 - out_qe; if (gray <= 0) gray = 0; else { gray *= (1 - 6 * DBL_EPSILON); gray = pow(gray, data.gamma) * (1-DBL_EPSILON); } grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient + bhi * data.blue_coefficient + 1./32768 + out_qe; grayhi *= (1 + 6 * DBL_EPSILON); if (grayhi >= 1) grayhi = 1; else grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON); err = (grayhi - gray) / 2; gray = (grayhi + gray) / 2; if (err <= in_qe) err = gray * DBL_EPSILON; else err -= in_qe; /* Validate that the error is within limits (this has caused * problems before, it's much easier to detect them here.) */ if (err > pm->limit) { size_t pos = 0; char buffer[128]; pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error "); pos = safecatd(buffer, sizeof buffer, pos, err, 6); pos = safecat(buffer, sizeof buffer, pos, " exceeds limit "); pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6); png_error(pp, buffer); } } } # endif /* !DIGITIZE */ that->bluef = that->greenf = that->redf = gray; that->bluee = that->greene = that->rede = err; /* The sBIT is the minium of the three colour channel sBITs. */ if (that->red_sBIT > that->green_sBIT) that->red_sBIT = that->green_sBIT; if (that->red_sBIT > that->blue_sBIT) that->red_sBIT = that->blue_sBIT; that->blue_sBIT = that->green_sBIT = that->red_sBIT; /* And remove the colour bit in the type: */ if (that->colour_type == PNG_COLOR_TYPE_RGB) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int udf_readdir(struct file *file, struct dir_context *ctx) { struct inode *dir = file_inode(file); struct udf_inode_info *iinfo = UDF_I(dir); struct udf_fileident_bh fibh = { .sbh = NULL, .ebh = NULL}; struct fileIdentDesc *fi = NULL; struct fileIdentDesc cfi; int block, iblock; loff_t nf_pos; int flen; unsigned char *fname = NULL; unsigned char *nameptr; uint16_t liu; uint8_t lfi; loff_t size = udf_ext0_offset(dir) + dir->i_size; struct buffer_head *tmp, *bha[16]; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; int i, num, ret = 0; struct extent_position epos = { NULL, 0, {0, 0} }; if (ctx->pos == 0) { if (!dir_emit_dot(file, ctx)) return 0; ctx->pos = 1; } nf_pos = (ctx->pos - 1) << 2; if (nf_pos >= size) goto out; fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) { ret = -ENOMEM; goto out; } if (nf_pos == 0) nf_pos = udf_ext0_offset(dir); fibh.soffset = fibh.eoffset = nf_pos & (dir->i_sb->s_blocksize - 1); if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, nf_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) { ret = -ENOENT; goto out; } block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else { offset = 0; } if (!(fibh.sbh = fibh.ebh = udf_tread(dir->i_sb, block))) { ret = -EIO; goto out; } if (!(offset & ((16 >> (dir->i_sb->s_blocksize_bits - 9)) - 1))) { i = 16 >> (dir->i_sb->s_blocksize_bits - 9); if (i + offset > (elen >> dir->i_sb->s_blocksize_bits)) i = (elen >> dir->i_sb->s_blocksize_bits) - offset; for (num = 0; i > 0; i--) { block = udf_get_lb_pblock(dir->i_sb, &eloc, offset + i); tmp = udf_tgetblk(dir->i_sb, block); if (tmp && !buffer_uptodate(tmp) && !buffer_locked(tmp)) bha[num++] = tmp; else brelse(tmp); } if (num) { ll_rw_block(READA, num, bha); for (i = 0; i < num; i++) brelse(bha[i]); } } } while (nf_pos < size) { struct kernel_lb_addr tloc; ctx->pos = (nf_pos >> 2) + 1; fi = udf_fileident_read(dir, &nf_pos, &fibh, &cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out; liu = le16_to_cpu(cfi.lengthOfImpUse); lfi = cfi.lengthFileIdent; if (fibh.sbh == fibh.ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh.soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) { nameptr = (char *)(fibh.ebh->b_data + poffset - lfi); } else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh.ebh->b_data, poffset); } } if ((cfi.fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi.fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if (cfi.fileCharacteristics & FID_FILE_CHAR_PARENT) { if (!dir_emit_dotdot(file, ctx)) goto out; continue; } flen = udf_get_filename(dir->i_sb, nameptr, fname, lfi); if (!flen) continue; tloc = lelb_to_cpu(cfi.icb.extLocation); iblock = udf_get_lb_pblock(dir->i_sb, &tloc, 0); if (!dir_emit(ctx, fname, flen, iblock, DT_UNKNOWN)) goto out; } /* end while */ ctx->pos = (nf_pos >> 2) + 1; out: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); kfree(fname); return ret; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17 Target: 1 Example 2: Code: static int raw_v4_seq_open(struct inode *inode, struct file *file) { return raw_seq_open(inode, file, &raw_v4_hashinfo, &raw_seq_ops); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void bt_for_each(struct blk_mq_hw_ctx *hctx, struct blk_mq_bitmap_tags *bt, unsigned int off, busy_iter_fn *fn, void *data, bool reserved) { struct request *rq; int bit, i; for (i = 0; i < bt->map_nr; i++) { struct blk_align_bitmap *bm = &bt->map[i]; for (bit = find_first_bit(&bm->word, bm->depth); bit < bm->depth; bit = find_next_bit(&bm->word, bm->depth, bit + 1)) { rq = blk_mq_tag_to_rq(hctx->tags, off + bit); if (rq->q == hctx->queue) fn(hctx, rq, data, reserved); } off += (1 << bt->bits_per_word); } } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
1