instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> methodCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestMediaQueryListListener.method");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestMediaQueryListListener* imp = V8TestMediaQueryListListener::toNative(args.Holder());
EXCEPTION_BLOCK(RefPtr<MediaQueryListListener>, listener, MediaQueryListListener::create(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->method(listener);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> methodCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestMediaQueryListListener.method");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestMediaQueryListListener* imp = V8TestMediaQueryListListener::toNative(args.Holder());
EXCEPTION_BLOCK(RefPtr<MediaQueryListListener>, listener, MediaQueryListListener::create(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->method(listener);
return v8::Handle<v8::Value>();
}
| 171,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int readpng2_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
readpng2_error_handler, readpng2_warning_handler);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 4; /* out of memory */
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters) */
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or exit immediately, so here we are: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
/* prepare the reader to ignore all recognized chunks whose data won't be
* used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT,
* IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */
{
/* These byte strings were copied from png.h. If a future version
* of readpng2.c recognizes more chunks, add them to this list.
*/
static PNG_CONST png_byte chunks_to_process[] = {
98, 75, 71, 68, '\0', /* bKGD */
103, 65, 77, 65, '\0', /* gAMA */
115, 82, 71, 66, '\0', /* sRGB */
};
/* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */
png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */,
NULL, -1);
/* But do not ignore chunks in the "chunks_to_process" list */
png_set_keep_unknown_chunks(png_ptr,
0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process,
sizeof(chunks_to_process)/5);
}
#endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */
/* instead of doing png_init_io() here, now we set up our callback
* functions for progressive decoding */
png_set_progressive_read_fn(png_ptr, mainprog_ptr,
readpng2_info_callback, readpng2_row_callback, readpng2_end_callback);
/* make sure we save our pointers for use in readpng2_decode_data() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* and that's all there is to initialization */
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int readpng2_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), mainprog_ptr,
readpng2_error_handler, readpng2_warning_handler);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 4; /* out of memory */
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters) */
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or exit immediately, so here we are: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
/* prepare the reader to ignore all recognized chunks whose data won't be
* used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT,
* IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */
{
/* These byte strings were copied from png.h. If a future version
* of readpng2.c recognizes more chunks, add them to this list.
*/
static PNG_CONST png_byte chunks_to_process[] = {
98, 75, 71, 68, '\0', /* bKGD */
103, 65, 77, 65, '\0', /* gAMA */
115, 82, 71, 66, '\0', /* sRGB */
};
/* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */
png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */,
NULL, -1);
/* But do not ignore chunks in the "chunks_to_process" list */
png_set_keep_unknown_chunks(png_ptr,
0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process,
sizeof(chunks_to_process)/5);
}
#endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */
/* instead of doing png_init_io() here, now we set up our callback
* functions for progressive decoding */
png_set_progressive_read_fn(png_ptr, mainprog_ptr,
readpng2_info_callback, readpng2_row_callback, readpng2_end_callback);
/* make sure we save our pointers for use in readpng2_decode_data() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* and that's all there is to initialization */
return 0;
}
| 173,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
Commit Message: ALSA: usb-audio: Kill stray URB at exiting
USB-audio driver may leave a stray URB for the mixer interrupt when it
exits by some error during probe. This leads to a use-after-free
error as spotted by syzkaller like:
==================================================================
BUG: KASAN: use-after-free in snd_usb_mixer_interrupt+0x604/0x6f0
Call Trace:
<IRQ>
__dump_stack lib/dump_stack.c:16
dump_stack+0x292/0x395 lib/dump_stack.c:52
print_address_description+0x78/0x280 mm/kasan/report.c:252
kasan_report_error mm/kasan/report.c:351
kasan_report+0x23d/0x350 mm/kasan/report.c:409
__asan_report_load8_noabort+0x19/0x20 mm/kasan/report.c:430
snd_usb_mixer_interrupt+0x604/0x6f0 sound/usb/mixer.c:2490
__usb_hcd_giveback_urb+0x2e0/0x650 drivers/usb/core/hcd.c:1779
....
Allocated by task 1484:
save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59
save_stack+0x43/0xd0 mm/kasan/kasan.c:447
set_track mm/kasan/kasan.c:459
kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551
kmem_cache_alloc_trace+0x11e/0x2d0 mm/slub.c:2772
kmalloc ./include/linux/slab.h:493
kzalloc ./include/linux/slab.h:666
snd_usb_create_mixer+0x145/0x1010 sound/usb/mixer.c:2540
create_standard_mixer_quirk+0x58/0x80 sound/usb/quirks.c:516
snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560
create_composite_quirk+0x1c4/0x3e0 sound/usb/quirks.c:59
snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560
usb_audio_probe+0x1040/0x2c10 sound/usb/card.c:618
....
Freed by task 1484:
save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59
save_stack+0x43/0xd0 mm/kasan/kasan.c:447
set_track mm/kasan/kasan.c:459
kasan_slab_free+0x72/0xc0 mm/kasan/kasan.c:524
slab_free_hook mm/slub.c:1390
slab_free_freelist_hook mm/slub.c:1412
slab_free mm/slub.c:2988
kfree+0xf6/0x2f0 mm/slub.c:3919
snd_usb_mixer_free+0x11a/0x160 sound/usb/mixer.c:2244
snd_usb_mixer_dev_free+0x36/0x50 sound/usb/mixer.c:2250
__snd_device_free+0x1ff/0x380 sound/core/device.c:91
snd_device_free_all+0x8f/0xe0 sound/core/device.c:244
snd_card_do_free sound/core/init.c:461
release_card_device+0x47/0x170 sound/core/init.c:181
device_release+0x13f/0x210 drivers/base/core.c:814
....
Actually such a URB is killed properly at disconnection when the
device gets probed successfully, and what we need is to apply it for
the error-path, too.
In this patch, we apply snd_usb_mixer_disconnect() at releasing.
Also introduce a new flag, disconnected, to struct usb_mixer_interface
for not performing the disconnection procedure twice.
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416 | static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
/* kill pending URBs */
snd_usb_mixer_disconnect(mixer);
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
| 167,684 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char *create_output_name(unsigned char *fname, unsigned char *dir,
int lower, int isunix, int utf8)
{
unsigned char *p, *name, c, *fe, sep, slash;
unsigned int x;
sep = (isunix) ? '/' : '\\'; /* the path-seperator */
slash = (isunix) ? '\\' : '/'; /* the other slash */
/* length of filename */
x = strlen((char *) fname);
/* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */
if (utf8) x *= 3;
/* length of output directory */
if (dir) x += strlen((char *) dir);
if (!(name = (unsigned char *) malloc(x + 2))) {
fprintf(stderr, "out of memory!\n");
return NULL;
}
/* start with blank name */
*name = '\0';
/* add output directory if needed */
if (dir) {
strcpy((char *) name, (char *) dir);
strcat((char *) name, "/");
}
/* remove leading slashes */
while (*fname == sep) fname++;
/* copy from fi->filename to new name, converting MS-DOS slashes to UNIX
* slashes as we go. Also lowercases characters if needed.
*/
p = &name[strlen((char *)name)];
fe = &fname[strlen((char *)fname)];
if (utf8) {
/* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes.
* %000000000xxxxxxx -> %0xxxxxxx
* %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy
* %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz
*
* Therefore, the inverse is as follows:
* First char:
* 0x00 - 0x7F = one byte char
* 0x80 - 0xBF = invalid
* 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)
* 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)
* 0xF0 - 0xFF = invalid
*/
do {
if (fname >= fe) {
free(name);
return NULL;
}
/* get next UTF8 char */
if ((c = *fname++) < 0x80) x = c;
else {
if ((c >= 0xC0) && (c < 0xE0)) {
x = (c & 0x1F) << 6;
x |= *fname++ & 0x3F;
}
else if ((c >= 0xE0) && (c < 0xF0)) {
x = (c & 0xF) << 12;
x |= (*fname++ & 0x3F) << 6;
x |= *fname++ & 0x3F;
}
else x = '?';
}
/* whatever is the path seperator -> '/'
* whatever is the other slash -> '\\'
* otherwise, if lower is set, the lowercase version */
if (x == sep) x = '/';
else if (x == slash) x = '\\';
else if (lower) x = (unsigned int) tolower((int) x);
/* integer back to UTF8 */
if (x < 0x80) {
*p++ = (unsigned char) x;
}
else if (x < 0x800) {
*p++ = 0xC0 | (x >> 6);
*p++ = 0x80 | (x & 0x3F);
}
else {
*p++ = 0xE0 | (x >> 12);
*p++ = 0x80 | ((x >> 6) & 0x3F);
*p++ = 0x80 | (x & 0x3F);
}
} while (x);
}
else {
/* regular non-utf8 version */
do {
c = *fname++;
if (c == sep) c = '/';
else if (c == slash) c = '\\';
else if (lower) c = (unsigned char) tolower((int) c);
} while ((*p++ = c));
}
return (char *) name;
}
Commit Message: add anti "../" and leading slash protection to chmextract
CWE ID: CWE-22 | static char *create_output_name(unsigned char *fname, unsigned char *dir,
char *create_output_name(char *fname) {
char *out, *p;
if ((out = malloc(strlen(fname) + 1))) {
/* remove leading slashes */
while (*fname == '/' || *fname == '\\') fname++;
/* if that removes all characters, just call it "x" */
strcpy(out, (*fname) ? fname : "x");
/* change "../" to "xx/" */
for (p = out; *p; p++) {
if (p[0] == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\\')) {
p[0] = p[1] = 'x';
}
}
}
return out;
}
| 169,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) {
size_t oldSize = mSize;
size_t offset = 0;
while (mSize >= 10 && offset <= mSize - 10) {
if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
break;
}
size_t dataSize;
if (iTunesHack) {
dataSize = U32_AT(&mData[offset + 4]);
} else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
return false;
}
if (dataSize > mSize - 10 - offset) {
return false;
}
uint16_t flags = U16_AT(&mData[offset + 8]);
uint16_t prevFlags = flags;
if (flags & 1) {
if (mSize < 14 || mSize - 14 < offset || dataSize < 4) {
return false;
}
memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
mSize -= 4;
dataSize -= 4;
flags &= ~1;
}
if (flags & 2) {
size_t readOffset = offset + 11;
size_t writeOffset = offset + 11;
for (size_t i = 0; i + 1 < dataSize; ++i) {
if (mData[readOffset - 1] == 0xff
&& mData[readOffset] == 0x00) {
++readOffset;
--mSize;
--dataSize;
}
mData[writeOffset++] = mData[readOffset++];
}
memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset);
flags &= ~2;
}
if (flags != prevFlags || iTunesHack) {
WriteSyncsafeInteger(&mData[offset + 4], dataSize);
mData[offset + 8] = flags >> 8;
mData[offset + 9] = flags & 0xff;
}
offset += 10 + dataSize;
}
memset(&mData[mSize], 0, oldSize - mSize);
return true;
}
Commit Message: Fix out of bounds access
Bug: 34618607
Change-Id: I84f0ef948414d0b2d54e8948b6c30b8ae4da2b36
(cherry picked from commit d1c19c57f66d91ea8033c8fa6510a8760a6e663b)
CWE ID: CWE-119 | bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) {
size_t oldSize = mSize;
size_t offset = 0;
while (mSize >= 10 && offset <= mSize - 10) {
if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
break;
}
size_t dataSize;
if (iTunesHack) {
dataSize = U32_AT(&mData[offset + 4]);
} else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
return false;
}
if (dataSize > mSize - 10 - offset) {
return false;
}
uint16_t flags = U16_AT(&mData[offset + 8]);
uint16_t prevFlags = flags;
if (flags & 1) {
if (mSize < 14 || mSize - 14 < offset || dataSize < 4) {
return false;
}
memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
mSize -= 4;
dataSize -= 4;
flags &= ~1;
}
if ((flags & 2) && (dataSize >= 2)) {
size_t readOffset = offset + 11;
size_t writeOffset = offset + 11;
for (size_t i = 0; i + 1 < dataSize; ++i) {
if (mData[readOffset - 1] == 0xff
&& mData[readOffset] == 0x00) {
++readOffset;
--mSize;
--dataSize;
}
mData[writeOffset++] = mData[readOffset++];
}
if (readOffset <= oldSize) {
memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset);
} else {
ALOGE("b/34618607 (%zu %zu %zu %zu)", readOffset, writeOffset, oldSize, mSize);
android_errorWriteLog(0x534e4554, "34618607");
}
}
flags &= ~2;
if (flags != prevFlags || iTunesHack) {
WriteSyncsafeInteger(&mData[offset + 4], dataSize);
mData[offset + 8] = flags >> 8;
mData[offset + 9] = flags & 0xff;
}
offset += 10 + dataSize;
}
memset(&mData[mSize], 0, oldSize - mSize);
return true;
}
| 174,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebRunnerBrowserMainParts::PreMainMessageLoopRun() {
DCHECK(!screen_);
auto platform_screen = ui::OzonePlatform::GetInstance()->CreateScreen();
if (platform_screen) {
screen_ = std::make_unique<aura::ScreenOzone>(std::move(platform_screen));
} else {
screen_ = std::make_unique<WebRunnerScreen>();
}
display::Screen::SetScreenInstance(screen_.get());
DCHECK(!browser_context_);
browser_context_ =
std::make_unique<WebRunnerBrowserContext>(GetWebContextDataDir());
fidl::InterfaceRequest<chromium::web::Context> context_request(
std::move(context_channel_));
context_impl_ = std::make_unique<ContextImpl>(browser_context_.get());
context_binding_ = std::make_unique<fidl::Binding<chromium::web::Context>>(
context_impl_.get(), std::move(context_request));
context_binding_->set_error_handler(
[this]() { std::move(quit_closure_).Run(); });
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | void WebRunnerBrowserMainParts::PreMainMessageLoopRun() {
DCHECK(!screen_);
auto platform_screen = ui::OzonePlatform::GetInstance()->CreateScreen();
if (platform_screen) {
screen_ = std::make_unique<aura::ScreenOzone>(std::move(platform_screen));
} else {
screen_ = std::make_unique<WebRunnerScreen>();
}
display::Screen::SetScreenInstance(screen_.get());
DCHECK(!browser_context_);
browser_context_ =
std::make_unique<WebRunnerBrowserContext>(GetWebContextDataDir());
context_service_ = std::make_unique<ContextImpl>(browser_context_.get());
context_binding_ = std::make_unique<fidl::Binding<chromium::web::Context>>(
context_service_.get(), fidl::InterfaceRequest<chromium::web::Context>(
std::move(context_channel_)));
// Quit the browser main loop when the Context connection is dropped.
context_binding_->set_error_handler([this]() {
DLOG(WARNING) << "Client connection to Context service dropped.";
context_service_.reset();
std::move(quit_closure_).Run();
});
}
| 172,157 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXARIAGridCell::isAriaRowHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringCase(role, "rowheader");
}
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 | bool AXARIAGridCell::isAriaRowHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringASCIICase(role, "rowheader");
}
| 171,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: JSValue JSDirectoryEntry::getFile(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
if (exec->hadException())
return jsUndefined();
int argsCount = exec->argumentCount();
if (argsCount <= 1) {
imp->getFile(path);
return jsUndefined();
}
RefPtr<WebKitFlags> flags;
if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
JSObject* object = exec->argument(1).getObject();
flags = WebKitFlags::create();
JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
flags->setCreate(jsCreate.toBoolean(exec));
JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
flags->setExclusive(jsExclusive.toBoolean(exec));
}
if (exec->hadException())
return jsUndefined();
RefPtr<EntryCallback> successCallback;
if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
if (!exec->argument(2).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
}
RefPtr<ErrorCallback> errorCallback;
if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
if (!exec->argument(3).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
}
imp->getFile(path, flags, successCallback, errorCallback);
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 | JSValue JSDirectoryEntry::getFile(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createNotEnoughArgumentsError(exec));
DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
if (exec->hadException())
return jsUndefined();
int argsCount = exec->argumentCount();
if (argsCount <= 1) {
imp->getFile(path);
return jsUndefined();
}
RefPtr<WebKitFlags> flags;
if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
JSObject* object = exec->argument(1).getObject();
flags = WebKitFlags::create();
JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
flags->setCreate(jsCreate.toBoolean(exec));
JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
flags->setExclusive(jsExclusive.toBoolean(exec));
}
if (exec->hadException())
return jsUndefined();
RefPtr<EntryCallback> successCallback;
if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
if (!exec->argument(2).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
}
RefPtr<ErrorCallback> errorCallback;
if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
if (!exec->argument(3).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
}
imp->getFile(path, flags, successCallback, errorCallback);
return jsUndefined();
}
| 170,561 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
cache_filename[MaxTextExtent],
id[MaxTextExtent],
keyword[MaxTextExtent],
*options;
const unsigned char
*p;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
register ssize_t
i;
size_t
depth,
length;
ssize_t
count;
StringInfo
*profile;
unsigned int
signature;
/*
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);
}
(void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
AppendImageFormat("cache",cache_filename);
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
offset=0;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
profiles=(LinkedListInfo *) NULL;
length=MaxTextExtent;
options=AcquireString((char *) NULL);
signature=GetMagickSignature((const StringInfo *) NULL);
image->depth=8;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MaxTextExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MaxTextExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorDatabase(options,&image->background_color,
exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorDatabase(options,&image->border_color,
exception);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
image->colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
if (LocaleCompare(keyword,"error") == 0)
{
image->error.mean_error_per_pixel=StringToDouble(options,
(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"magick-signature") == 0)
{
signature=(unsigned int) StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"matte") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"matte-color") == 0)
{
(void) QueryColorDatabase(options,&image->matte_color,
exception);
break;
}
if (LocaleCompare(keyword,"maximum-error") == 0)
{
image->error.normalized_maximum_error=StringToDouble(
options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"mean-error") == 0)
{
image->error.normalized_mean_error=StringToDouble(options,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"opaque") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
if ((flags & SigmaValue) != 0)
image->chromaticity.red_primary.y=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,
options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"MagickCache") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) || (image->columns == 0) ||
(image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (signature != GetMagickSignature((const StringInfo *) NULL))
ThrowReaderException(CacheError,"IncompatibleAPI");
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MaxTextExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MaxTextExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MaxTextExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
register unsigned char
*p;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
(void) ReadBlob(image,GetStringInfoLength(profile),p);
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
/*
Create image colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->colors != 0)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Read image colormap from file.
*/
packet_size=(size_t) (3UL*depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
p=colormap;
switch (depth)
{
default:
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Attach persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
if (status == MagickFalse)
ThrowReaderException(CacheError,"UnableToPersistPixelCache");
/*
Proceed to next image.
*/
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
CWE ID: CWE-772 | static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
cache_filename[MaxTextExtent],
id[MaxTextExtent],
keyword[MaxTextExtent],
*options;
const unsigned char
*p;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
register ssize_t
i;
size_t
depth,
length;
ssize_t
count;
StringInfo
*profile;
unsigned int
signature;
/*
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);
}
(void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
AppendImageFormat("cache",cache_filename);
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
offset=0;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
profiles=(LinkedListInfo *) NULL;
length=MaxTextExtent;
options=AcquireString((char *) NULL);
signature=GetMagickSignature((const StringInfo *) NULL);
image->depth=8;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MaxTextExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MaxTextExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorDatabase(options,&image->background_color,
exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorDatabase(options,&image->border_color,
exception);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
image->colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
if (LocaleCompare(keyword,"error") == 0)
{
image->error.mean_error_per_pixel=StringToDouble(options,
(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"magick-signature") == 0)
{
signature=(unsigned int) StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"matte") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"matte-color") == 0)
{
(void) QueryColorDatabase(options,&image->matte_color,
exception);
break;
}
if (LocaleCompare(keyword,"maximum-error") == 0)
{
image->error.normalized_maximum_error=StringToDouble(
options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"mean-error") == 0)
{
image->error.normalized_mean_error=StringToDouble(options,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"opaque") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
if ((flags & SigmaValue) != 0)
image->chromaticity.red_primary.y=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,
options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"MagickCache") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) || (image->columns == 0) ||
(image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (signature != GetMagickSignature((const StringInfo *) NULL))
ThrowReaderException(CacheError,"IncompatibleAPI");
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MaxTextExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MaxTextExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MaxTextExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
register unsigned char
*p;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
(void) ReadBlob(image,GetStringInfoLength(profile),p);
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
/*
Create image colormap.
*/
image->colormap=(PixelPacket *) AcquireQuantumMemory(image->colors+1,
sizeof(*image->colormap));
if (image->colormap == (PixelPacket *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->colors != 0)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Read image colormap from file.
*/
packet_size=(size_t) (3UL*depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
p=colormap;
switch (depth)
{
default:
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
/*
Attach persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
if (status == MagickFalse)
ThrowReaderException(CacheError,"UnableToPersistPixelCache");
/*
Proceed to next image.
*/
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,408 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
unsigned code_point;
ReadUTFChar(spec, &i, end, &code_point);
AppendUTF8Value(code_point, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
Commit Message: Percent-encode UTF8 characters in URL fragment identifiers.
This brings us into line with Firefox, Safari, and the spec.
Bug: 758523
Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe
Reviewed-on: https://chromium-review.googlesource.com/668363
Commit-Queue: Mike West <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507481}
CWE ID: CWE-79 | void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
AppendUTF8EscapedChar(spec, &i, end, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
| 172,903 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
return pointer;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle))
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
return pointer;
}
| 167,605 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
Commit Message: Fixed a sanitizer failure in the BMP codec.
Also, added a --debug-level command line option to the imginfo command
for debugging purposes.
CWE ID: CWE-476 | jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
| 168,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataEntry* GDataEntry::FromDocumentEntry(
GDataDirectory* parent,
DocumentEntry* doc,
GDataDirectoryService* directory_service) {
DCHECK(doc);
if (doc->is_folder())
return GDataDirectory::FromDocumentEntry(parent, doc, directory_service);
else if (doc->is_hosted_document() || doc->is_file())
return GDataFile::FromDocumentEntry(parent, doc, directory_service);
return NULL;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataEntry* GDataEntry::FromDocumentEntry(
| 171,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static int l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
case L2CAP_MODE_STREAMING:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
| 167,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IsIDNComponentSafe(base::StringPiece16 label) {
return g_idn_spoof_checker.Get().Check(label);
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20 | bool IsIDNComponentSafe(base::StringPiece16 label) {
bool IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) {
return g_idn_spoof_checker.Get().Check(label, is_tld_ascii);
}
| 172,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcEstablishConnection(ClientPtr client)
{
const char *reason;
char *auth_proto, *auth_string;
xConnClientPrefix *prefix;
REQUEST(xReq);
prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq);
auth_proto = (char *) prefix + sz_xConnClientPrefix;
auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto);
if ((prefix->majorVersion != X_PROTOCOL) ||
(prefix->minorVersion != X_PROTOCOL_REVISION))
reason = "Protocol version mismatch";
else
return (SendConnSetup(client, reason));
}
Commit Message:
CWE ID: CWE-20 | ProcEstablishConnection(ClientPtr client)
{
const char *reason;
char *auth_proto, *auth_string;
xConnClientPrefix *prefix;
REQUEST(xReq);
prefix = (xConnClientPrefix *) ((char *) stuff + sz_xReq);
auth_proto = (char *) prefix + sz_xConnClientPrefix;
auth_string = auth_proto + pad_to_int32(prefix->nbytesAuthProto);
if ((client->req_len << 2) != sz_xReq + sz_xConnClientPrefix +
pad_to_int32(prefix->nbytesAuthProto) +
pad_to_int32(prefix->nbytesAuthString))
reason = "Bad length";
else if ((prefix->majorVersion != X_PROTOCOL) ||
(prefix->minorVersion != X_PROTOCOL_REVISION))
reason = "Protocol version mismatch";
else
return (SendConnSetup(client, reason));
}
| 165,448 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
| 173,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame),
logging_state_active_(false),
was_username_autofilled_(false),
was_password_autofilled_(false),
weak_ptr_factory_(this) {
Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
}
Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent
Unlike in AutofillAgent, the factory is no longer used in PAA.
[email protected]
BUG=609010,609007,608100,608101,433486
Review-Url: https://codereview.chromium.org/1945723003
Cr-Commit-Position: refs/heads/master@{#391475}
CWE ID: | PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame),
logging_state_active_(false),
was_username_autofilled_(false),
was_password_autofilled_(false) {
Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
}
| 173,334 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned int seedsize(struct crypto_alg *alg)
{
struct rng_alg *ralg = container_of(alg, struct rng_alg, base);
return alg->cra_rng.rng_make_random ?
alg->cra_rng.seedsize : ralg->seedsize;
}
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static unsigned int seedsize(struct crypto_alg *alg)
{
struct rng_alg *ralg = container_of(alg, struct rng_alg, base);
return ralg->seedsize;
}
| 167,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
Commit Message: xtensa: prevent arbitrary read in ptrace
Prevent an arbitrary kernel read. Check the user pointer with access_ok()
before copying data in.
[[email protected]: s/EIO/EFAULT/]
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Christian Zankel <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | int ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
if (!access_ok(VERIFY_READ, uregs, sizeof(elf_xtregs_t)))
return -EFAULT;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
| 165,849 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gray_render_span( int y,
int count,
const FT_Span* spans,
PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += ( map->rows - 1 ) * map->pitch;
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
Commit Message:
CWE ID: CWE-189 | gray_render_span( int y,
int count,
const FT_Span* spans,
PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += (unsigned)( ( map->rows - 1 ) * map->pitch );
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
| 165,004 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: transform_image_validate(transform_display *dp, png_const_structp pp,
png_infop pi)
{
/* Constants for the loop below: */
PNG_CONST png_store* PNG_CONST ps = dp->this.ps;
PNG_CONST png_byte in_ct = dp->this.colour_type;
PNG_CONST png_byte in_bd = dp->this.bit_depth;
PNG_CONST png_uint_32 w = dp->this.w;
PNG_CONST png_uint_32 h = dp->this.h;
PNG_CONST png_byte out_ct = dp->output_colour_type;
PNG_CONST png_byte out_bd = dp->output_bit_depth;
PNG_CONST png_byte sample_depth = (png_byte)(out_ct ==
PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
PNG_CONST png_byte red_sBIT = dp->this.red_sBIT;
PNG_CONST png_byte green_sBIT = dp->this.green_sBIT;
PNG_CONST png_byte blue_sBIT = dp->this.blue_sBIT;
PNG_CONST png_byte alpha_sBIT = dp->this.alpha_sBIT;
PNG_CONST int have_tRNS = dp->this.is_transparent;
double digitization_error;
store_palette out_palette;
png_uint_32 y;
UNUSED(pi)
/* Check for row overwrite errors */
store_image_check(dp->this.ps, pp, 0);
/* Read the palette corresponding to the output if the output colour type
* indicates a palette, othewise set out_palette to garbage.
*/
if (out_ct == PNG_COLOR_TYPE_PALETTE)
{
/* Validate that the palette count itself has not changed - this is not
* expected.
*/
int npalette = (-1);
(void)read_palette(out_palette, &npalette, pp, pi);
if (npalette != dp->this.npalette)
png_error(pp, "unexpected change in palette size");
digitization_error = .5;
}
else
{
png_byte in_sample_depth;
memset(out_palette, 0x5e, sizeof out_palette);
/* use-input-precision means assume that if the input has 8 bit (or less)
* samples and the output has 16 bit samples the calculations will be done
* with 8 bit precision, not 16.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
in_sample_depth = 8;
else
in_sample_depth = in_bd;
if (sample_depth != 16 || in_sample_depth > 8 ||
!dp->pm->calculations_use_input_precision)
digitization_error = .5;
/* Else calculations are at 8 bit precision, and the output actually
* consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
*/
else
digitization_error = .5 * 257;
}
for (y=0; y<h; ++y)
{
png_const_bytep PNG_CONST pRow = store_image_row(ps, pp, 0, y);
png_uint_32 x;
/* The original, standard, row pre-transforms. */
png_byte std[STANDARD_ROWMAX];
transform_row(pp, std, in_ct, in_bd, y);
/* Go through each original pixel transforming it and comparing with what
* libpng did to the same pixel.
*/
for (x=0; x<w; ++x)
{
image_pixel in_pixel, out_pixel;
unsigned int r, g, b, a;
/* Find out what we think the pixel should be: */
image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette);
in_pixel.red_sBIT = red_sBIT;
in_pixel.green_sBIT = green_sBIT;
in_pixel.blue_sBIT = blue_sBIT;
in_pixel.alpha_sBIT = alpha_sBIT;
in_pixel.have_tRNS = have_tRNS;
/* For error detection, below. */
r = in_pixel.red;
g = in_pixel.green;
b = in_pixel.blue;
a = in_pixel.alpha;
dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
/* Read the output pixel and compare it to what we got, we don't
* use the error field here, so no need to update sBIT.
*/
image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette);
/* We don't expect changes to the index here even if the bit depth is
* changed.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE &&
out_ct == PNG_COLOR_TYPE_PALETTE)
{
if (in_pixel.palette_index != out_pixel.palette_index)
png_error(pp, "unexpected transformed palette index");
}
/* Check the colours for palette images too - in fact the palette could
* be separately verified itself in most cases.
*/
if (in_pixel.red != out_pixel.red)
transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
out_pixel.red, sample_depth, in_pixel.rede,
dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.green != out_pixel.green)
transform_range_check(pp, r, g, b, a, in_pixel.green,
in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.blue != out_pixel.blue)
transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
out_pixel.blue, sample_depth, in_pixel.bluee,
dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
in_pixel.alpha != out_pixel.alpha)
transform_range_check(pp, r, g, b, a, in_pixel.alpha,
in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
digitization_error);
} /* pixel (x) loop */
} /* row (y) loop */
/* Record that something was actually checked to avoid a false positive. */
dp->this.ps->validated = 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_image_validate(transform_display *dp, png_const_structp pp,
png_infop pi)
{
/* Constants for the loop below: */
const png_store* const ps = dp->this.ps;
const png_byte in_ct = dp->this.colour_type;
const png_byte in_bd = dp->this.bit_depth;
const png_uint_32 w = dp->this.w;
const png_uint_32 h = dp->this.h;
const png_byte out_ct = dp->output_colour_type;
const png_byte out_bd = dp->output_bit_depth;
const png_byte sample_depth = (png_byte)(out_ct ==
PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
const png_byte red_sBIT = dp->this.red_sBIT;
const png_byte green_sBIT = dp->this.green_sBIT;
const png_byte blue_sBIT = dp->this.blue_sBIT;
const png_byte alpha_sBIT = dp->this.alpha_sBIT;
const int have_tRNS = dp->this.is_transparent;
double digitization_error;
store_palette out_palette;
png_uint_32 y;
UNUSED(pi)
/* Check for row overwrite errors */
store_image_check(dp->this.ps, pp, 0);
/* Read the palette corresponding to the output if the output colour type
* indicates a palette, othewise set out_palette to garbage.
*/
if (out_ct == PNG_COLOR_TYPE_PALETTE)
{
/* Validate that the palette count itself has not changed - this is not
* expected.
*/
int npalette = (-1);
(void)read_palette(out_palette, &npalette, pp, pi);
if (npalette != dp->this.npalette)
png_error(pp, "unexpected change in palette size");
digitization_error = .5;
}
else
{
png_byte in_sample_depth;
memset(out_palette, 0x5e, sizeof out_palette);
/* use-input-precision means assume that if the input has 8 bit (or less)
* samples and the output has 16 bit samples the calculations will be done
* with 8 bit precision, not 16.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
in_sample_depth = 8;
else
in_sample_depth = in_bd;
if (sample_depth != 16 || in_sample_depth > 8 ||
!dp->pm->calculations_use_input_precision)
digitization_error = .5;
/* Else calculations are at 8 bit precision, and the output actually
* consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
*/
else
digitization_error = .5 * 257;
}
for (y=0; y<h; ++y)
{
png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
png_uint_32 x;
/* The original, standard, row pre-transforms. */
png_byte std[STANDARD_ROWMAX];
transform_row(pp, std, in_ct, in_bd, y);
/* Go through each original pixel transforming it and comparing with what
* libpng did to the same pixel.
*/
for (x=0; x<w; ++x)
{
image_pixel in_pixel, out_pixel;
unsigned int r, g, b, a;
/* Find out what we think the pixel should be: */
image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
NULL);
in_pixel.red_sBIT = red_sBIT;
in_pixel.green_sBIT = green_sBIT;
in_pixel.blue_sBIT = blue_sBIT;
in_pixel.alpha_sBIT = alpha_sBIT;
in_pixel.have_tRNS = have_tRNS != 0;
/* For error detection, below. */
r = in_pixel.red;
g = in_pixel.green;
b = in_pixel.blue;
a = in_pixel.alpha;
/* This applies the transforms to the input data, including output
* format operations which must be used when reading the output
* pixel that libpng produces.
*/
dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
/* Read the output pixel and compare it to what we got, we don't
* use the error field here, so no need to update sBIT. in_pixel
* says whether we expect libpng to change the output format.
*/
image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
&in_pixel);
/* We don't expect changes to the index here even if the bit depth is
* changed.
*/
if (in_ct == PNG_COLOR_TYPE_PALETTE &&
out_ct == PNG_COLOR_TYPE_PALETTE)
{
if (in_pixel.palette_index != out_pixel.palette_index)
png_error(pp, "unexpected transformed palette index");
}
/* Check the colours for palette images too - in fact the palette could
* be separately verified itself in most cases.
*/
if (in_pixel.red != out_pixel.red)
transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
out_pixel.red, sample_depth, in_pixel.rede,
dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.green != out_pixel.green)
transform_range_check(pp, r, g, b, a, in_pixel.green,
in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
in_pixel.blue != out_pixel.blue)
transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
out_pixel.blue, sample_depth, in_pixel.bluee,
dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
digitization_error);
if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
in_pixel.alpha != out_pixel.alpha)
transform_range_check(pp, r, g, b, a, in_pixel.alpha,
in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
digitization_error);
} /* pixel (x) loop */
} /* row (y) loop */
/* Record that something was actually checked to avoid a false positive. */
dp->this.ps->validated = 1;
}
| 173,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
/* ext4_handle_valid() assumes a valid handle_t pointer */
if (handle && !ext4_handle_valid(handle))
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (sbi->s_journal && !handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
Commit Message: ext4: make orphan functions be no-op in no-journal mode
Instead of checking whether the handle is valid, we check if journal
is enabled. This avoids taking the s_orphan_lock mutex in all cases
when there is no journal in use, including the error paths where
ext4_orphan_del() is called with a handle set to NULL.
Signed-off-by: Anatol Pomozov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: CWE-20 | int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
| 166,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Visualizer_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
VisualizerContext * pContext = (VisualizerContext *)self;
int retsize;
if (pContext == NULL || pContext->mState == VISUALIZER_STATE_UNINITIALIZED) {
return -EINVAL;
}
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_init(pContext);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL ||
*replySize != sizeof(effect_config_t)) {
return -EINVAL;
}
Visualizer_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Visualizer_reset(pContext);
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_INITIALIZED) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_ACTIVE) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_GET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t)) ||
pReplyData == NULL ||
*replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t))) {
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(uint32_t));
effect_param_t *p = (effect_param_t *)pReplyData;
p->status = 0;
*replySize = sizeof(effect_param_t) + sizeof(uint32_t);
if (p->psize != sizeof(uint32_t)) {
p->status = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
ALOGV("get mCaptureSize = %" PRIu32, pContext->mCaptureSize);
*((uint32_t *)p->data + 1) = pContext->mCaptureSize;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_SCALING_MODE:
ALOGV("get mScalingMode = %" PRIu32, pContext->mScalingMode);
*((uint32_t *)p->data + 1) = pContext->mScalingMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
ALOGV("get mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
*((uint32_t *)p->data + 1) = pContext->mMeasurementMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
default:
p->status = -EINVAL;
}
} break;
case EFFECT_CMD_SET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t)) ||
pReplyData == NULL || *replySize != sizeof(int32_t)) {
return -EINVAL;
}
*(int32_t *)pReplyData = 0;
effect_param_t *p = (effect_param_t *)pCmdData;
if (p->psize != sizeof(uint32_t) || p->vsize != sizeof(uint32_t)) {
*(int32_t *)pReplyData = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
pContext->mCaptureSize = *((uint32_t *)p->data + 1);
ALOGV("set mCaptureSize = %" PRIu32, pContext->mCaptureSize);
break;
case VISUALIZER_PARAM_SCALING_MODE:
pContext->mScalingMode = *((uint32_t *)p->data + 1);
ALOGV("set mScalingMode = %" PRIu32, pContext->mScalingMode);
break;
case VISUALIZER_PARAM_LATENCY:
pContext->mLatency = *((uint32_t *)p->data + 1);
ALOGV("set mLatency = %" PRIu32, pContext->mLatency);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
pContext->mMeasurementMode = *((uint32_t *)p->data + 1);
ALOGV("set mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
break;
default:
*(int32_t *)pReplyData = -EINVAL;
}
} break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_VOLUME:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
case VISUALIZER_CMD_CAPTURE: {
uint32_t captureSize = pContext->mCaptureSize;
if (pReplyData == NULL || *replySize != captureSize) {
ALOGV("VISUALIZER_CMD_CAPTURE() error *replySize %" PRIu32 " captureSize %" PRIu32,
*replySize, captureSize);
return -EINVAL;
}
if (pContext->mState == VISUALIZER_STATE_ACTIVE) {
const uint32_t deltaMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if ((pContext->mLastCaptureIdx == pContext->mCaptureIdx) &&
(pContext->mBufferUpdateTime.tv_sec != 0) &&
(deltaMs > MAX_STALL_TIME_MS)) {
ALOGV("capture going to idle");
pContext->mBufferUpdateTime.tv_sec = 0;
memset(pReplyData, 0x80, captureSize);
} else {
int32_t latencyMs = pContext->mLatency;
latencyMs -= deltaMs;
if (latencyMs < 0) {
latencyMs = 0;
}
const uint32_t deltaSmpl =
pContext->mConfig.inputCfg.samplingRate * latencyMs / 1000;
int32_t capturePoint = pContext->mCaptureIdx - captureSize - deltaSmpl;
if (capturePoint < 0) {
uint32_t size = -capturePoint;
if (size > captureSize) {
size = captureSize;
}
memcpy(pReplyData,
pContext->mCaptureBuf + CAPTURE_BUF_SIZE + capturePoint,
size);
pReplyData = (char *)pReplyData + size;
captureSize -= size;
capturePoint = 0;
}
memcpy(pReplyData,
pContext->mCaptureBuf + capturePoint,
captureSize);
}
pContext->mLastCaptureIdx = pContext->mCaptureIdx;
} else {
memset(pReplyData, 0x80, captureSize);
}
} break;
case VISUALIZER_CMD_MEASURE: {
uint16_t peakU16 = 0;
float sumRmsSquared = 0.0f;
uint8_t nbValidMeasurements = 0;
const int32_t delayMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if (delayMs > DISCARD_MEASUREMENTS_TIME_MS) {
ALOGV("Discarding measurements, last measurement is %" PRId32 "ms old", delayMs);
for (uint32_t i=0 ; i<pContext->mMeasurementWindowSizeInBuffers ; i++) {
pContext->mPastMeasurements[i].mIsValid = false;
pContext->mPastMeasurements[i].mPeakU16 = 0;
pContext->mPastMeasurements[i].mRmsSquared = 0;
}
pContext->mMeasurementBufferIdx = 0;
} else {
for (uint32_t i=0 ; i < pContext->mMeasurementWindowSizeInBuffers ; i++) {
if (pContext->mPastMeasurements[i].mIsValid) {
if (pContext->mPastMeasurements[i].mPeakU16 > peakU16) {
peakU16 = pContext->mPastMeasurements[i].mPeakU16;
}
sumRmsSquared += pContext->mPastMeasurements[i].mRmsSquared;
nbValidMeasurements++;
}
}
}
float rms = nbValidMeasurements == 0 ? 0.0f : sqrtf(sumRmsSquared / nbValidMeasurements);
int32_t* pIntReplyData = (int32_t*)pReplyData;
if (rms < 0.000016f) {
pIntReplyData[MEASUREMENT_IDX_RMS] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_RMS] = (int32_t) (2000 * log10(rms / 32767.0f));
}
if (peakU16 == 0) {
pIntReplyData[MEASUREMENT_IDX_PEAK] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_PEAK] = (int32_t) (2000 * log10(peakU16 / 32767.0f));
}
ALOGV("VISUALIZER_CMD_MEASURE peak=%" PRIu16 " (%" PRId32 "mB), rms=%.1f (%" PRId32 "mB)",
peakU16, pIntReplyData[MEASUREMENT_IDX_PEAK],
rms, pIntReplyData[MEASUREMENT_IDX_RMS]);
}
break;
default:
ALOGW("Visualizer_command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
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 | int Visualizer_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
VisualizerContext * pContext = (VisualizerContext *)self;
int retsize;
if (pContext == NULL || pContext->mState == VISUALIZER_STATE_UNINITIALIZED) {
return -EINVAL;
}
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_init(pContext);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL ||
*replySize != sizeof(effect_config_t)) {
return -EINVAL;
}
Visualizer_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Visualizer_reset(pContext);
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_INITIALIZED) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_ACTIVE) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_GET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t))) {
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(uint32_t));
effect_param_t *p = (effect_param_t *)pReplyData;
p->status = 0;
*replySize = sizeof(effect_param_t) + sizeof(uint32_t);
if (p->psize != sizeof(uint32_t)) {
p->status = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
ALOGV("get mCaptureSize = %" PRIu32, pContext->mCaptureSize);
*((uint32_t *)p->data + 1) = pContext->mCaptureSize;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_SCALING_MODE:
ALOGV("get mScalingMode = %" PRIu32, pContext->mScalingMode);
*((uint32_t *)p->data + 1) = pContext->mScalingMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
ALOGV("get mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
*((uint32_t *)p->data + 1) = pContext->mMeasurementMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
default:
p->status = -EINVAL;
}
} break;
case EFFECT_CMD_SET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t)) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
return -EINVAL;
}
*(int32_t *)pReplyData = 0;
effect_param_t *p = (effect_param_t *)pCmdData;
if (p->psize != sizeof(uint32_t) || p->vsize != sizeof(uint32_t)) {
*(int32_t *)pReplyData = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
pContext->mCaptureSize = *((uint32_t *)p->data + 1);
ALOGV("set mCaptureSize = %" PRIu32, pContext->mCaptureSize);
break;
case VISUALIZER_PARAM_SCALING_MODE:
pContext->mScalingMode = *((uint32_t *)p->data + 1);
ALOGV("set mScalingMode = %" PRIu32, pContext->mScalingMode);
break;
case VISUALIZER_PARAM_LATENCY:
pContext->mLatency = *((uint32_t *)p->data + 1);
ALOGV("set mLatency = %" PRIu32, pContext->mLatency);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
pContext->mMeasurementMode = *((uint32_t *)p->data + 1);
ALOGV("set mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
break;
default:
*(int32_t *)pReplyData = -EINVAL;
}
} break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_VOLUME:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
case VISUALIZER_CMD_CAPTURE: {
uint32_t captureSize = pContext->mCaptureSize;
if (pReplyData == NULL || replySize == NULL || *replySize != captureSize) {
ALOGV("VISUALIZER_CMD_CAPTURE() error *replySize %" PRIu32 " captureSize %" PRIu32,
*replySize, captureSize);
return -EINVAL;
}
if (pContext->mState == VISUALIZER_STATE_ACTIVE) {
const uint32_t deltaMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if ((pContext->mLastCaptureIdx == pContext->mCaptureIdx) &&
(pContext->mBufferUpdateTime.tv_sec != 0) &&
(deltaMs > MAX_STALL_TIME_MS)) {
ALOGV("capture going to idle");
pContext->mBufferUpdateTime.tv_sec = 0;
memset(pReplyData, 0x80, captureSize);
} else {
int32_t latencyMs = pContext->mLatency;
latencyMs -= deltaMs;
if (latencyMs < 0) {
latencyMs = 0;
}
const uint32_t deltaSmpl =
pContext->mConfig.inputCfg.samplingRate * latencyMs / 1000;
int32_t capturePoint = pContext->mCaptureIdx - captureSize - deltaSmpl;
if (capturePoint < 0) {
uint32_t size = -capturePoint;
if (size > captureSize) {
size = captureSize;
}
memcpy(pReplyData,
pContext->mCaptureBuf + CAPTURE_BUF_SIZE + capturePoint,
size);
pReplyData = (char *)pReplyData + size;
captureSize -= size;
capturePoint = 0;
}
memcpy(pReplyData,
pContext->mCaptureBuf + capturePoint,
captureSize);
}
pContext->mLastCaptureIdx = pContext->mCaptureIdx;
} else {
memset(pReplyData, 0x80, captureSize);
}
} break;
case VISUALIZER_CMD_MEASURE: {
uint16_t peakU16 = 0;
float sumRmsSquared = 0.0f;
uint8_t nbValidMeasurements = 0;
const int32_t delayMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if (delayMs > DISCARD_MEASUREMENTS_TIME_MS) {
ALOGV("Discarding measurements, last measurement is %" PRId32 "ms old", delayMs);
for (uint32_t i=0 ; i<pContext->mMeasurementWindowSizeInBuffers ; i++) {
pContext->mPastMeasurements[i].mIsValid = false;
pContext->mPastMeasurements[i].mPeakU16 = 0;
pContext->mPastMeasurements[i].mRmsSquared = 0;
}
pContext->mMeasurementBufferIdx = 0;
} else {
for (uint32_t i=0 ; i < pContext->mMeasurementWindowSizeInBuffers ; i++) {
if (pContext->mPastMeasurements[i].mIsValid) {
if (pContext->mPastMeasurements[i].mPeakU16 > peakU16) {
peakU16 = pContext->mPastMeasurements[i].mPeakU16;
}
sumRmsSquared += pContext->mPastMeasurements[i].mRmsSquared;
nbValidMeasurements++;
}
}
}
float rms = nbValidMeasurements == 0 ? 0.0f : sqrtf(sumRmsSquared / nbValidMeasurements);
int32_t* pIntReplyData = (int32_t*)pReplyData;
if (rms < 0.000016f) {
pIntReplyData[MEASUREMENT_IDX_RMS] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_RMS] = (int32_t) (2000 * log10(rms / 32767.0f));
}
if (peakU16 == 0) {
pIntReplyData[MEASUREMENT_IDX_PEAK] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_PEAK] = (int32_t) (2000 * log10(peakU16 / 32767.0f));
}
ALOGV("VISUALIZER_CMD_MEASURE peak=%" PRIu16 " (%" PRId32 "mB), rms=%.1f (%" PRId32 "mB)",
peakU16, pIntReplyData[MEASUREMENT_IDX_PEAK],
rms, pIntReplyData[MEASUREMENT_IDX_RMS]);
}
break;
default:
ALOGW("Visualizer_command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
| 173,355 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Blob::~Blob()
{
ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | Blob::~Blob()
{
BlobRegistry::unregisterBlobURL(m_internalURL);
}
| 170,679 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
struct sshbuf *b = NULL;
int r;
const u_char *inblob, *outblob;
size_t inl, outl;
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
(r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
goto out;
if (inl == 0)
state->compression_in_started = 0;
else if (inl != sizeof(state->compression_in_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_in_started = 1;
memcpy(&state->compression_in_stream, inblob, inl);
}
if (outl == 0)
state->compression_out_started = 0;
else if (outl != sizeof(state->compression_out_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_out_started = 1;
memcpy(&state->compression_out_stream, outblob, outl);
}
r = 0;
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
| 168,654 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
JBIG2Segment(segNumA)
{
w = wA;
h = hA;
line = (wA + 7) >> 3;
if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
error(-1, "invalid width/height");
data = NULL;
return;
}
data = (Guchar *)gmalloc(h * line + 1);
data[h * line] = 0;
}
Commit Message:
CWE ID: CWE-189 | JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
JBIG2Segment(segNumA)
{
w = wA;
h = hA;
line = (wA + 7) >> 3;
if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
error(-1, "invalid width/height");
data = NULL;
return;
}
data = (Guchar *)gmallocn(h, line + 1);
data[h * line] = 0;
}
| 164,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init ipgre_init(void)
{
int err;
printk(KERN_INFO "GRE over IPv4 tunneling driver\n");
if (inet_add_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) {
printk(KERN_INFO "ipgre init: can't add protocol\n");
return -EAGAIN;
}
err = register_pernet_device(&ipgre_net_ops);
if (err < 0)
goto gen_device_failed;
err = rtnl_link_register(&ipgre_link_ops);
if (err < 0)
goto rtnl_link_failed;
err = rtnl_link_register(&ipgre_tap_ops);
if (err < 0)
goto tap_ops_failed;
out:
return err;
tap_ops_failed:
rtnl_link_unregister(&ipgre_link_ops);
rtnl_link_failed:
unregister_pernet_device(&ipgre_net_ops);
gen_device_failed:
inet_del_protocol(&ipgre_protocol, IPPROTO_GRE);
goto out;
}
Commit Message: gre: fix netns vs proto registration ordering
GRE protocol receive hook can be called right after protocol addition is done.
If netns stuff is not yet initialized, we're going to oops in
net_generic().
This is remotely oopsable if ip_gre is compiled as module and packet
comes at unfortunate moment of module loading.
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int __init ipgre_init(void)
{
int err;
printk(KERN_INFO "GRE over IPv4 tunneling driver\n");
err = register_pernet_device(&ipgre_net_ops);
if (err < 0)
return err;
err = inet_add_protocol(&ipgre_protocol, IPPROTO_GRE);
if (err < 0) {
printk(KERN_INFO "ipgre init: can't add protocol\n");
goto add_proto_failed;
}
err = rtnl_link_register(&ipgre_link_ops);
if (err < 0)
goto rtnl_link_failed;
err = rtnl_link_register(&ipgre_tap_ops);
if (err < 0)
goto tap_ops_failed;
out:
return err;
tap_ops_failed:
rtnl_link_unregister(&ipgre_link_ops);
rtnl_link_failed:
inet_del_protocol(&ipgre_protocol, IPPROTO_GRE);
add_proto_failed:
unregister_pernet_device(&ipgre_net_ops);
goto out;
}
| 165,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
Commit Message: Always mark content downloaded by devtools delegate as potentially dangerous
Bug: 805445
Change-Id: I7051f519205e178db57e23320ab979f8fa9ce38b
Reviewed-on: https://chromium-review.googlesource.com/894782
Commit-Queue: David Vallet <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533215}
CWE ID: | void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
| 173,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: iakerb_gss_export_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 maj;
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
/* We don't currently support exporting partially established contexts. */
if (!ctx->established)
return GSS_S_UNAVAILABLE;
maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc,
interprocess_token);
if (ctx->gssc == GSS_C_NO_CONTEXT) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return maj;
}
Commit Message: Fix IAKERB context export/import [CVE-2015-2698]
The patches for CVE-2015-2696 contained a regression in the newly
added IAKERB iakerb_gss_export_sec_context() function, which could
cause it to corrupt memory. Fix the regression by properly
dereferencing the context_handle pointer before casting it.
Also, the patches did not implement an IAKERB gss_import_sec_context()
function, under the erroneous belief that an exported IAKERB context
would be tagged as a krb5 context. Implement it now to allow IAKERB
contexts to be successfully exported and imported after establishment.
CVE-2015-2698:
In any MIT krb5 release with the patches for CVE-2015-2696 applied, an
application which calls gss_export_sec_context() may experience memory
corruption if the context was established using the IAKERB mechanism.
Historically, some vulnerabilities of this nature can be translated
into remote code execution, though the necessary exploits must be
tailored to the individual application and are usually quite
complicated.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C
ticket: 8273 (new)
target_version: 1.14
tags: pullup
CWE ID: CWE-119 | iakerb_gss_export_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 maj;
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle;
/* We don't currently support exporting partially established contexts. */
if (!ctx->established)
return GSS_S_UNAVAILABLE;
maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc,
interprocess_token);
if (ctx->gssc == GSS_C_NO_CONTEXT) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return maj;
}
| 166,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (request.url() != GURL(kSwappedOutURL) &&
GetContentClient()->renderer()->HandleNavigation(frame, request, type,
default_policy,
is_redirect)) {
return WebKit::WebNavigationPolicyIgnore;
}
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(frame, request));
if (is_swapped_out_) {
if (request.url() != GURL(kSwappedOutURL)) {
if (frame->parent() == NULL) {
OpenURL(frame, request.url(), referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool force_swap_due_to_flag =
command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
command_line.HasSwitch(switches::kSitePerProcess);
if (force_swap_due_to_flag &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (!net::RegistryControlledDomainService::SameDomainOrHost(frame_url,
url) ||
frame_url.scheme() != url.scheme()) {
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_request =
renderer_preferences_.browser_handles_non_local_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (!browser_handles_request) {
browser_handles_request =
renderer_preferences_.browser_handles_all_top_level_requests &&
IsTopLevelNavigation(frame);
}
if (browser_handles_request) {
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
bool is_initial_navigation = page_id_ == -1;
bool should_fork = HasWebUIScheme(url) ||
(cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
(frame->isViewSourceModeEnabled() &&
type != WebKit::WebNavigationTypeReload);
if (!should_fork && url.SchemeIs(chrome::kFileScheme)) {
GURL source_url(old_url);
if (is_initial_navigation && source_url.is_empty() && frame->opener())
source_url = frame->opener()->top()->document().url();
DCHECK(!source_url.is_empty());
should_fork = !source_url.SchemeIs(chrome::kFileScheme);
}
if (!should_fork) {
should_fork = GetContentClient()->renderer()->ShouldFork(
frame, url, request.httpMethod().utf8(), is_initial_navigation,
&send_referrer);
}
if (should_fork) {
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
Commit Message: Let the browser handle external navigations from DevTools.
BUG=180555
Review URL: https://chromiumcodereview.appspot.com/12531004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (request.url() != GURL(kSwappedOutURL) &&
GetContentClient()->renderer()->HandleNavigation(frame, request, type,
default_policy,
is_redirect)) {
return WebKit::WebNavigationPolicyIgnore;
}
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(frame, request));
if (is_swapped_out_) {
if (request.url() != GURL(kSwappedOutURL)) {
if (frame->parent() == NULL) {
OpenURL(frame, request.url(), referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool force_swap_due_to_flag =
command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
command_line.HasSwitch(switches::kSitePerProcess);
if (force_swap_due_to_flag &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (!net::RegistryControlledDomainService::SameDomainOrHost(frame_url,
url) ||
frame_url.scheme() != url.scheme()) {
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_request =
renderer_preferences_.browser_handles_non_local_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (!browser_handles_request) {
browser_handles_request =
renderer_preferences_.browser_handles_all_top_level_requests &&
IsTopLevelNavigation(frame);
}
if (browser_handles_request) {
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
// All navigations to or from WebUI URLs or within WebUI-enabled
// RenderProcesses must be handled by the browser process so that the
// correct bindings and data sources can be registered.
int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
bool is_initial_navigation = page_id_ == -1;
bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
(cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
(frame->isViewSourceModeEnabled() &&
type != WebKit::WebNavigationTypeReload);
if (!should_fork && url.SchemeIs(chrome::kFileScheme)) {
GURL source_url(old_url);
if (is_initial_navigation && source_url.is_empty() && frame->opener())
source_url = frame->opener()->top()->document().url();
DCHECK(!source_url.is_empty());
should_fork = !source_url.SchemeIs(chrome::kFileScheme);
}
if (!should_fork) {
should_fork = GetContentClient()->renderer()->ShouldFork(
frame, url, request.httpMethod().utf8(), is_initial_navigation,
&send_referrer);
}
if (should_fork) {
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
| 171,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CreateOAuth2ServiceDelegate(
signin::AccountConsistencyMethod account_consistency) {
oauth2_service_delegate_.reset(new MutableProfileOAuth2TokenServiceDelegate(
client_.get(), &signin_error_controller_, &account_tracker_service_,
token_web_data_, account_consistency, revoke_all_tokens_on_load_,
true /* can_revoke_credantials */));
base::RunLoop().RunUntilIdle();
oauth2_service_delegate_->AddObserver(this);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void CreateOAuth2ServiceDelegate(
std::unique_ptr<MutableProfileOAuth2TokenServiceDelegate>
CreateOAuth2ServiceDelegate(
signin::AccountConsistencyMethod account_consistency) {
return std::make_unique<MutableProfileOAuth2TokenServiceDelegate>(
client_.get(), &signin_error_controller_, &account_tracker_service_,
token_web_data_, account_consistency, revoke_all_tokens_on_load_,
true /* can_revoke_credantials */);
// Make sure delegate has a chance to load itself before continuing.
base::RunLoop().RunUntilIdle();
}
void InitializeOAuth2ServiceDelegate(
signin::AccountConsistencyMethod account_consistency) {
oauth2_service_delegate_ = CreateOAuth2ServiceDelegate(account_consistency);
oauth2_service_delegate_->AddObserver(this);
}
| 172,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val)
{
int i;
RESOLVE(obj);
if (!OBJ_IS_DICT(obj))
fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj));
if (!val)
val = PDF_OBJ_NULL;
if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED))
pdf_sort_dict(ctx, obj);
if (key < PDF_OBJ_NAME__LIMIT)
i = pdf_dict_find(ctx, obj, key);
else
i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key));
prepare_object_for_alteration(ctx, obj, val);
if (i >= 0 && i < DICT(obj)->len)
{
if (DICT(obj)->items[i].v != val)
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
pdf_drop_obj(ctx, d);
}
}
else
memmove(&DICT(obj)->items[i + 1],
&DICT(obj)->items[i],
(DICT(obj)->len - i) * sizeof(struct keyval));
DICT(obj)->items[i].k = pdf_keep_obj(ctx, key);
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
DICT(obj)->len ++;
}
}
Commit Message:
CWE ID: CWE-416 | pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val)
static void
pdf_dict_get_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val, pdf_obj **old_val)
{
int i;
if (old_val)
*old_val = NULL;
RESOLVE(obj);
if (!OBJ_IS_DICT(obj))
fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj));
if (!val)
val = PDF_OBJ_NULL;
if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED))
pdf_sort_dict(ctx, obj);
if (key < PDF_OBJ_NAME__LIMIT)
i = pdf_dict_find(ctx, obj, key);
else
i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key));
prepare_object_for_alteration(ctx, obj, val);
if (i >= 0 && i < DICT(obj)->len)
{
if (DICT(obj)->items[i].v != val)
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
{
pdf_obj *d = DICT(obj)->items[i].v;
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
if (old_val)
*old_val = d;
else
pdf_drop_obj(ctx, d);
}
}
else
memmove(&DICT(obj)->items[i + 1],
&DICT(obj)->items[i],
(DICT(obj)->len - i) * sizeof(struct keyval));
DICT(obj)->items[i].k = pdf_keep_obj(ctx, key);
DICT(obj)->items[i].v = pdf_keep_obj(ctx, val);
DICT(obj)->len ++;
}
}
| 165,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithCallbackArg(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"));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
impl->methodWithCallbackArg(callback);
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 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithCallbackArg(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, createNotEnoughArgumentsError(exec));
if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject());
impl->methodWithCallbackArg(callback);
return JSValue::encode(jsUndefined());
}
| 170,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGLRenderingContextBase::linkProgram(WebGLProgram* program) {
if (!ValidateWebGLProgramOrShader("linkProgram", program))
return;
if (program->ActiveTransformFeedbackCount() > 0) {
SynthesizeGLError(
GL_INVALID_OPERATION, "linkProgram",
"program being used by one or more active transform feedback objects");
return;
}
ContextGL()->LinkProgram(ObjectOrZero(program));
program->IncreaseLinkCount();
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | void WebGLRenderingContextBase::linkProgram(WebGLProgram* program) {
if (!ValidateWebGLProgramOrShader("linkProgram", program))
return;
if (program->ActiveTransformFeedbackCount() > 0) {
SynthesizeGLError(
GL_INVALID_OPERATION, "linkProgram",
"program being used by one or more active transform feedback objects");
return;
}
GLuint query = 0u;
if (ExtensionEnabled(kKHRParallelShaderCompileName)) {
ContextGL()->GenQueriesEXT(1, &query);
ContextGL()->BeginQueryEXT(GL_PROGRAM_COMPLETION_QUERY_CHROMIUM, query);
}
ContextGL()->LinkProgram(ObjectOrZero(program));
if (ExtensionEnabled(kKHRParallelShaderCompileName)) {
ContextGL()->EndQueryEXT(GL_PROGRAM_COMPLETION_QUERY_CHROMIUM);
addProgramCompletionQuery(program, query);
}
program->IncreaseLinkCount();
}
| 172,537 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int inotify_release(struct inode *ignored, struct file *file)
{
struct fsnotify_group *group = file->private_data;
struct user_struct *user = group->inotify_data.user;
pr_debug("%s: group=%p\n", __func__, group);
fsnotify_clear_marks_by_group(group);
/* free this group, matching get was inotify_init->fsnotify_obtain_group */
fsnotify_put_group(group);
atomic_dec(&user->inotify_devs);
return 0;
}
Commit Message: inotify: fix double free/corruption of stuct user
On an error path in inotify_init1 a normal user can trigger a double
free of struct user. This is a regression introduced by a2ae4cc9a16e
("inotify: stop kernel memory leak on file creation failure").
We fix this by making sure that if a group exists the user reference is
dropped when the group is cleaned up. We should not explictly drop the
reference on error and also drop the reference when the group is cleaned
up.
The new lifetime rules are that an inotify group lives from
inotify_new_group to the last fsnotify_put_group. Since the struct user
and inotify_devs are directly tied to this lifetime they are only
changed/updated in those two locations. We get rid of all special
casing of struct user or user->inotify_devs.
Signed-off-by: Eric Paris <[email protected]>
Cc: [email protected] (2.6.37 and up)
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static int inotify_release(struct inode *ignored, struct file *file)
{
struct fsnotify_group *group = file->private_data;
pr_debug("%s: group=%p\n", __func__, group);
fsnotify_clear_marks_by_group(group);
/* free this group, matching get was inotify_init->fsnotify_obtain_group */
fsnotify_put_group(group);
return 0;
}
| 165,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CorePageLoadMetricsObserver::RecordTimingHistograms(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& info) {
if (info.started_in_foreground && info.first_background_time) {
const base::TimeDelta first_background_time =
info.first_background_time.value();
if (!info.time_to_commit) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit,
first_background_time);
} else if (!timing.first_paint ||
timing.first_paint > first_background_time) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint,
first_background_time);
}
if (timing.parse_start && first_background_time >= timing.parse_start &&
(!timing.parse_stop || timing.parse_stop > first_background_time)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse,
first_background_time);
}
}
if (failed_provisional_load_info_.error != net::OK) {
DCHECK(failed_provisional_load_info_.interval);
if (WasStartedInForegroundOptionalEventInForeground(
failed_provisional_load_info_.interval, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad,
failed_provisional_load_info_.interval.value());
}
}
if (!info.time_to_commit || timing.IsEmpty())
return;
const base::TimeDelta time_to_commit = info.time_to_commit.value();
if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit);
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit);
}
if (timing.dom_content_loaded_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.dom_content_loaded_event_start, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded,
timing.dom_content_loaded_event_start.value() -
timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
}
}
if (timing.load_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad,
timing.load_event_start.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad,
timing.load_event_start.value());
}
}
if (timing.first_layout) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout,
timing.first_layout.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout,
timing.first_layout.value());
}
}
if (timing.first_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint,
timing.first_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint,
timing.first_paint.value());
}
if (!info.started_in_foreground && info.first_foreground_time &&
timing.first_paint > info.first_foreground_time.value() &&
(!info.first_background_time ||
timing.first_paint < info.first_background_time.value())) {
PAGE_LOAD_HISTOGRAM(
internal::kHistogramForegroundToFirstPaint,
timing.first_paint.value() - info.first_foreground_time.value());
}
}
if (timing.first_text_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint,
timing.first_text_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint,
timing.first_text_paint.value());
}
}
if (timing.first_image_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_image_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint,
timing.first_image_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint,
timing.first_image_paint.value());
}
}
if (timing.first_contentful_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_contentful_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
if (base::TimeTicks::IsHighResolution()) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintHigh,
timing.first_contentful_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintLow,
timing.first_contentful_paint.value());
}
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseStartToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.parse_start.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramDomLoadingToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
}
}
if (timing.parse_start) {
if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (timing.parse_stop) {
base::TimeDelta parse_duration =
timing.parse_stop.value() - timing.parse_start.value();
if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration,
parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (info.started_in_foreground) {
if (info.first_background_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground,
info.first_background_time.value());
} else {
if (info.first_foreground_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground,
info.first_foreground_time.value());
}
}
Commit Message: Remove clock resolution page load histograms.
These were temporary metrics intended to understand whether high/low
resolution clocks adversely impact page load metrics. After collecting a few
months of data it was determined that clock resolution doesn't adversely
impact our metrics, and it that these histograms were no longer needed.
BUG=394757
Review-Url: https://codereview.chromium.org/2155143003
Cr-Commit-Position: refs/heads/master@{#406143}
CWE ID: | void CorePageLoadMetricsObserver::RecordTimingHistograms(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& info) {
if (info.started_in_foreground && info.first_background_time) {
const base::TimeDelta first_background_time =
info.first_background_time.value();
if (!info.time_to_commit) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit,
first_background_time);
} else if (!timing.first_paint ||
timing.first_paint > first_background_time) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint,
first_background_time);
}
if (timing.parse_start && first_background_time >= timing.parse_start &&
(!timing.parse_stop || timing.parse_stop > first_background_time)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse,
first_background_time);
}
}
if (failed_provisional_load_info_.error != net::OK) {
DCHECK(failed_provisional_load_info_.interval);
if (WasStartedInForegroundOptionalEventInForeground(
failed_provisional_load_info_.interval, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad,
failed_provisional_load_info_.interval.value());
}
}
if (!info.time_to_commit || timing.IsEmpty())
return;
const base::TimeDelta time_to_commit = info.time_to_commit.value();
if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit);
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit);
}
if (timing.dom_content_loaded_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.dom_content_loaded_event_start, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded,
timing.dom_content_loaded_event_start.value() -
timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
}
}
if (timing.load_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad,
timing.load_event_start.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad,
timing.load_event_start.value());
}
}
if (timing.first_layout) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout,
timing.first_layout.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout,
timing.first_layout.value());
}
}
if (timing.first_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint,
timing.first_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint,
timing.first_paint.value());
}
if (!info.started_in_foreground && info.first_foreground_time &&
timing.first_paint > info.first_foreground_time.value() &&
(!info.first_background_time ||
timing.first_paint < info.first_background_time.value())) {
PAGE_LOAD_HISTOGRAM(
internal::kHistogramForegroundToFirstPaint,
timing.first_paint.value() - info.first_foreground_time.value());
}
}
if (timing.first_text_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint,
timing.first_text_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint,
timing.first_text_paint.value());
}
}
if (timing.first_image_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_image_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint,
timing.first_image_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint,
timing.first_image_paint.value());
}
}
if (timing.first_contentful_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_contentful_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseStartToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.parse_start.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramDomLoadingToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
}
}
if (timing.parse_start) {
if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (timing.parse_stop) {
base::TimeDelta parse_duration =
timing.parse_stop.value() - timing.parse_start.value();
if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration,
parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (info.started_in_foreground) {
if (info.first_background_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground,
info.first_background_time.value());
} else {
if (info.first_foreground_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground,
info.first_foreground_time.value());
}
}
| 171,663 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PropertyTreeManager::SetupRootEffectNode() {
cc::EffectTree& effect_tree = property_trees_.effect_tree;
effect_tree.clear();
property_trees_.element_id_to_effect_node_index.clear();
cc::EffectNode& effect_node =
*effect_tree.Node(effect_tree.Insert(cc::EffectNode(), kInvalidNodeId));
DCHECK_EQ(effect_node.id, kSecondaryRootNodeId);
static UniqueObjectId unique_id = NewUniqueObjectId();
effect_node.stable_id =
CompositorElementIdFromUniqueObjectId(unique_id).ToInternalValue();
effect_node.transform_id = kRealRootNodeId;
effect_node.clip_id = kSecondaryRootNodeId;
effect_node.has_render_surface = true;
root_layer_->SetEffectTreeIndex(effect_node.id);
current_effect_id_ = effect_node.id;
current_effect_type_ = CcEffectType::kEffect;
current_effect_ = EffectPaintPropertyNode::Root();
current_clip_ = current_effect_->OutputClip();
}
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: | void PropertyTreeManager::SetupRootEffectNode() {
cc::EffectTree& effect_tree = property_trees_.effect_tree;
effect_tree.clear();
property_trees_.element_id_to_effect_node_index.clear();
cc::EffectNode& effect_node =
*effect_tree.Node(effect_tree.Insert(cc::EffectNode(), kInvalidNodeId));
DCHECK_EQ(effect_node.id, kSecondaryRootNodeId);
static UniqueObjectId unique_id = NewUniqueObjectId();
effect_node.stable_id =
CompositorElementIdFromUniqueObjectId(unique_id).ToInternalValue();
effect_node.transform_id = kRealRootNodeId;
effect_node.clip_id = kSecondaryRootNodeId;
effect_node.has_render_surface = true;
root_layer_->SetEffectTreeIndex(effect_node.id);
current_effect_id_ = effect_node.id;
current_effect_type_ = CcEffectType::kEffect;
current_effect_ = &EffectPaintPropertyNode::Root();
current_clip_ = current_effect_->OutputClip();
}
| 171,829 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
xml_parser *parser = (xml_parser *)rsrc->ptr;
if (parser->parser) {
XML_ParserFree(parser->parser);
}
if (parser->ltags) {
int inx;
for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++)
efree(parser->ltags[ inx ]);
efree(parser->ltags);
}
if (parser->startElementHandler) {
zval_ptr_dtor(&parser->startElementHandler);
}
if (parser->endElementHandler) {
zval_ptr_dtor(&parser->endElementHandler);
}
if (parser->characterDataHandler) {
zval_ptr_dtor(&parser->characterDataHandler);
}
if (parser->processingInstructionHandler) {
zval_ptr_dtor(&parser->processingInstructionHandler);
}
if (parser->defaultHandler) {
zval_ptr_dtor(&parser->defaultHandler);
}
if (parser->unparsedEntityDeclHandler) {
zval_ptr_dtor(&parser->unparsedEntityDeclHandler);
}
if (parser->notationDeclHandler) {
zval_ptr_dtor(&parser->notationDeclHandler);
}
if (parser->externalEntityRefHandler) {
zval_ptr_dtor(&parser->externalEntityRefHandler);
}
if (parser->unknownEncodingHandler) {
zval_ptr_dtor(&parser->unknownEncodingHandler);
}
if (parser->startNamespaceDeclHandler) {
zval_ptr_dtor(&parser->startNamespaceDeclHandler);
}
if (parser->endNamespaceDeclHandler) {
zval_ptr_dtor(&parser->endNamespaceDeclHandler);
}
if (parser->baseURI) {
efree(parser->baseURI);
}
if (parser->object) {
zval_ptr_dtor(&parser->object);
}
efree(parser);
}
Commit Message:
CWE ID: CWE-119 | static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
xml_parser *parser = (xml_parser *)rsrc->ptr;
if (parser->parser) {
XML_ParserFree(parser->parser);
}
if (parser->ltags) {
int inx;
for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++)
efree(parser->ltags[ inx ]);
efree(parser->ltags);
}
if (parser->startElementHandler) {
zval_ptr_dtor(&parser->startElementHandler);
}
if (parser->endElementHandler) {
zval_ptr_dtor(&parser->endElementHandler);
}
if (parser->characterDataHandler) {
zval_ptr_dtor(&parser->characterDataHandler);
}
if (parser->processingInstructionHandler) {
zval_ptr_dtor(&parser->processingInstructionHandler);
}
if (parser->defaultHandler) {
zval_ptr_dtor(&parser->defaultHandler);
}
if (parser->unparsedEntityDeclHandler) {
zval_ptr_dtor(&parser->unparsedEntityDeclHandler);
}
if (parser->notationDeclHandler) {
zval_ptr_dtor(&parser->notationDeclHandler);
}
if (parser->externalEntityRefHandler) {
zval_ptr_dtor(&parser->externalEntityRefHandler);
}
if (parser->unknownEncodingHandler) {
zval_ptr_dtor(&parser->unknownEncodingHandler);
}
if (parser->startNamespaceDeclHandler) {
zval_ptr_dtor(&parser->startNamespaceDeclHandler);
}
if (parser->endNamespaceDeclHandler) {
zval_ptr_dtor(&parser->endNamespaceDeclHandler);
}
if (parser->baseURI) {
efree(parser->baseURI);
}
if (parser->object) {
zval_ptr_dtor(&parser->object);
}
efree(parser);
}
| 165,047 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xscale1pmu_handle_irq(int irq_num, void *dev)
{
unsigned long pmnc;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
/*
* NOTE: there's an A stepping erratum that states if an overflow
* bit already exists and another occurs, the previous
* Overflow bit gets cleared. There's no workaround.
* Fixed in B stepping or later.
*/
pmnc = xscale1pmu_read_pmnc();
/*
* Write the value back to clear the overflow flags. Overflow
* flags remain in pmnc for use below. We also disable the PMU
* while we process the interrupt.
*/
xscale1pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE);
if (!(pmnc & XSCALE1_OVERFLOWED_MASK))
return IRQ_NONE;
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx <= armpmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
if (!test_bit(idx, cpuc->active_mask))
continue;
if (!xscale1_pmnc_counter_has_overflowed(pmnc, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 0, &data, regs))
armpmu->disable(hwc, idx);
}
irq_work_run();
/*
* Re-enable the PMU.
*/
pmnc = xscale1pmu_read_pmnc() | XSCALE_PMU_ENABLE;
xscale1pmu_write_pmnc(pmnc);
return IRQ_HANDLED;
}
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 | xscale1pmu_handle_irq(int irq_num, void *dev)
{
unsigned long pmnc;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
/*
* NOTE: there's an A stepping erratum that states if an overflow
* bit already exists and another occurs, the previous
* Overflow bit gets cleared. There's no workaround.
* Fixed in B stepping or later.
*/
pmnc = xscale1pmu_read_pmnc();
/*
* Write the value back to clear the overflow flags. Overflow
* flags remain in pmnc for use below. We also disable the PMU
* while we process the interrupt.
*/
xscale1pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE);
if (!(pmnc & XSCALE1_OVERFLOWED_MASK))
return IRQ_NONE;
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx <= armpmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
if (!test_bit(idx, cpuc->active_mask))
continue;
if (!xscale1_pmnc_counter_has_overflowed(pmnc, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, &data, regs))
armpmu->disable(hwc, idx);
}
irq_work_run();
/*
* Re-enable the PMU.
*/
pmnc = xscale1pmu_read_pmnc() | XSCALE_PMU_ENABLE;
xscale1pmu_write_pmnc(pmnc);
return IRQ_HANDLED;
}
| 165,775 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
xhci_kick_epctx(epctx, streamid);
}
Commit Message:
CWE ID: CWE-835 | static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
if (epctx->kick_active) {
return;
}
xhci_kick_epctx(epctx, streamid);
}
| 164,795 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
int
status,
unique_file;
ssize_t
n;
SVGInfo
*svg_info;
unsigned char
message[MaxTextExtent];
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
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 ((image->x_resolution < MagickEpsilon) ||
(image->y_resolution < MagickEpsilon))
{
GeometryInfo
geometry_info;
int
flags;
flags=ParseGeometry(SVGDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
if (LocaleCompare(image_info->magick,"MSVG") != 0)
{
const DelegateInfo
*delegate_info;
delegate_info=GetDelegateInfo("svg:decode",(char *) NULL,exception);
if (delegate_info != (const DelegateInfo *) NULL)
{
char
background[MaxTextExtent],
command[MaxTextExtent],
density[MaxTextExtent],
input_filename[MaxTextExtent],
opacity[MaxTextExtent],
output_filename[MaxTextExtent],
unique[MaxTextExtent];
int
status;
struct stat
attributes;
/*
Our best hope for compliance to the SVG standard.
*/
status=AcquireUniqueSymbolicLink(image->filename,input_filename);
(void) AcquireUniqueFilename(output_filename);
(void) AcquireUniqueFilename(unique);
(void) FormatLocaleString(density,MaxTextExtent,"%.20g,%.20g",
image->x_resolution,image->y_resolution);
(void) FormatLocaleString(background,MaxTextExtent,
"rgb(%.20g%%,%.20g%%,%.20g%%)",
100.0*QuantumScale*image->background_color.red,
100.0*QuantumScale*image->background_color.green,
100.0*QuantumScale*image->background_color.blue);
(void) FormatLocaleString(opacity,MaxTextExtent,"%.20g",QuantumScale*
(QuantumRange-image->background_color.opacity));
(void) FormatLocaleString(command,MaxTextExtent,GetDelegateCommands(
delegate_info),input_filename,output_filename,density,background,
opacity,unique);
status=ExternalDelegateCommand(MagickFalse,image_info->verbose,
command,(char *) NULL,exception);
(void) RelinquishUniqueFileResource(unique);
(void) RelinquishUniqueFileResource(input_filename);
if ((status == 0) && (stat(output_filename,&attributes) == 0) &&
(attributes.st_size != 0))
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->filename,output_filename,
MaxTextExtent);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(output_filename);
if (image != (Image *) NULL)
return(image);
}
(void) RelinquishUniqueFileResource(output_filename);
}
{
#if defined(MAGICKCORE_RSVG_DELEGATE)
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface_t
*cairo_surface;
cairo_t
*cairo_image;
MemoryInfo
*pixel_info;
register unsigned char
*p;
RsvgDimensionData
dimension_info;
unsigned char
*pixels;
#else
GdkPixbuf
*pixel_buffer;
register const guchar
*p;
#endif
GError
*error;
ssize_t
y;
PixelPacket
fill_color;
register ssize_t
x;
register PixelPacket
*q;
RsvgHandle
*svg_handle;
svg_handle=rsvg_handle_new();
if (svg_handle == (RsvgHandle *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
rsvg_handle_set_base_uri(svg_handle,image_info->filename);
if ((image->x_resolution != 90.0) && (image->y_resolution != 90.0))
rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution,
image->y_resolution);
while ((n=ReadBlob(image,MaxTextExtent,message)) != 0)
{
error=(GError *) NULL;
(void) rsvg_handle_write(svg_handle,message,n,&error);
if (error != (GError *) NULL)
g_error_free(error);
}
error=(GError *) NULL;
rsvg_handle_close(svg_handle,&error);
if (error != (GError *) NULL)
g_error_free(error);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
rsvg_handle_get_dimensions(svg_handle,&dimension_info);
image->columns=image->x_resolution*dimension_info.width/90.0;
image->rows=image->y_resolution*dimension_info.height/90.0;
pixel_info=(MemoryInfo *) NULL;
#else
pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);
rsvg_handle_free(svg_handle);
image->columns=gdk_pixbuf_get_width(pixel_buffer);
image->rows=gdk_pixbuf_get_height(pixel_buffer);
#endif
image->matte=MagickTrue;
SetImageProperty(image,"svg:base-uri",
rsvg_handle_get_base_uri(svg_handle));
if ((image->columns == 0) || (image->rows == 0))
{
#if !defined(MAGICKCORE_CAIRO_DELEGATE)
g_object_unref(G_OBJECT(pixel_buffer));
#endif
g_object_unref(svg_handle);
ThrowReaderException(MissingDelegateError,
"NoDecodeDelegateForThisImageFormat");
}
if (image_info->ping == MagickFalse)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
size_t
stride;
stride=4*image->columns;
#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
(int) image->columns);
#endif
pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
#endif
(void) SetImageBackgroundColor(image);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface=cairo_image_surface_create_for_data(pixels,
CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows, (int)
stride);
if (cairo_surface == (cairo_surface_t *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
cairo_image=cairo_create(cairo_surface);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);
cairo_paint(cairo_image);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);
cairo_scale(cairo_image,image->x_resolution/90.0,
image->y_resolution/90.0);
rsvg_handle_render_cairo(svg_handle,cairo_image);
cairo_destroy(cairo_image);
cairo_surface_destroy(cairo_surface);
g_object_unref(svg_handle);
p=pixels;
#else
p=gdk_pixbuf_get_pixels(pixel_buffer);
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
fill_color.blue=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.red=ScaleCharToQuantum(*p++);
#else
fill_color.red=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.blue=ScaleCharToQuantum(*p++);
#endif
fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
{
double
gamma;
gamma=1.0-QuantumScale*fill_color.opacity;
gamma=PerceptibleReciprocal(gamma);
fill_color.blue*=gamma;
fill_color.green*=gamma;
fill_color.red*=gamma;
}
#endif
MagickCompositeOver(&fill_color,fill_color.opacity,q,
(MagickRealType) q->opacity,q);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
#if defined(MAGICKCORE_CAIRO_DELEGATE)
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
#else
g_object_unref(G_OBJECT(pixel_buffer));
#endif
(void) CloseBlob(image);
return(GetFirstImageInList(image));
#endif
}
}
/*
Open draw file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"w");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Parse SVG file.
*/
if (image == (Image *) NULL)
return((Image *) NULL);
svg_info=AcquireSVGInfo();
if (svg_info == (SVGInfo *) NULL)
{
(void) fclose(file);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
svg_info->file=file;
svg_info->exception=exception;
svg_info->image=image;
svg_info->image_info=image_info;
svg_info->bounds.width=image->columns;
svg_info->bounds.height=image->rows;
if (image_info->size != (char *) NULL)
(void) CloneString(&svg_info->size,image_info->size);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX");
(void) xmlSubstituteEntitiesDefault(1);
(void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=SVGInternalSubset;
sax_modules.isStandalone=SVGIsStandalone;
sax_modules.hasInternalSubset=SVGHasInternalSubset;
sax_modules.hasExternalSubset=SVGHasExternalSubset;
sax_modules.resolveEntity=SVGResolveEntity;
sax_modules.getEntity=SVGGetEntity;
sax_modules.entityDecl=SVGEntityDeclaration;
sax_modules.notationDecl=SVGNotationDeclaration;
sax_modules.attributeDecl=SVGAttributeDeclaration;
sax_modules.elementDecl=SVGElementDeclaration;
sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=SVGSetDocumentLocator;
sax_modules.startDocument=SVGStartDocument;
sax_modules.endDocument=SVGEndDocument;
sax_modules.startElement=SVGStartElement;
sax_modules.endElement=SVGEndElement;
sax_modules.reference=SVGReference;
sax_modules.characters=SVGCharacters;
sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;
sax_modules.processingInstruction=SVGProcessingInstructions;
sax_modules.comment=SVGComment;
sax_modules.warning=SVGWarning;
sax_modules.error=SVGError;
sax_modules.fatalError=SVGError;
sax_modules.getParameterEntity=SVGGetParameterEntity;
sax_modules.cdataBlock=SVGCDataBlock;
sax_modules.externalSubset=SVGExternalSubset;
sax_handler=(&sax_modules);
n=ReadBlob(image,MaxTextExtent,message);
if (n > 0)
{
svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)
message,n,image->filename);
while ((n=ReadBlob(image,MaxTextExtent,message)) != 0)
{
status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);
if (status != 0)
break;
}
}
(void) xmlParseChunk(svg_info->parser,(char *) message,0,1);
xmlFreeParserCtxt(svg_info->parser);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
(void) fclose(file);
(void) CloseBlob(image);
image->columns=svg_info->width;
image->rows=svg_info->height;
if (exception->severity >= ErrorException)
{
image=DestroyImage(image);
return((Image *) NULL);
}
if (image_info->ping == MagickFalse)
{
ImageInfo
*read_info;
/*
Draw image.
*/
image=DestroyImage(image);
image=(Image *) NULL;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
if (read_info->density != (char *) NULL)
read_info->density=DestroyString(read_info->density);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"mvg:%s",
filename);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
}
/*
Relinquish resources.
*/
if (image != (Image *) NULL)
{
if (svg_info->title != (char *) NULL)
(void) SetImageProperty(image,"svg:title",svg_info->title);
if (svg_info->comment != (char *) NULL)
(void) SetImageProperty(image,"svg:comment",svg_info->comment);
}
svg_info=DestroySVGInfo(svg_info);
(void) RelinquishUniqueFileResource(filename);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
int
status,
unique_file;
ssize_t
n;
SVGInfo
*svg_info;
unsigned char
message[MaxTextExtent];
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
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 ((image->x_resolution < MagickEpsilon) ||
(image->y_resolution < MagickEpsilon))
{
GeometryInfo
geometry_info;
int
flags;
flags=ParseGeometry(SVGDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
if (LocaleCompare(image_info->magick,"MSVG") != 0)
{
const DelegateInfo
*delegate_info;
delegate_info=GetDelegateInfo("svg:decode",(char *) NULL,exception);
if (delegate_info != (const DelegateInfo *) NULL)
{
char
background[MaxTextExtent],
command[MaxTextExtent],
density[MaxTextExtent],
input_filename[MaxTextExtent],
opacity[MaxTextExtent],
output_filename[MaxTextExtent],
unique[MaxTextExtent];
int
status;
struct stat
attributes;
/*
Our best hope for compliance to the SVG standard.
*/
status=AcquireUniqueSymbolicLink(image->filename,input_filename);
(void) AcquireUniqueFilename(output_filename);
(void) AcquireUniqueFilename(unique);
(void) FormatLocaleString(density,MaxTextExtent,"%.20g,%.20g",
image->x_resolution,image->y_resolution);
(void) FormatLocaleString(background,MaxTextExtent,
"rgb(%.20g%%,%.20g%%,%.20g%%)",
100.0*QuantumScale*image->background_color.red,
100.0*QuantumScale*image->background_color.green,
100.0*QuantumScale*image->background_color.blue);
(void) FormatLocaleString(opacity,MaxTextExtent,"%.20g",QuantumScale*
(QuantumRange-image->background_color.opacity));
(void) FormatLocaleString(command,MaxTextExtent,GetDelegateCommands(
delegate_info),input_filename,output_filename,density,background,
opacity,unique);
status=ExternalDelegateCommand(MagickFalse,image_info->verbose,
command,(char *) NULL,exception);
(void) RelinquishUniqueFileResource(unique);
(void) RelinquishUniqueFileResource(input_filename);
if ((status == 0) && (stat(output_filename,&attributes) == 0) &&
(attributes.st_size != 0))
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->filename,output_filename,
MaxTextExtent);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(output_filename);
if (image != (Image *) NULL)
return(image);
}
(void) RelinquishUniqueFileResource(output_filename);
}
{
#if defined(MAGICKCORE_RSVG_DELEGATE)
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface_t
*cairo_surface;
cairo_t
*cairo_image;
MemoryInfo
*pixel_info;
register unsigned char
*p;
RsvgDimensionData
dimension_info;
unsigned char
*pixels;
#else
GdkPixbuf
*pixel_buffer;
register const guchar
*p;
#endif
GError
*error;
ssize_t
y;
PixelPacket
fill_color;
register ssize_t
x;
register PixelPacket
*q;
RsvgHandle
*svg_handle;
svg_handle=rsvg_handle_new();
if (svg_handle == (RsvgHandle *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
rsvg_handle_set_base_uri(svg_handle,image_info->filename);
if ((image->x_resolution != 90.0) && (image->y_resolution != 90.0))
rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution,
image->y_resolution);
while ((n=ReadBlob(image,MaxTextExtent,message)) != 0)
{
error=(GError *) NULL;
(void) rsvg_handle_write(svg_handle,message,n,&error);
if (error != (GError *) NULL)
g_error_free(error);
}
error=(GError *) NULL;
rsvg_handle_close(svg_handle,&error);
if (error != (GError *) NULL)
g_error_free(error);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
rsvg_handle_get_dimensions(svg_handle,&dimension_info);
image->columns=image->x_resolution*dimension_info.width/90.0;
image->rows=image->y_resolution*dimension_info.height/90.0;
pixel_info=(MemoryInfo *) NULL;
#else
pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);
rsvg_handle_free(svg_handle);
image->columns=gdk_pixbuf_get_width(pixel_buffer);
image->rows=gdk_pixbuf_get_height(pixel_buffer);
#endif
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->matte=MagickTrue;
SetImageProperty(image,"svg:base-uri",
rsvg_handle_get_base_uri(svg_handle));
if ((image->columns == 0) || (image->rows == 0))
{
#if !defined(MAGICKCORE_CAIRO_DELEGATE)
g_object_unref(G_OBJECT(pixel_buffer));
#endif
g_object_unref(svg_handle);
ThrowReaderException(MissingDelegateError,
"NoDecodeDelegateForThisImageFormat");
}
if (image_info->ping == MagickFalse)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
size_t
stride;
stride=4*image->columns;
#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
(int) image->columns);
#endif
pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
#endif
(void) SetImageBackgroundColor(image);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
cairo_surface=cairo_image_surface_create_for_data(pixels,
CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows, (int)
stride);
if (cairo_surface == (cairo_surface_t *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
g_object_unref(svg_handle);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
cairo_image=cairo_create(cairo_surface);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);
cairo_paint(cairo_image);
cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);
cairo_scale(cairo_image,image->x_resolution/90.0,
image->y_resolution/90.0);
rsvg_handle_render_cairo(svg_handle,cairo_image);
cairo_destroy(cairo_image);
cairo_surface_destroy(cairo_surface);
g_object_unref(svg_handle);
p=pixels;
#else
p=gdk_pixbuf_get_pixels(pixel_buffer);
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
#if defined(MAGICKCORE_CAIRO_DELEGATE)
fill_color.blue=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.red=ScaleCharToQuantum(*p++);
#else
fill_color.red=ScaleCharToQuantum(*p++);
fill_color.green=ScaleCharToQuantum(*p++);
fill_color.blue=ScaleCharToQuantum(*p++);
#endif
fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++);
#if defined(MAGICKCORE_CAIRO_DELEGATE)
{
double
gamma;
gamma=1.0-QuantumScale*fill_color.opacity;
gamma=PerceptibleReciprocal(gamma);
fill_color.blue*=gamma;
fill_color.green*=gamma;
fill_color.red*=gamma;
}
#endif
MagickCompositeOver(&fill_color,fill_color.opacity,q,
(MagickRealType) q->opacity,q);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
#if defined(MAGICKCORE_CAIRO_DELEGATE)
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
#else
g_object_unref(G_OBJECT(pixel_buffer));
#endif
(void) CloseBlob(image);
return(GetFirstImageInList(image));
#endif
}
}
/*
Open draw file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"w");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Parse SVG file.
*/
if (image == (Image *) NULL)
return((Image *) NULL);
svg_info=AcquireSVGInfo();
if (svg_info == (SVGInfo *) NULL)
{
(void) fclose(file);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
svg_info->file=file;
svg_info->exception=exception;
svg_info->image=image;
svg_info->image_info=image_info;
svg_info->bounds.width=image->columns;
svg_info->bounds.height=image->rows;
if (image_info->size != (char *) NULL)
(void) CloneString(&svg_info->size,image_info->size);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX");
(void) xmlSubstituteEntitiesDefault(1);
(void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=SVGInternalSubset;
sax_modules.isStandalone=SVGIsStandalone;
sax_modules.hasInternalSubset=SVGHasInternalSubset;
sax_modules.hasExternalSubset=SVGHasExternalSubset;
sax_modules.resolveEntity=SVGResolveEntity;
sax_modules.getEntity=SVGGetEntity;
sax_modules.entityDecl=SVGEntityDeclaration;
sax_modules.notationDecl=SVGNotationDeclaration;
sax_modules.attributeDecl=SVGAttributeDeclaration;
sax_modules.elementDecl=SVGElementDeclaration;
sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=SVGSetDocumentLocator;
sax_modules.startDocument=SVGStartDocument;
sax_modules.endDocument=SVGEndDocument;
sax_modules.startElement=SVGStartElement;
sax_modules.endElement=SVGEndElement;
sax_modules.reference=SVGReference;
sax_modules.characters=SVGCharacters;
sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;
sax_modules.processingInstruction=SVGProcessingInstructions;
sax_modules.comment=SVGComment;
sax_modules.warning=SVGWarning;
sax_modules.error=SVGError;
sax_modules.fatalError=SVGError;
sax_modules.getParameterEntity=SVGGetParameterEntity;
sax_modules.cdataBlock=SVGCDataBlock;
sax_modules.externalSubset=SVGExternalSubset;
sax_handler=(&sax_modules);
n=ReadBlob(image,MaxTextExtent,message);
if (n > 0)
{
svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)
message,n,image->filename);
while ((n=ReadBlob(image,MaxTextExtent,message)) != 0)
{
status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);
if (status != 0)
break;
}
}
(void) xmlParseChunk(svg_info->parser,(char *) message,0,1);
xmlFreeParserCtxt(svg_info->parser);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
(void) fclose(file);
(void) CloseBlob(image);
image->columns=svg_info->width;
image->rows=svg_info->height;
if (exception->severity >= ErrorException)
{
image=DestroyImage(image);
return((Image *) NULL);
}
if (image_info->ping == MagickFalse)
{
ImageInfo
*read_info;
/*
Draw image.
*/
image=DestroyImage(image);
image=(Image *) NULL;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
if (read_info->density != (char *) NULL)
read_info->density=DestroyString(read_info->density);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"mvg:%s",
filename);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
}
/*
Relinquish resources.
*/
if (image != (Image *) NULL)
{
if (svg_info->title != (char *) NULL)
(void) SetImageProperty(image,"svg:title",svg_info->title);
if (svg_info->comment != (char *) NULL)
(void) SetImageProperty(image,"svg:comment",svg_info->comment);
}
svg_info=DestroySVGInfo(svg_info);
(void) RelinquishUniqueFileResource(filename);
return(GetFirstImageInList(image));
}
| 168,607 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
Commit Message: ...
CWE ID: CWE-119 | static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
| 169,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
base::SharedMemory shared_memory(transfer_buffer, false);
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
uint32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
base::SharedMemory shared_memory(transfer_buffer, false);
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 171,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice,
UWORD8 u1_nal_ref_idc,
dec_struct_t *ps_dec /* Decoder parameters */
)
{
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
dec_pic_params_t *ps_pps;
dec_seq_params_t *ps_seq;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
pocstruct_t s_tmp_poc;
WORD32 i_delta_poc[2];
WORD32 i4_poc = 0;
UWORD16 u2_first_mb_in_slice, u2_frame_num;
UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type;
UWORD32 u4_idr_pic_id = 0;
UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type;
UWORD8 u1_nal_unit_type;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
WORD8 i1_is_end_of_poc;
WORD32 ret, end_of_frame;
WORD32 prev_slice_err, num_mb_skipped;
UWORD8 u1_mbaff;
pocstruct_t *ps_cur_poc;
UWORD32 u4_temp;
WORD32 i_temp;
UWORD32 u4_call_end_of_pic = 0;
/* read FirstMbInSlice and slice type*/
ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0;
u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u2_first_mb_in_slice
> (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs))
{
return ERROR_CORRUPTED_SLICE;
}
/*we currently don not support ASO*/
if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag)
<= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0)
&& (ps_dec->u4_first_slice_in_pic != 0))
{
return ERROR_CORRUPTED_SLICE;
}
COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice);
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > 9)
return ERROR_INV_SLC_TYPE_T;
u1_slice_type = u4_temp;
COPYTHECONTEXT("SH: slice_type",(u1_slice_type));
ps_dec->u1_sl_typ_5_9 = 0;
/* Find Out the Slice Type is 5 to 9 or not then Set the Flag */
/* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/
/* will be of same type of current */
if(u1_slice_type > 4)
{
u1_slice_type -= 5;
ps_dec->u1_sl_typ_5_9 = 1;
}
{
UWORD32 skip;
if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB)
|| (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB))
{
UWORD32 u4_bit_stream_offset = 0;
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else if((I_SLICE == u1_slice_type)
&& (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames))
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else
{
skip = 1;
}
/* If one frame worth of data is already skipped, do not skip the next one */
if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped))
{
skip = 0;
}
if(skip)
{
ps_dec->u4_prev_nal_skipped = 1;
ps_dec->i4_dec_skip_mode = IVD_SKIP_PB;
return 0;
}
else
{
/* If the previous NAL was skipped, then
do not process that buffer in this call.
Return to app and process it in the next call.
This is necessary to handle cases where I/IDR is not complete in
the current buffer and application intends to fill the remaining part of the bitstream
later. This ensures we process only frame worth of data in every call */
if(1 == ps_dec->u4_prev_nal_skipped)
{
ps_dec->u4_return_to_app = 1;
return 0;
}
}
}
}
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp & MASK_ERR_PIC_SET_ID)
return ERROR_INV_SPS_PPS_T;
/* discard slice if pic param is invalid */
COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp);
ps_pps = &ps_dec->ps_pps[u4_temp];
if(FALSE == ps_pps->u1_is_valid)
{
return ERROR_INV_SPS_PPS_T;
}
ps_seq = ps_pps->ps_sps;
if(!ps_seq)
return ERROR_INV_SPS_PPS_T;
if(FALSE == ps_seq->u1_is_valid)
return ERROR_INV_SPS_PPS_T;
/* Get the frame num */
u2_frame_num = ih264d_get_bits_h264(ps_bitstrm,
ps_seq->u1_bits_in_frm_num);
COPYTHECONTEXT("SH: frame_num", u2_frame_num);
/* Get the field related flags */
if(!ps_seq->u1_frame_mbs_only_flag)
{
u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag);
u1_bottom_field_flag = 0;
if(u1_field_pic_flag)
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld;
u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag);
}
else
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
}
else
{
u1_field_pic_flag = 0;
u1_bottom_field_flag = 0;
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
u1_nal_unit_type = SLICE_NAL;
if(u1_is_idr_slice)
{
if(0 == u1_field_pic_flag)
{
ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY;
}
u1_nal_unit_type = IDR_SLICE_NAL;
u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u4_idr_pic_id > 65535)
return ERROR_INV_SPS_PPS_T;
COPYTHECONTEXT("SH: ", u4_idr_pic_id);
}
/* read delta pic order count information*/
i_delta_poc[0] = i_delta_poc[1] = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type;
if(u1_pic_order_cnt_type == 0)
{
i_temp = ih264d_get_bits_h264(
ps_bitstrm,
ps_seq->u1_log2_max_pic_order_cnt_lsb_minus);
if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb)
return ERROR_INV_SPS_PPS_T;
s_tmp_poc.i4_pic_order_cnt_lsb = i_temp;
COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb);
if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom",
s_tmp_poc.i4_delta_pic_order_cnt_bottom);
}
}
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
if(u1_pic_order_cnt_type == 1
&& (!ps_seq->u1_delta_pic_order_always_zero_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[0]",
s_tmp_poc.i4_delta_pic_order_cnt[0]);
if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag)
{
s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[1]",
s_tmp_poc.i4_delta_pic_order_cnt[1]);
}
}
if(ps_pps->u1_redundant_pic_cnt_present_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_REDUNDANT_PIC_CNT)
return ERROR_INV_SPS_PPS_T;
u1_redundant_pic_cnt = u4_temp;
COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt);
}
/*--------------------------------------------------------------------*/
/* Check if the slice is part of new picture */
/*--------------------------------------------------------------------*/
i1_is_end_of_poc = 0;
if(!ps_dec->u1_first_slice_in_stream)
{
i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc,
&s_tmp_poc, &ps_dec->s_cur_pic_poc,
ps_cur_slice, u1_pic_order_cnt_type,
u1_nal_unit_type, u4_idr_pic_id,
u1_field_pic_flag,
u1_bottom_field_flag);
/* since we support only Full frame decode, every new process should
* process a new pic
*/
if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0))
{
/* if it is the first slice is process call ,it should be a new frame. If it is not
* reject current pic and dont add it to dpb
*/
ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC;
i1_is_end_of_poc = 1;
}
else
{
/* reset REJECT_CUR_PIC */
ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC;
}
}
/*--------------------------------------------------------------------*/
/* Check for error in slice and parse the missing/corrupted MB's */
/* as skip-MB's in an inserted P-slice */
/*--------------------------------------------------------------------*/
u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag);
prev_slice_err = 0;
if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream)
{
if(u2_frame_num != ps_dec->u2_prv_frame_num
&& ps_dec->u1_top_bottom_decoded != 0
&& ps_dec->u1_top_bottom_decoded
!= (TOP_FIELD_ONLY | BOT_FIELD_ONLY))
{
ps_dec->u1_dangling_field = 1;
if(ps_dec->u4_first_slice_in_pic)
{
prev_slice_err = 1;
}
else
{
prev_slice_err = 2;
}
if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY)
ps_cur_slice->u1_bottom_field_flag = 1;
else
ps_cur_slice->u1_bottom_field_flag = 0;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL;
}
else if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice > 0)
{
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
ps_cur_poc = &s_tmp_poc;
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->i4_pic_order_cnt_lsb =
s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
}
}
else
{
if(ps_dec->u4_first_slice_in_pic)
{
/* if valid slice header is not decoded do start of pic processing
* since in the current process call, frame num is not updated in the slice structure yet
* ih264d_is_end_of_pic is checked with valid frame num of previous process call,
* although i1_is_end_of_poc is set there could be more slices in the frame,
* so conceal only till cur slice */
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
}
else
{
/* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame
* completely */
prev_slice_err = 2;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
}
ps_cur_poc = &s_tmp_poc;
}
}
else
{
if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded)
{
prev_slice_err = 2;
num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &s_tmp_poc;
}
else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded)
{
return ERROR_CORRUPTED_SLICE;
}
}
if(prev_slice_err)
{
ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err);
if(ps_dec->u1_dangling_field == 1)
{
ps_dec->u1_second_field = 1 - ps_dec->u1_second_field;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_dec->u2_prv_frame_num = u2_frame_num;
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_DANGLING_FIELD_IN_PIC;
}
if(prev_slice_err == 2)
{
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_INCOMPLETE_FRAME;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
/* return if all MBs in frame are parsed*/
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_IN_LAST_SLICE_OF_PIC;
}
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
if(ret != OK)
return ret;
i1_is_end_of_poc = 0;
}
if (ps_dec->u4_first_slice_in_pic == 0)
ps_dec->ps_parse_cur_slice++;
ps_dec->u1_slice_header_done = 0;
/*--------------------------------------------------------------------*/
/* If the slice is part of new picture, do End of Pic processing. */
/*--------------------------------------------------------------------*/
if(!ps_dec->u1_first_slice_in_stream)
{
UWORD8 uc_mbs_exceed = 0;
if(ps_dec->u2_total_mbs_coded
== (ps_dec->ps_cur_sps->u2_max_mb_addr + 1))
{
/*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so
,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */
if(ps_dec->u4_first_slice_in_pic == 0)
uc_mbs_exceed = 1;
}
if(i1_is_end_of_poc || uc_mbs_exceed)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
#if WIN32
H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n");
#endif
return RET_LAST_SKIP;
}
else
{
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
}
}
}
if(u1_field_pic_flag)
{
ps_dec->u2_prv_frame_num = u2_frame_num;
}
if(ps_cur_slice->u1_mmco_equalto5)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair
{
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc =
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
}
else if(!ps_cur_slice->u1_bottom_field_flag)
i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
else
i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_poc = i4_temp_poc;
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice, ps_pps,
u1_nal_ref_idc,
u1_bottom_field_flag,
u1_field_pic_flag, &i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering + 1;
ps_dec->i4_max_poc = 0;
}
}
/*--------------------------------------------------------------------*/
/* Copy the values read from the bitstream to the slice header and then*/
/* If the slice is first slice in picture, then do Start of Picture */
/* processing. */
/*--------------------------------------------------------------------*/
ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0];
ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1];
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->u1_slice_type = u1_slice_type;
ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
if(ps_seq->u1_frame_mbs_only_flag)
ps_cur_slice->u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
else
ps_cur_slice->u1_direct_8x8_inference_flag = 1;
if(u1_slice_type == B_SLICE)
{
ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag",
ps_cur_slice->u1_direct_spatial_mv_pred_flag);
if(ps_cur_slice->u1_direct_spatial_mv_pred_flag)
ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct;
else
ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct;
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB;
}
else
{
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice == 0)
{
ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps);
if(ret != OK)
return ret;
}
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
/* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */
{
UWORD8 uc_nofield_nombaff;
uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0)
&& (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0)
&& (u1_slice_type != B_SLICE)
&& (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0));
/* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */
if(uc_nofield_nombaff)
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
}
else
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_mp;
}
}
/*
* Decide whether to decode the current picture or not
*/
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u4_frm_sei_sync == u2_frame_num)
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
}
ps_err->u4_cur_frm = u2_frame_num;
}
/* Decision for decoding if the picture is to be skipped */
{
WORD32 i4_skip_b_pic, i4_skip_p_pic;
i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT)
&& (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT)
&& (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
/**************************************************************/
/* Skip the B picture if skip mask is set for B picture and */
/* Current B picture is a non reference B picture or there is */
/* no user for reference B picture */
/**************************************************************/
if(i4_skip_b_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
/* Don't decode the picture in SKIP-B mode if that picture is B */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
/**************************************************************/
/* Skip the P picture if skip mask is set for P picture and */
/* Current P picture is a non reference P picture or there is */
/* no user for reference P picture */
/**************************************************************/
if(i4_skip_p_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
/* Don't decode the picture in SKIP-P mode if that picture is P */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
}
{
UWORD16 u2_mb_x, u2_mb_y;
ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice
<< ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE)
- SUB_BLK_SIZE;
if(u2_first_mb_in_slice)
{
UWORD8 u1_mb_aff;
UWORD8 u1_field_pic;
UWORD16 u2_frm_wd_in_mbs;
u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag;
u1_field_pic = ps_cur_slice->u1_field_pic_flag;
{
UWORD32 x_offset;
UWORD32 y_offset;
UWORD32 u4_frame_stride;
tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y <<= u1_mb_aff;
if((u2_mb_x > u2_frm_wd_in_mbs - 1)
|| (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1))
{
return ERROR_CORRUPTED_SLICE;
}
u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic;
x_offset = u2_mb_x << 4;
y_offset = (u2_mb_y * u4_frame_stride) << 4;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset
+ y_offset;
u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic;
x_offset >>= 1;
y_offset = (u2_mb_y * u4_frame_stride) << 3;
x_offset *= YUV420SP_FACTOR;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset
+ y_offset;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset
+ y_offset;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
if(ps_dec->u1_separate_parse == 1)
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
else
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff);
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv
+ ((u2_first_mb_in_slice << u1_mb_aff) << 4);
}
}
else
{
tfr_ctxt_t *ps_trns_addr;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = 0xffff;
u2_mb_y = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
}
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
}
/* RBSP stop bit is used for CABAC decoding*/
ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode;
ps_dec->u1_B = (u1_slice_type == B_SLICE);
ps_dec->u4_next_mb_skip = 0;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice =
ps_dec->ps_cur_slice->u2_first_mb_in_slice;
ps_dec->ps_parse_cur_slice->slice_type =
ps_dec->ps_cur_slice->u1_slice_type;
ps_dec->u4_start_recon_deblk = 1;
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MAX_FRAMES;
if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) &&
(0 == ps_dec->i4_display_delay))
{
num_entries = 1;
}
num_entries = ((2 * num_entries) + 1);
if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc)
{
num_entries *= 2;
}
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf;
}
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
if(u1_slice_type == I_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT;
ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice);
if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE)
ps_dec->i4_pic_type = I_SLICE;
}
else if(u1_slice_type == P_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
if(ps_dec->i4_pic_type != B_SLICE)
ps_dec->i4_pic_type = P_SLICE;
}
else if(u1_slice_type == B_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
ps_dec->i4_pic_type = B_SLICE;
}
else
return ERROR_INV_SLC_TYPE_T;
if(ps_dec->u1_slice_header_done)
{
/* set to zero to indicate a valid slice has been decoded */
/* first slice header successfully decoded */
ps_dec->u4_first_slice_in_pic = 0;
ps_dec->u1_first_slice_in_stream = 0;
}
if(ret != OK)
return ret;
ps_dec->u2_cur_slice_num++;
/* storing last Mb X and MbY of the slice */
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
/* End of Picture detection */
if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1))
{
ps_dec->u1_pic_decode_done = 1;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if((ps_err->u1_err_flag & REJECT_PB_PICS)
&& (ps_err->u1_cur_pic_type == PIC_TYPE_I))
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
PRINT_BIN_BIT_RATIO(ps_dec)
return ret;
}
Commit Message: Decoder: Initialize slice parameters before concealing error MBs
Also memset ps_dec_op structure to zero.
For error input, this ensures dimensions are initialized to zero
Bug: 28165661
Change-Id: I66eb2ddc5e02e74b7ff04da5f749443920f37141
CWE ID: CWE-20 | WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice,
UWORD8 u1_nal_ref_idc,
dec_struct_t *ps_dec /* Decoder parameters */
)
{
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
dec_pic_params_t *ps_pps;
dec_seq_params_t *ps_seq;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
pocstruct_t s_tmp_poc;
WORD32 i_delta_poc[2];
WORD32 i4_poc = 0;
UWORD16 u2_first_mb_in_slice, u2_frame_num;
UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type;
UWORD32 u4_idr_pic_id = 0;
UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type;
UWORD8 u1_nal_unit_type;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
WORD8 i1_is_end_of_poc;
WORD32 ret, end_of_frame;
WORD32 prev_slice_err, num_mb_skipped;
UWORD8 u1_mbaff;
pocstruct_t *ps_cur_poc;
UWORD32 u4_temp;
WORD32 i_temp;
UWORD32 u4_call_end_of_pic = 0;
/* read FirstMbInSlice and slice type*/
ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0;
u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u2_first_mb_in_slice
> (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs))
{
return ERROR_CORRUPTED_SLICE;
}
/*we currently don not support ASO*/
if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag)
<= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0)
&& (ps_dec->u4_first_slice_in_pic != 0))
{
return ERROR_CORRUPTED_SLICE;
}
COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice);
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > 9)
return ERROR_INV_SLC_TYPE_T;
u1_slice_type = u4_temp;
COPYTHECONTEXT("SH: slice_type",(u1_slice_type));
ps_dec->u1_sl_typ_5_9 = 0;
/* Find Out the Slice Type is 5 to 9 or not then Set the Flag */
/* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/
/* will be of same type of current */
if(u1_slice_type > 4)
{
u1_slice_type -= 5;
ps_dec->u1_sl_typ_5_9 = 1;
}
{
UWORD32 skip;
if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB)
|| (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB))
{
UWORD32 u4_bit_stream_offset = 0;
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else if((I_SLICE == u1_slice_type)
&& (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames))
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else
{
skip = 1;
}
/* If one frame worth of data is already skipped, do not skip the next one */
if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped))
{
skip = 0;
}
if(skip)
{
ps_dec->u4_prev_nal_skipped = 1;
ps_dec->i4_dec_skip_mode = IVD_SKIP_PB;
return 0;
}
else
{
/* If the previous NAL was skipped, then
do not process that buffer in this call.
Return to app and process it in the next call.
This is necessary to handle cases where I/IDR is not complete in
the current buffer and application intends to fill the remaining part of the bitstream
later. This ensures we process only frame worth of data in every call */
if(1 == ps_dec->u4_prev_nal_skipped)
{
ps_dec->u4_return_to_app = 1;
return 0;
}
}
}
}
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp & MASK_ERR_PIC_SET_ID)
return ERROR_INV_SPS_PPS_T;
/* discard slice if pic param is invalid */
COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp);
ps_pps = &ps_dec->ps_pps[u4_temp];
if(FALSE == ps_pps->u1_is_valid)
{
return ERROR_INV_SPS_PPS_T;
}
ps_seq = ps_pps->ps_sps;
if(!ps_seq)
return ERROR_INV_SPS_PPS_T;
if(FALSE == ps_seq->u1_is_valid)
return ERROR_INV_SPS_PPS_T;
/* Get the frame num */
u2_frame_num = ih264d_get_bits_h264(ps_bitstrm,
ps_seq->u1_bits_in_frm_num);
COPYTHECONTEXT("SH: frame_num", u2_frame_num);
/* Get the field related flags */
if(!ps_seq->u1_frame_mbs_only_flag)
{
u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag);
u1_bottom_field_flag = 0;
if(u1_field_pic_flag)
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld;
u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag);
}
else
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
}
else
{
u1_field_pic_flag = 0;
u1_bottom_field_flag = 0;
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
u1_nal_unit_type = SLICE_NAL;
if(u1_is_idr_slice)
{
if(0 == u1_field_pic_flag)
{
ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY;
}
u1_nal_unit_type = IDR_SLICE_NAL;
u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u4_idr_pic_id > 65535)
return ERROR_INV_SPS_PPS_T;
COPYTHECONTEXT("SH: ", u4_idr_pic_id);
}
/* read delta pic order count information*/
i_delta_poc[0] = i_delta_poc[1] = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type;
if(u1_pic_order_cnt_type == 0)
{
i_temp = ih264d_get_bits_h264(
ps_bitstrm,
ps_seq->u1_log2_max_pic_order_cnt_lsb_minus);
if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb)
return ERROR_INV_SPS_PPS_T;
s_tmp_poc.i4_pic_order_cnt_lsb = i_temp;
COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb);
if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom",
s_tmp_poc.i4_delta_pic_order_cnt_bottom);
}
}
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
if(u1_pic_order_cnt_type == 1
&& (!ps_seq->u1_delta_pic_order_always_zero_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[0]",
s_tmp_poc.i4_delta_pic_order_cnt[0]);
if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag)
{
s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[1]",
s_tmp_poc.i4_delta_pic_order_cnt[1]);
}
}
if(ps_pps->u1_redundant_pic_cnt_present_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_REDUNDANT_PIC_CNT)
return ERROR_INV_SPS_PPS_T;
u1_redundant_pic_cnt = u4_temp;
COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt);
}
/*--------------------------------------------------------------------*/
/* Check if the slice is part of new picture */
/*--------------------------------------------------------------------*/
i1_is_end_of_poc = 0;
if(!ps_dec->u1_first_slice_in_stream)
{
i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc,
&s_tmp_poc, &ps_dec->s_cur_pic_poc,
ps_cur_slice, u1_pic_order_cnt_type,
u1_nal_unit_type, u4_idr_pic_id,
u1_field_pic_flag,
u1_bottom_field_flag);
/* since we support only Full frame decode, every new process should
* process a new pic
*/
if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0))
{
/* if it is the first slice is process call ,it should be a new frame. If it is not
* reject current pic and dont add it to dpb
*/
ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC;
i1_is_end_of_poc = 1;
}
else
{
/* reset REJECT_CUR_PIC */
ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC;
}
}
/*--------------------------------------------------------------------*/
/* Check for error in slice and parse the missing/corrupted MB's */
/* as skip-MB's in an inserted P-slice */
/*--------------------------------------------------------------------*/
u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag);
prev_slice_err = 0;
if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream)
{
if(u2_frame_num != ps_dec->u2_prv_frame_num
&& ps_dec->u1_top_bottom_decoded != 0
&& ps_dec->u1_top_bottom_decoded
!= (TOP_FIELD_ONLY | BOT_FIELD_ONLY))
{
ps_dec->u1_dangling_field = 1;
if(ps_dec->u4_first_slice_in_pic)
{
prev_slice_err = 1;
}
else
{
prev_slice_err = 2;
}
if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY)
ps_cur_slice->u1_bottom_field_flag = 1;
else
ps_cur_slice->u1_bottom_field_flag = 0;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL;
}
else if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice > 0)
{
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
ps_cur_poc = &s_tmp_poc;
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->i4_pic_order_cnt_lsb =
s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
}
}
else
{
if(ps_dec->u4_first_slice_in_pic)
{
/* if valid slice header is not decoded do start of pic processing
* since in the current process call, frame num is not updated in the slice structure yet
* ih264d_is_end_of_pic is checked with valid frame num of previous process call,
* although i1_is_end_of_poc is set there could be more slices in the frame,
* so conceal only till cur slice */
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
}
else
{
/* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame
* completely */
prev_slice_err = 2;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
}
ps_cur_poc = &s_tmp_poc;
}
}
else
{
if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded)
{
prev_slice_err = 2;
num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &s_tmp_poc;
}
else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded)
{
return ERROR_CORRUPTED_SLICE;
}
}
if(prev_slice_err)
{
ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err);
if(ps_dec->u1_dangling_field == 1)
{
ps_dec->u1_second_field = 1 - ps_dec->u1_second_field;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_dec->u2_prv_frame_num = u2_frame_num;
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_DANGLING_FIELD_IN_PIC;
}
if(prev_slice_err == 2)
{
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_INCOMPLETE_FRAME;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
/* return if all MBs in frame are parsed*/
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_IN_LAST_SLICE_OF_PIC;
}
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
if(ret != OK)
return ret;
i1_is_end_of_poc = 0;
}
if (ps_dec->u4_first_slice_in_pic == 0)
ps_dec->ps_parse_cur_slice++;
ps_dec->u1_slice_header_done = 0;
/*--------------------------------------------------------------------*/
/* If the slice is part of new picture, do End of Pic processing. */
/*--------------------------------------------------------------------*/
if(!ps_dec->u1_first_slice_in_stream)
{
UWORD8 uc_mbs_exceed = 0;
if(ps_dec->u2_total_mbs_coded
== (ps_dec->ps_cur_sps->u2_max_mb_addr + 1))
{
/*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so
,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */
if(ps_dec->u4_first_slice_in_pic == 0)
uc_mbs_exceed = 1;
}
if(i1_is_end_of_poc || uc_mbs_exceed)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
#if WIN32
H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n");
#endif
return RET_LAST_SKIP;
}
else
{
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
}
}
}
if(u1_field_pic_flag)
{
ps_dec->u2_prv_frame_num = u2_frame_num;
}
if(ps_cur_slice->u1_mmco_equalto5)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair
{
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc =
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
}
else if(!ps_cur_slice->u1_bottom_field_flag)
i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
else
i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_poc = i4_temp_poc;
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice, ps_pps,
u1_nal_ref_idc,
u1_bottom_field_flag,
u1_field_pic_flag, &i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering + 1;
ps_dec->i4_max_poc = 0;
}
}
/*--------------------------------------------------------------------*/
/* Copy the values read from the bitstream to the slice header and then*/
/* If the slice is first slice in picture, then do Start of Picture */
/* processing. */
/*--------------------------------------------------------------------*/
ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0];
ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1];
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->u1_slice_type = u1_slice_type;
ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
if(ps_seq->u1_frame_mbs_only_flag)
ps_cur_slice->u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
else
ps_cur_slice->u1_direct_8x8_inference_flag = 1;
if(u1_slice_type == B_SLICE)
{
ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag",
ps_cur_slice->u1_direct_spatial_mv_pred_flag);
if(ps_cur_slice->u1_direct_spatial_mv_pred_flag)
ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct;
else
ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct;
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB;
}
else
{
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice == 0)
{
ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps);
if(ret != OK)
return ret;
}
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
/* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */
{
UWORD8 uc_nofield_nombaff;
uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0)
&& (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0)
&& (u1_slice_type != B_SLICE)
&& (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0));
/* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */
if(uc_nofield_nombaff)
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
}
else
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_mp;
}
}
/*
* Decide whether to decode the current picture or not
*/
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u4_frm_sei_sync == u2_frame_num)
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
}
ps_err->u4_cur_frm = u2_frame_num;
}
/* Decision for decoding if the picture is to be skipped */
{
WORD32 i4_skip_b_pic, i4_skip_p_pic;
i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT)
&& (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT)
&& (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
/**************************************************************/
/* Skip the B picture if skip mask is set for B picture and */
/* Current B picture is a non reference B picture or there is */
/* no user for reference B picture */
/**************************************************************/
if(i4_skip_b_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
/* Don't decode the picture in SKIP-B mode if that picture is B */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
/**************************************************************/
/* Skip the P picture if skip mask is set for P picture and */
/* Current P picture is a non reference P picture or there is */
/* no user for reference P picture */
/**************************************************************/
if(i4_skip_p_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
/* Don't decode the picture in SKIP-P mode if that picture is P */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
}
{
UWORD16 u2_mb_x, u2_mb_y;
ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice
<< ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE)
- SUB_BLK_SIZE;
if(u2_first_mb_in_slice)
{
UWORD8 u1_mb_aff;
UWORD8 u1_field_pic;
UWORD16 u2_frm_wd_in_mbs;
u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag;
u1_field_pic = ps_cur_slice->u1_field_pic_flag;
{
UWORD32 x_offset;
UWORD32 y_offset;
UWORD32 u4_frame_stride;
tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y <<= u1_mb_aff;
if((u2_mb_x > u2_frm_wd_in_mbs - 1)
|| (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1))
{
return ERROR_CORRUPTED_SLICE;
}
u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic;
x_offset = u2_mb_x << 4;
y_offset = (u2_mb_y * u4_frame_stride) << 4;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset
+ y_offset;
u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic;
x_offset >>= 1;
y_offset = (u2_mb_y * u4_frame_stride) << 3;
x_offset *= YUV420SP_FACTOR;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset
+ y_offset;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset
+ y_offset;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
if(ps_dec->u1_separate_parse == 1)
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
else
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff);
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv
+ ((u2_first_mb_in_slice << u1_mb_aff) << 4);
}
}
else
{
tfr_ctxt_t *ps_trns_addr;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = 0xffff;
u2_mb_y = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
}
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
}
/* RBSP stop bit is used for CABAC decoding*/
ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode;
ps_dec->u1_B = (u1_slice_type == B_SLICE);
ps_dec->u4_next_mb_skip = 0;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice =
ps_dec->ps_cur_slice->u2_first_mb_in_slice;
ps_dec->ps_parse_cur_slice->slice_type =
ps_dec->ps_cur_slice->u1_slice_type;
ps_dec->u4_start_recon_deblk = 1;
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MAX_FRAMES;
if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) &&
(0 == ps_dec->i4_display_delay))
{
num_entries = 1;
}
num_entries = ((2 * num_entries) + 1);
if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc)
{
num_entries *= 2;
}
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf;
}
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
if(u1_slice_type == I_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT;
ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice);
if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE)
ps_dec->i4_pic_type = I_SLICE;
}
else if(u1_slice_type == P_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
if(ps_dec->i4_pic_type != B_SLICE)
ps_dec->i4_pic_type = P_SLICE;
}
else if(u1_slice_type == B_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
ps_dec->i4_pic_type = B_SLICE;
}
else
return ERROR_INV_SLC_TYPE_T;
if(ps_dec->u1_slice_header_done)
{
/* set to zero to indicate a valid slice has been decoded */
/* first slice header successfully decoded */
ps_dec->u4_first_slice_in_pic = 0;
ps_dec->u1_first_slice_in_stream = 0;
}
if(ret != OK)
return ret;
ps_dec->u2_cur_slice_num++;
/* storing last Mb X and MbY of the slice */
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
/* End of Picture detection */
if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1))
{
ps_dec->u1_pic_decode_done = 1;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if((ps_err->u1_err_flag & REJECT_PB_PICS)
&& (ps_err->u1_cur_pic_type == PIC_TYPE_I))
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
PRINT_BIN_BIT_RATIO(ps_dec)
return ret;
}
| 174,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int 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 | 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;
}
| 165,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGLRenderingContextBase::TexImageHelperImageData(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint border,
GLenum format,
GLenum type,
GLsizei depth,
GLint xoffset,
GLint yoffset,
GLint zoffset,
ImageData* pixels,
const IntRect& source_image_rect,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
DCHECK(pixels);
if (pixels->data()->BufferBase()->IsNeutered()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name,
"The source data has been neutered.");
return;
}
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target,
level, internalformat, pixels->width(), pixels->height(),
depth, border, format, type, xoffset, yoffset, zoffset))
return;
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(
func_name, function_id, pixels, source_image_rect, depth,
unpack_image_height, &selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = source_image_rect;
if (unpack_flip_y_) {
adjusted_source_image_rect.SetY(pixels->height() -
adjusted_source_image_rect.MaxY());
}
Vector<uint8_t> data;
bool need_conversion = true;
if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA &&
type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
if (!WebGLImageConversion::ExtractImageData(
pixels->data()->Data(),
WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(),
adjusted_source_image_rect, depth, unpack_image_height, format,
type, unpack_flip_y_, unpack_premultiply_alpha_, data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data();
if (function_id == kTexImage2D) {
DCHECK_EQ(unpack_image_height, 0);
TexImage2DBase(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), border, format, type, bytes);
} else if (function_id == kTexSubImage2D) {
DCHECK_EQ(unpack_image_height, 0);
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type, bytes);
} else {
GLint upload_height = adjusted_source_image_rect.Height();
if (unpack_image_height) {
upload_height = unpack_image_height;
}
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(target, level, internalformat,
adjusted_source_image_rect.Width(), upload_height,
depth, border, format, type, bytes);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
upload_height, depth, format, type, bytes);
}
}
}
Commit Message: fix incorrect TexImage3D params w/ UNPACK_IMAGE_HEIGHT
Bug: 804123
Test: http://github.com/KhronosGroup/WebGL/pull/2646
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ifbce9b93f0b35817881e1e34930cbac22a1e8b98
Reviewed-on: https://chromium-review.googlesource.com/1053573
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Kai Ninomiya <[email protected]>
Cr-Commit-Position: refs/heads/master@{#558962}
CWE ID: | void WebGLRenderingContextBase::TexImageHelperImageData(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint border,
GLenum format,
GLenum type,
GLsizei depth,
GLint xoffset,
GLint yoffset,
GLint zoffset,
ImageData* pixels,
const IntRect& source_image_rect,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
DCHECK(pixels);
if (pixels->data()->BufferBase()->IsNeutered()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name,
"The source data has been neutered.");
return;
}
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target,
level, internalformat, pixels->width(), pixels->height(),
depth, border, format, type, xoffset, yoffset, zoffset))
return;
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(
func_name, function_id, pixels, source_image_rect, depth,
unpack_image_height, &selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = source_image_rect;
if (unpack_flip_y_) {
adjusted_source_image_rect.SetY(pixels->height() -
adjusted_source_image_rect.MaxY());
}
Vector<uint8_t> data;
bool need_conversion = true;
if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA &&
type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
if (!WebGLImageConversion::ExtractImageData(
pixels->data()->Data(),
WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(),
adjusted_source_image_rect, depth, unpack_image_height, format,
type, unpack_flip_y_, unpack_premultiply_alpha_, data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data();
if (function_id == kTexImage2D) {
DCHECK_EQ(unpack_image_height, 0);
TexImage2DBase(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), border, format, type, bytes);
} else if (function_id == kTexSubImage2D) {
DCHECK_EQ(unpack_image_height, 0);
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type, bytes);
} else {
GLint upload_height = adjusted_source_image_rect.Height();
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(target, level, internalformat,
adjusted_source_image_rect.Width(), upload_height,
depth, border, format, type, bytes);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
upload_height, depth, format, type, bytes);
}
}
}
| 173,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RemoveInvalidFilesFromPersistentDirectory(
const GDataCacheMetadataMap::ResourceIdToFilePathMap& persistent_file_map,
const GDataCacheMetadataMap::ResourceIdToFilePathMap& outgoing_file_map,
GDataCacheMetadataMap::CacheMap* cache_map) {
for (GDataCacheMetadataMap::ResourceIdToFilePathMap::const_iterator iter =
persistent_file_map.begin();
iter != persistent_file_map.end(); ++iter) {
const std::string& resource_id = iter->first;
const FilePath& file_path = iter->second;
GDataCacheMetadataMap::CacheMap::iterator cache_map_iter =
cache_map->find(resource_id);
if (cache_map_iter != cache_map->end()) {
const GDataCache::CacheEntry& cache_entry = cache_map_iter->second;
if (cache_entry.IsDirty() && outgoing_file_map.count(resource_id) == 0) {
LOG(WARNING) << "Removing dirty-but-not-committed file: "
<< file_path.value();
file_util::Delete(file_path, false);
cache_map->erase(cache_map_iter);
}
if (!cache_entry.IsDirty() && !cache_entry.IsPinned()) {
LOG(WARNING) << "Removing persistent-but-dangling file: "
<< file_path.value();
file_util::Delete(file_path, false);
cache_map->erase(cache_map_iter);
}
}
}
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void RemoveInvalidFilesFromPersistentDirectory(
| 170,867 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppResult::Open(int event_flags) {
RecordHistogram(APP_SEARCH_RESULT);
const extensions::Extension* extension =
extensions::ExtensionSystem::Get(profile_)->extension_service()
->GetInstalledExtension(app_id_);
if (!extension)
return;
if (!extensions::util::IsAppLaunchable(app_id_, profile_))
return;
if (RunExtensionEnableFlow())
return;
if (display_type() != DISPLAY_RECOMMENDATION) {
extensions::RecordAppListSearchLaunch(extension);
content::RecordAction(
base::UserMetricsAction("AppList_ClickOnAppFromSearch"));
}
controller_->ActivateApp(
profile_,
extension,
AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH,
event_flags);
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | void AppResult::Open(int event_flags) {
RecordHistogram(APP_SEARCH_RESULT);
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension(
app_id_);
if (!extension)
return;
if (!extensions::util::IsAppLaunchable(app_id_, profile_))
return;
if (RunExtensionEnableFlow())
return;
if (display_type() != DISPLAY_RECOMMENDATION) {
extensions::RecordAppListSearchLaunch(extension);
content::RecordAction(
base::UserMetricsAction("AppList_ClickOnAppFromSearch"));
}
controller_->ActivateApp(
profile_,
extension,
AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH,
event_flags);
}
| 171,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_read_start_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
int max_pixel_depth;
png_size_t row_bytes;
png_debug(1, "in png_read_start_row");
png_ptr->zstream.avail_in = 0;
png_init_read_transformations(png_ptr);
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
if (!(png_ptr->transformations & PNG_INTERLACE))
png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
png_pass_ystart[0]) / png_pass_yinc[0];
else
png_ptr->num_rows = png_ptr->height;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
}
else
#endif /* PNG_READ_INTERLACING_SUPPORTED */
{
png_ptr->num_rows = png_ptr->height;
png_ptr->iwidth = png_ptr->width;
}
max_pixel_depth = png_ptr->pixel_depth;
#ifdef PNG_READ_PACK_SUPPORTED
if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
max_pixel_depth = 8;
#endif
#ifdef PNG_READ_EXPAND_SUPPORTED
if (png_ptr->transformations & PNG_EXPAND)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (png_ptr->num_trans)
max_pixel_depth = 32;
else
max_pixel_depth = 24;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
{
if (max_pixel_depth < 8)
max_pixel_depth = 8;
if (png_ptr->num_trans)
max_pixel_depth *= 2;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
{
if (png_ptr->num_trans)
{
max_pixel_depth *= 4;
max_pixel_depth /= 3;
}
}
}
#endif
#ifdef PNG_READ_FILLER_SUPPORTED
if (png_ptr->transformations & (PNG_FILLER))
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
max_pixel_depth = 32;
else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
{
if (max_pixel_depth <= 8)
max_pixel_depth = 16;
else
max_pixel_depth = 32;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
{
if (max_pixel_depth <= 32)
max_pixel_depth = 32;
else
max_pixel_depth = 64;
}
}
#endif
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
if (png_ptr->transformations & PNG_GRAY_TO_RGB)
{
if (
#ifdef PNG_READ_EXPAND_SUPPORTED
(png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
#endif
#ifdef PNG_READ_FILLER_SUPPORTED
(png_ptr->transformations & (PNG_FILLER)) ||
#endif
png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (max_pixel_depth <= 16)
max_pixel_depth = 32;
else
max_pixel_depth = 64;
}
else
{
if (max_pixel_depth <= 8)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
max_pixel_depth = 32;
else
max_pixel_depth = 24;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
max_pixel_depth = 64;
else
max_pixel_depth = 48;
}
}
#endif
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
if (png_ptr->transformations & PNG_USER_TRANSFORM)
{
int user_pixel_depth = png_ptr->user_transform_depth*
png_ptr->user_transform_channels;
if (user_pixel_depth > max_pixel_depth)
max_pixel_depth=user_pixel_depth;
}
#endif
/* Align the width on the next larger 8 pixels. Mainly used
* for interlacing
*/
row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
/* Calculate the maximum bytes needed, adding a byte and a pixel
* for safety's sake
*/
row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
1 + ((max_pixel_depth + 7) >> 3);
#ifdef PNG_MAX_MALLOC_64K
if (row_bytes > (png_uint_32)65536L)
png_error(png_ptr, "This image requires a row greater than 64KB");
#endif
if (row_bytes + 64 > png_ptr->old_big_row_buf_size)
{
png_free(png_ptr, png_ptr->big_row_buf);
if (png_ptr->interlaced)
png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
row_bytes + 64);
else
png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr,
row_bytes + 64);
png_ptr->old_big_row_buf_size = row_bytes + 64;
/* Use 32 bytes of padding before and after row_buf. */
png_ptr->row_buf = png_ptr->big_row_buf + 32;
png_ptr->old_big_row_buf_size = row_bytes + 64;
}
#ifdef PNG_MAX_MALLOC_64K
if ((png_uint_32)row_bytes + 1 > (png_uint_32)65536L)
png_error(png_ptr, "This image requires a row greater than 64KB");
#endif
if ((png_uint_32)row_bytes > (png_uint_32)(PNG_SIZE_MAX - 1))
png_error(png_ptr, "Row has too many bytes to allocate in memory.");
if (row_bytes + 1 > png_ptr->old_prev_row_size)
{
png_free(png_ptr, png_ptr->prev_row);
png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
row_bytes + 1));
png_memset_check(png_ptr, png_ptr->prev_row, 0, row_bytes + 1);
png_ptr->old_prev_row_size = row_bytes + 1;
}
png_ptr->rowbytes = row_bytes;
png_debug1(3, "width = %lu,", png_ptr->width);
png_debug1(3, "height = %lu,", png_ptr->height);
png_debug1(3, "iwidth = %lu,", png_ptr->iwidth);
png_debug1(3, "num_rows = %lu,", png_ptr->num_rows);
png_debug1(3, "rowbytes = %lu,", png_ptr->rowbytes);
png_debug1(3, "irowbytes = %lu",
PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
png_ptr->flags |= PNG_FLAG_ROW_INIT;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_read_start_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif
int max_pixel_depth;
png_size_t row_bytes;
png_debug(1, "in png_read_start_row");
png_ptr->zstream.avail_in = 0;
png_init_read_transformations(png_ptr);
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
if (!(png_ptr->transformations & PNG_INTERLACE))
png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
png_pass_ystart[0]) / png_pass_yinc[0];
else
png_ptr->num_rows = png_ptr->height;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
}
else
#endif /* PNG_READ_INTERLACING_SUPPORTED */
{
png_ptr->num_rows = png_ptr->height;
png_ptr->iwidth = png_ptr->width;
}
max_pixel_depth = png_ptr->pixel_depth;
#ifdef PNG_READ_PACK_SUPPORTED
if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
max_pixel_depth = 8;
#endif
#ifdef PNG_READ_EXPAND_SUPPORTED
if (png_ptr->transformations & PNG_EXPAND)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (png_ptr->num_trans)
max_pixel_depth = 32;
else
max_pixel_depth = 24;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
{
if (max_pixel_depth < 8)
max_pixel_depth = 8;
if (png_ptr->num_trans)
max_pixel_depth *= 2;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
{
if (png_ptr->num_trans)
{
max_pixel_depth *= 4;
max_pixel_depth /= 3;
}
}
}
#endif
#ifdef PNG_READ_FILLER_SUPPORTED
if (png_ptr->transformations & (PNG_FILLER))
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
max_pixel_depth = 32;
else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
{
if (max_pixel_depth <= 8)
max_pixel_depth = 16;
else
max_pixel_depth = 32;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
{
if (max_pixel_depth <= 32)
max_pixel_depth = 32;
else
max_pixel_depth = 64;
}
}
#endif
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
if (png_ptr->transformations & PNG_GRAY_TO_RGB)
{
if (
#ifdef PNG_READ_EXPAND_SUPPORTED
(png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
#endif
#ifdef PNG_READ_FILLER_SUPPORTED
(png_ptr->transformations & (PNG_FILLER)) ||
#endif
png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (max_pixel_depth <= 16)
max_pixel_depth = 32;
else
max_pixel_depth = 64;
}
else
{
if (max_pixel_depth <= 8)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
max_pixel_depth = 32;
else
max_pixel_depth = 24;
}
else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
max_pixel_depth = 64;
else
max_pixel_depth = 48;
}
}
#endif
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
if (png_ptr->transformations & PNG_USER_TRANSFORM)
{
int user_pixel_depth = png_ptr->user_transform_depth*
png_ptr->user_transform_channels;
if (user_pixel_depth > max_pixel_depth)
max_pixel_depth=user_pixel_depth;
}
#endif
/* Align the width on the next larger 8 pixels. Mainly used
* for interlacing
*/
row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
/* Calculate the maximum bytes needed, adding a byte and a pixel
* for safety's sake
*/
row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
1 + ((max_pixel_depth + 7) >> 3);
#ifdef PNG_MAX_MALLOC_64K
if (row_bytes > (png_uint_32)65536L)
png_error(png_ptr, "This image requires a row greater than 64KB");
#endif
if (row_bytes + 64 > png_ptr->old_big_row_buf_size)
{
png_free(png_ptr, png_ptr->big_row_buf);
if (png_ptr->interlaced)
png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
row_bytes + 64);
else
png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr,
row_bytes + 64);
png_ptr->old_big_row_buf_size = row_bytes + 64;
/* Use 32 bytes of padding before and after row_buf. */
png_ptr->row_buf = png_ptr->big_row_buf + 32;
png_ptr->old_big_row_buf_size = row_bytes + 64;
}
#ifdef PNG_MAX_MALLOC_64K
if ((png_uint_32)row_bytes + 1 > (png_uint_32)65536L)
png_error(png_ptr, "This image requires a row greater than 64KB");
#endif
if ((png_uint_32)row_bytes > (png_uint_32)(PNG_SIZE_MAX - 1))
png_error(png_ptr, "Row has too many bytes to allocate in memory.");
if (row_bytes + 1 > png_ptr->old_prev_row_size)
{
png_free(png_ptr, png_ptr->prev_row);
png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
row_bytes + 1));
png_memset_check(png_ptr, png_ptr->prev_row, 0, row_bytes + 1);
png_ptr->old_prev_row_size = row_bytes + 1;
}
png_ptr->rowbytes = row_bytes;
png_debug1(3, "width = %lu,", png_ptr->width);
png_debug1(3, "height = %lu,", png_ptr->height);
png_debug1(3, "iwidth = %lu,", png_ptr->iwidth);
png_debug1(3, "num_rows = %lu,", png_ptr->num_rows);
png_debug1(3, "rowbytes = %lu,", png_ptr->rowbytes);
png_debug1(3, "irowbytes = %lu",
PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
png_ptr->flags |= PNG_FLAG_ROW_INIT;
}
| 172,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
int ret = 0;
struct vm_area_struct *vma = walk->private;
pte_t *pte;
spinlock_t *ptl;
split_huge_page_pmd(walk->mm, pmd);
retry:
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; addr += PAGE_SIZE) {
pte_t ptent = *(pte++);
union mc_target target;
int type;
struct page *page;
struct page_cgroup *pc;
swp_entry_t ent;
if (!mc.precharge)
break;
type = is_target_pte_for_mc(vma, addr, ptent, &target);
switch (type) {
case MC_TARGET_PAGE:
page = target.page;
if (isolate_lru_page(page))
goto put;
pc = lookup_page_cgroup(page);
if (!mem_cgroup_move_account(page, 1, pc,
mc.from, mc.to, false)) {
mc.precharge--;
/* we uncharge from mc.from later. */
mc.moved_charge++;
}
putback_lru_page(page);
put: /* is_target_pte_for_mc() gets the page */
put_page(page);
break;
case MC_TARGET_SWAP:
ent = target.ent;
if (!mem_cgroup_move_swap_account(ent,
mc.from, mc.to, false)) {
mc.precharge--;
/* we fixup refcnts and charges later. */
mc.moved_swap++;
}
break;
default:
break;
}
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
if (addr != end) {
/*
* We have consumed all precharges we got in can_attach().
* We try charge one by one, but don't do any additional
* charges to mc.to if we have failed in charge once in attach()
* phase.
*/
ret = mem_cgroup_do_precharge(1);
if (!ret)
goto retry;
}
return ret;
}
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(¤t->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 | static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
int ret = 0;
struct vm_area_struct *vma = walk->private;
pte_t *pte;
spinlock_t *ptl;
split_huge_page_pmd(walk->mm, pmd);
if (pmd_trans_unstable(pmd))
return 0;
retry:
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; addr += PAGE_SIZE) {
pte_t ptent = *(pte++);
union mc_target target;
int type;
struct page *page;
struct page_cgroup *pc;
swp_entry_t ent;
if (!mc.precharge)
break;
type = is_target_pte_for_mc(vma, addr, ptent, &target);
switch (type) {
case MC_TARGET_PAGE:
page = target.page;
if (isolate_lru_page(page))
goto put;
pc = lookup_page_cgroup(page);
if (!mem_cgroup_move_account(page, 1, pc,
mc.from, mc.to, false)) {
mc.precharge--;
/* we uncharge from mc.from later. */
mc.moved_charge++;
}
putback_lru_page(page);
put: /* is_target_pte_for_mc() gets the page */
put_page(page);
break;
case MC_TARGET_SWAP:
ent = target.ent;
if (!mem_cgroup_move_swap_account(ent,
mc.from, mc.to, false)) {
mc.precharge--;
/* we fixup refcnts and charges later. */
mc.moved_swap++;
}
break;
default:
break;
}
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
if (addr != end) {
/*
* We have consumed all precharges we got in can_attach().
* We try charge one by one, but don't do any additional
* charges to mc.to if we have failed in charge once in attach()
* phase.
*/
ret = mem_cgroup_do_precharge(1);
if (!ret)
goto retry;
}
return ret;
}
| 165,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
{
/* Must be called with pernet_ops_rwsem held */
const struct pernet_operations *ops, *saved_ops;
int error = 0;
LIST_HEAD(net_exit_list);
refcount_set(&net->count, 1);
refcount_set(&net->passive, 1);
net->dev_base_seq = 1;
net->user_ns = user_ns;
idr_init(&net->netns_ids);
spin_lock_init(&net->nsid_lock);
mutex_init(&net->ipv4.ra_mutex);
list_for_each_entry(ops, &pernet_list, list) {
error = ops_init(ops, net);
if (error < 0)
goto out_undo;
}
down_write(&net_rwsem);
list_add_tail_rcu(&net->list, &net_namespace_list);
up_write(&net_rwsem);
out:
return error;
out_undo:
/* Walk through the list backwards calling the exit functions
* for the pernet modules whose init functions did not fail.
*/
list_add(&net->exit_list, &net_exit_list);
saved_ops = ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_exit_list(ops, &net_exit_list);
ops = saved_ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_free_list(ops, &net_exit_list);
rcu_barrier();
goto out;
}
Commit Message: netns: provide pure entropy for net_hash_mix()
net_hash_mix() currently uses kernel address of a struct net,
and is used in many places that could be used to reveal this
address to a patient attacker, thus defeating KASLR, for
the typical case (initial net namespace, &init_net is
not dynamically allocated)
I believe the original implementation tried to avoid spending
too many cycles in this function, but security comes first.
Also provide entropy regardless of CONFIG_NET_NS.
Fixes: 0b4419162aa6 ("netns: introduce the net_hash_mix "salt" for hashes")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
{
/* Must be called with pernet_ops_rwsem held */
const struct pernet_operations *ops, *saved_ops;
int error = 0;
LIST_HEAD(net_exit_list);
refcount_set(&net->count, 1);
refcount_set(&net->passive, 1);
get_random_bytes(&net->hash_mix, sizeof(u32));
net->dev_base_seq = 1;
net->user_ns = user_ns;
idr_init(&net->netns_ids);
spin_lock_init(&net->nsid_lock);
mutex_init(&net->ipv4.ra_mutex);
list_for_each_entry(ops, &pernet_list, list) {
error = ops_init(ops, net);
if (error < 0)
goto out_undo;
}
down_write(&net_rwsem);
list_add_tail_rcu(&net->list, &net_namespace_list);
up_write(&net_rwsem);
out:
return error;
out_undo:
/* Walk through the list backwards calling the exit functions
* for the pernet modules whose init functions did not fail.
*/
list_add(&net->exit_list, &net_exit_list);
saved_ops = ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_exit_list(ops, &net_exit_list);
ops = saved_ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_free_list(ops, &net_exit_list);
rcu_barrier();
goto out;
}
| 169,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data)
{
/* This suppresses [Last] button: assistant thinks that
* we never have this page ready unless we are on it
* -> therefore there is at least one non-ready page
* -> therefore it won't show [Last]
*/
/* If processing is finished and if it was terminated because of an error
* the event progress page is selected. So, it does not make sense to show
* the next step button and we MUST NOT clear warnings.
*/
if (!is_processing_finished())
{
/* some pages hide it, so restore it to it's default */
show_next_step_button();
clear_warnings();
}
gtk_widget_hide(g_btn_detail);
gtk_widget_hide(g_btn_onfail);
if (!g_expert_mode)
gtk_widget_hide(g_btn_repeat);
/* Save text fields if changed */
/* Must be called before any GUI operation because the following two
* functions causes recreating of the text items tabs, thus all updates to
* these tabs will be lost */
save_items_from_notepad();
save_text_from_text_view(g_tv_comment, FILENAME_COMMENT);
if (pages[PAGENO_SUMMARY].page_widget == page)
{
if (!g_expert_mode)
{
/* Skip intro screen */
int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL);
log_info("switching to page_no:%d", n);
gtk_notebook_set_current_page(assistant, n);
return;
}
}
if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page)
{
if (highlight_forbidden())
{
add_sensitive_data_warning();
show_warnings();
gtk_expander_set_expanded(g_exp_search, TRUE);
}
else
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE);
show_warnings();
}
if (pages[PAGENO_REVIEW_DATA].page_widget == page)
{
update_ls_details_checkboxes(g_event_selected);
gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt));
}
if (pages[PAGENO_EDIT_COMMENT].page_widget == page)
{
gtk_widget_show(g_btn_detail);
gtk_widget_set_sensitive(g_btn_next, false);
on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL);
}
if (pages[PAGENO_EVENT_PROGRESS].page_widget == page)
{
log_info("g_event_selected:'%s'", g_event_selected);
if (g_event_selected
&& g_event_selected[0]
) {
clear_warnings();
start_event_run(g_event_selected);
}
}
if(pages[PAGENO_EVENT_SELECTOR].page_widget == page)
{
if (!g_expert_mode && !g_auto_event_list)
hide_next_step_button();
}
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
CWE ID: CWE-200 | static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data)
{
/* This suppresses [Last] button: assistant thinks that
* we never have this page ready unless we are on it
* -> therefore there is at least one non-ready page
* -> therefore it won't show [Last]
*/
/* If processing is finished and if it was terminated because of an error
* the event progress page is selected. So, it does not make sense to show
* the next step button and we MUST NOT clear warnings.
*/
if (!is_processing_finished())
{
/* some pages hide it, so restore it to it's default */
show_next_step_button();
clear_warnings();
}
gtk_widget_hide(g_btn_detail);
gtk_widget_hide(g_btn_onfail);
if (!g_expert_mode)
gtk_widget_hide(g_btn_repeat);
/* Save text fields if changed */
/* Must be called before any GUI operation because the following two
* functions causes recreating of the text items tabs, thus all updates to
* these tabs will be lost */
save_items_from_notepad();
save_text_from_text_view(g_tv_comment, FILENAME_COMMENT);
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
if (pages[PAGENO_SUMMARY].page_widget == page)
{
if (!g_expert_mode)
{
/* Skip intro screen */
int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL);
log_info("switching to page_no:%d", n);
gtk_notebook_set_current_page(assistant, n);
return;
}
}
if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page)
{
if (highlight_forbidden())
{
add_sensitive_data_warning();
show_warnings();
gtk_expander_set_expanded(g_exp_search, TRUE);
}
else
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE);
show_warnings();
}
if (pages[PAGENO_REVIEW_DATA].page_widget == page)
{
update_ls_details_checkboxes(g_event_selected);
gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt));
}
if (pages[PAGENO_EDIT_COMMENT].page_widget == page)
{
gtk_widget_show(g_btn_detail);
gtk_widget_set_sensitive(g_btn_next, false);
on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL);
}
if (pages[PAGENO_EVENT_PROGRESS].page_widget == page)
{
log_info("g_event_selected:'%s'", g_event_selected);
if (g_event_selected
&& g_event_selected[0]
) {
clear_warnings();
start_event_run(g_event_selected);
}
}
if(pages[PAGENO_EVENT_SELECTOR].page_widget == page)
{
if (!g_expert_mode && !g_auto_event_list)
hide_next_step_button();
}
}
| 166,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chapters::~Chapters() {
while (m_editions_count > 0) {
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
}
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 | Chapters::~Chapters() {
while (m_editions_count > 0) {
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
delete[] m_editions;
}
| 173,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ieee80211_fragment(struct ieee80211_tx_data *tx,
struct sk_buff *skb, int hdrlen,
int frag_threshold)
{
struct ieee80211_local *local = tx->local;
struct ieee80211_tx_info *info;
struct sk_buff *tmp;
int per_fragm = frag_threshold - hdrlen - FCS_LEN;
int pos = hdrlen + per_fragm;
int rem = skb->len - hdrlen - per_fragm;
if (WARN_ON(rem < 0))
return -EINVAL;
/* first fragment was already added to queue by caller */
while (rem) {
int fraglen = per_fragm;
if (fraglen > rem)
fraglen = rem;
rem -= fraglen;
tmp = dev_alloc_skb(local->tx_headroom +
frag_threshold +
tx->sdata->encrypt_headroom +
IEEE80211_ENCRYPT_TAILROOM);
if (!tmp)
return -ENOMEM;
__skb_queue_tail(&tx->skbs, tmp);
skb_reserve(tmp,
local->tx_headroom + tx->sdata->encrypt_headroom);
/* copy control information */
memcpy(tmp->cb, skb->cb, sizeof(tmp->cb));
info = IEEE80211_SKB_CB(tmp);
info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT |
IEEE80211_TX_CTL_FIRST_FRAGMENT);
if (rem)
info->flags |= IEEE80211_TX_CTL_MORE_FRAMES;
skb_copy_queue_mapping(tmp, skb);
tmp->priority = skb->priority;
tmp->dev = skb->dev;
/* copy header and data */
memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen);
memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen);
pos += fraglen;
}
/* adjust first fragment's length */
skb->len = hdrlen + per_fragm;
return 0;
}
Commit Message: mac80211: fix fragmentation code, particularly for encryption
The "new" fragmentation code (since my rewrite almost 5 years ago)
erroneously sets skb->len rather than using skb_trim() to adjust
the length of the first fragment after copying out all the others.
This leaves the skb tail pointer pointing to after where the data
originally ended, and thus causes the encryption MIC to be written
at that point, rather than where it belongs: immediately after the
data.
The impact of this is that if software encryption is done, then
a) encryption doesn't work for the first fragment, the connection
becomes unusable as the first fragment will never be properly
verified at the receiver, the MIC is practically guaranteed to
be wrong
b) we leak up to 8 bytes of plaintext (!) of the packet out into
the air
This is only mitigated by the fact that many devices are capable
of doing encryption in hardware, in which case this can't happen
as the tail pointer is irrelevant in that case. Additionally,
fragmentation is not used very frequently and would normally have
to be configured manually.
Fix this by using skb_trim() properly.
Cc: [email protected]
Fixes: 2de8e0d999b8 ("mac80211: rewrite fragmentation")
Reported-by: Jouni Malinen <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-200 | static int ieee80211_fragment(struct ieee80211_tx_data *tx,
struct sk_buff *skb, int hdrlen,
int frag_threshold)
{
struct ieee80211_local *local = tx->local;
struct ieee80211_tx_info *info;
struct sk_buff *tmp;
int per_fragm = frag_threshold - hdrlen - FCS_LEN;
int pos = hdrlen + per_fragm;
int rem = skb->len - hdrlen - per_fragm;
if (WARN_ON(rem < 0))
return -EINVAL;
/* first fragment was already added to queue by caller */
while (rem) {
int fraglen = per_fragm;
if (fraglen > rem)
fraglen = rem;
rem -= fraglen;
tmp = dev_alloc_skb(local->tx_headroom +
frag_threshold +
tx->sdata->encrypt_headroom +
IEEE80211_ENCRYPT_TAILROOM);
if (!tmp)
return -ENOMEM;
__skb_queue_tail(&tx->skbs, tmp);
skb_reserve(tmp,
local->tx_headroom + tx->sdata->encrypt_headroom);
/* copy control information */
memcpy(tmp->cb, skb->cb, sizeof(tmp->cb));
info = IEEE80211_SKB_CB(tmp);
info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT |
IEEE80211_TX_CTL_FIRST_FRAGMENT);
if (rem)
info->flags |= IEEE80211_TX_CTL_MORE_FRAMES;
skb_copy_queue_mapping(tmp, skb);
tmp->priority = skb->priority;
tmp->dev = skb->dev;
/* copy header and data */
memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen);
memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen);
pos += fraglen;
}
/* adjust first fragment's length */
skb_trim(skb, hdrlen + per_fragm);
return 0;
}
| 166,242 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameHostManager::RenderFrameHostManager(
FrameTreeNode* frame_tree_node,
RenderFrameHostDelegate* render_frame_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
Delegate* delegate)
: frame_tree_node_(frame_tree_node),
delegate_(delegate),
render_frame_delegate_(render_frame_delegate),
render_widget_delegate_(render_widget_delegate),
interstitial_page_(nullptr),
weak_factory_(this) {
DCHECK(frame_tree_node_);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | RenderFrameHostManager::RenderFrameHostManager(
FrameTreeNode* frame_tree_node,
RenderFrameHostDelegate* render_frame_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
Delegate* delegate)
: frame_tree_node_(frame_tree_node),
delegate_(delegate),
render_frame_delegate_(render_frame_delegate),
render_widget_delegate_(render_widget_delegate),
weak_factory_(this) {
DCHECK(frame_tree_node_);
}
| 172,323 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval)
{
zval *val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
MAKE_STD_ZVAL(val);
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(val, buf, 1);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
default:
ZVAL_STRING(val, "Unknown value type", 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(val, buf, 1);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", val);
} else {
*snmpval = *val;
zval_copy_ctor(snmpval);
}
zval_ptr_dtor(&val);
if(dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
Commit Message:
CWE ID: CWE-416 | static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval)
{
zval *val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
MAKE_STD_ZVAL(val);
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(val, buf, 1);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
default:
ZVAL_STRING(val, "Unknown value type", 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(val, buf, 1);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", val);
} else {
*snmpval = *val;
zval_copy_ctor(snmpval);
}
zval_ptr_dtor(&val);
if(dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
| 164,975 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EntrySync::remove(ExceptionState& exceptionState) const
{
RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create();
m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void EntrySync::remove(ExceptionState& exceptionState) const
{
VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create();
m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
helper->getResult(exceptionState);
}
| 171,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
ND_TCHECK_32BITS(obj_tptr + offset + 4);
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
trunc:
return -1;
}
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 | lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
ND_TCHECK_16BITS(obj_tptr + offset);
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_TCHECK_8BITS(obj_tptr + offset + 2);
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_TCHECK_8BITS(obj_tptr + offset + 3);
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
ND_TCHECK_32BITS(obj_tptr + offset + 4);
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
ND_TCHECK_32BITS(obj_tptr + offset + 8);
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_TCHECK_32BITS(obj_tptr + offset + 4);
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
trunc:
return -1;
}
| 169,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: kadm5_modify_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask)
{
int ret, ret2, i;
kadm5_policy_ent_rec pol;
krb5_boolean have_pol = FALSE;
krb5_db_entry *kdb;
krb5_tl_data *tl_data_orig;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) ||
(mask & KADM5_LAST_FAILED))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if(entry == (kadm5_principal_ent_t) NULL)
return EINVAL;
if (mask & KADM5_TL_DATA) {
tl_data_orig = entry->tl_data;
while (tl_data_orig) {
if (tl_data_orig->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
tl_data_orig = tl_data_orig->tl_data_next;
}
}
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
if (ret)
return(ret);
/*
* This is pretty much the same as create ...
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &pol, &have_pol);
if (ret)
goto done;
/* set us up to use the new policy */
adb.aux_attributes |= KADM5_POLICY;
if (adb.policy)
free(adb.policy);
adb.policy = strdup(entry->policy);
}
if (have_pol) {
/* set pw_max_life based on new policy */
if (pol.pw_max_life) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(kdb->pw_expiration));
if (ret)
goto done;
kdb->pw_expiration += pol.pw_max_life;
} else {
kdb->pw_expiration = 0;
}
}
if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) {
free(adb.policy);
adb.policy = NULL;
adb.aux_attributes &= ~KADM5_POLICY;
kdb->pw_expiration = 0;
}
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
if (mask & KADM5_PW_EXPIRATION)
kdb->pw_expiration = entry->pw_expiration;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
if((mask & KADM5_KVNO)) {
for (i = 0; i < kdb->n_key_data; i++)
kdb->key_data[i].key_data_kvno = entry->kvno;
}
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl;
/* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */
for (tl = entry->tl_data; tl;
tl = tl->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl);
if( ret )
{
goto done;
}
}
}
/*
* Setting entry->fail_auth_count to 0 can be used to manually unlock
* an account. It is not possible to set fail_auth_count to any other
* value using kadmin.
*/
if (mask & KADM5_FAIL_AUTH_COUNT) {
if (entry->fail_auth_count != 0) {
ret = KADM5_BAD_SERVER_PARAMS;
goto done;
}
kdb->fail_auth_count = 0;
}
/* let the mask propagate to the database provider */
kdb->mask = mask;
ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask);
if (ret)
goto done;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret) goto done;
(void) k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask);
ret = KADM5_OK;
done:
if (have_pol) {
ret2 = kadm5_free_policy_ent(handle->lhandle, &pol);
ret = ret ? ret : ret2;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
Commit Message: Check for null kadm5 policy name [CVE-2015-8630]
In kadm5_create_principal_3() and kadm5_modify_principal(), check for
entry->policy being null when KADM5_POLICY is included in the mask.
CVE-2015-8630:
In MIT krb5 1.12 and later, an authenticated attacker with permission
to modify a principal entry can cause kadmind to dereference a null
pointer by supplying a null policy value but including KADM5_POLICY in
the mask.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8342 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: | kadm5_modify_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask)
{
int ret, ret2, i;
kadm5_policy_ent_rec pol;
krb5_boolean have_pol = FALSE;
krb5_db_entry *kdb;
krb5_tl_data *tl_data_orig;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if(entry == NULL)
return EINVAL;
if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) ||
(mask & KADM5_LAST_FAILED))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && entry->policy == NULL)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if (mask & KADM5_TL_DATA) {
tl_data_orig = entry->tl_data;
while (tl_data_orig) {
if (tl_data_orig->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
tl_data_orig = tl_data_orig->tl_data_next;
}
}
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
if (ret)
return(ret);
/*
* This is pretty much the same as create ...
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &pol, &have_pol);
if (ret)
goto done;
/* set us up to use the new policy */
adb.aux_attributes |= KADM5_POLICY;
if (adb.policy)
free(adb.policy);
adb.policy = strdup(entry->policy);
}
if (have_pol) {
/* set pw_max_life based on new policy */
if (pol.pw_max_life) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(kdb->pw_expiration));
if (ret)
goto done;
kdb->pw_expiration += pol.pw_max_life;
} else {
kdb->pw_expiration = 0;
}
}
if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) {
free(adb.policy);
adb.policy = NULL;
adb.aux_attributes &= ~KADM5_POLICY;
kdb->pw_expiration = 0;
}
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
if (mask & KADM5_PW_EXPIRATION)
kdb->pw_expiration = entry->pw_expiration;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
if((mask & KADM5_KVNO)) {
for (i = 0; i < kdb->n_key_data; i++)
kdb->key_data[i].key_data_kvno = entry->kvno;
}
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl;
/* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */
for (tl = entry->tl_data; tl;
tl = tl->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl);
if( ret )
{
goto done;
}
}
}
/*
* Setting entry->fail_auth_count to 0 can be used to manually unlock
* an account. It is not possible to set fail_auth_count to any other
* value using kadmin.
*/
if (mask & KADM5_FAIL_AUTH_COUNT) {
if (entry->fail_auth_count != 0) {
ret = KADM5_BAD_SERVER_PARAMS;
goto done;
}
kdb->fail_auth_count = 0;
}
/* let the mask propagate to the database provider */
kdb->mask = mask;
ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask);
if (ret)
goto done;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret) goto done;
(void) k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask);
ret = KADM5_OK;
done:
if (have_pol) {
ret2 = kadm5_free_policy_ent(handle->lhandle, &pol);
ret = ret ? ret : ret2;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
| 167,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
CAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
Commit Message: Avoid reading past the end of buffer (Rui Reis)
CWE ID: CWE-125 | do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
CAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
| 169,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width * 3, 16);
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
Commit Message: avcodec/g2meet: Fix order of align and pixel size multiplication.
Fixes out of array accesses
Fixes Ticket2922
Found-by: ami_stuff
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-189 | static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width, 16) * 3;
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
| 165,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
Commit Message: net: sctp: fix panic on duplicate ASCONF chunks
When receiving a e.g. semi-good formed connection scan in the
form of ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
---------------- ASCONF_a; ASCONF_b ----------------->
... where ASCONF_a equals ASCONF_b chunk (at least both serials
need to be equal), we panic an SCTP server!
The problem is that good-formed ASCONF chunks that we reply with
ASCONF_ACK chunks are cached per serial. Thus, when we receive a
same ASCONF chunk twice (e.g. through a lost ASCONF_ACK), we do
not need to process them again on the server side (that was the
idea, also proposed in the RFC). Instead, we know it was cached
and we just resend the cached chunk instead. So far, so good.
Where things get nasty is in SCTP's side effect interpreter, that
is, sctp_cmd_interpreter():
While incoming ASCONF_a (chunk = event_arg) is being marked
!end_of_packet and !singleton, and we have an association context,
we do not flush the outqueue the first time after processing the
ASCONF_ACK singleton chunk via SCTP_CMD_REPLY. Instead, we keep it
queued up, although we set local_cork to 1. Commit 2e3216cd54b1
changed the precedence, so that as long as we get bundled, incoming
chunks we try possible bundling on outgoing queue as well. Before
this commit, we would just flush the output queue.
Now, while ASCONF_a's ASCONF_ACK sits in the corked outq, we
continue to process the same ASCONF_b chunk from the packet. As
we have cached the previous ASCONF_ACK, we find it, grab it and
do another SCTP_CMD_REPLY command on it. So, effectively, we rip
the chunk->list pointers and requeue the same ASCONF_ACK chunk
another time. Since we process ASCONF_b, it's correctly marked
with end_of_packet and we enforce an uncork, and thus flush, thus
crashing the kernel.
Fix it by testing if the ASCONF_ACK is currently pending and if
that is the case, do not requeue it. When flushing the output
queue we may relink the chunk for preparing an outgoing packet,
but eventually unlink it when it's copied into the skb right
before transmission.
Joint work with Vlad Yasevich.
Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (sctp_chunk_pending(ack))
continue;
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
| 166,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void perf_event_output(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct perf_output_handle handle;
struct perf_event_header header;
/* protect the callchain buffers */
rcu_read_lock();
perf_prepare_sample(&header, data, event, regs);
if (perf_output_begin(&handle, event, header.size, nmi, 1))
goto exit;
perf_output_sample(&handle, &header, data, event);
perf_output_end(&handle);
exit:
rcu_read_unlock();
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void perf_event_output(struct perf_event *event, int nmi,
static void perf_event_output(struct perf_event *event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct perf_output_handle handle;
struct perf_event_header header;
/* protect the callchain buffers */
rcu_read_lock();
perf_prepare_sample(&header, data, event, regs);
if (perf_output_begin(&handle, event, header.size, 1))
goto exit;
perf_output_sample(&handle, &header, data, event);
perf_output_end(&handle);
exit:
rcu_read_unlock();
}
| 165,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static PHP_FUNCTION(readgzfile)
{
char *filename;
int filename_len;
int flags = REPORT_ERRORS;
php_stream *stream;
int size;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &filename, &filename_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
size = php_stream_passthru(stream);
php_stream_close(stream);
RETURN_LONG(size);
}
Commit Message:
CWE ID: CWE-254 | static PHP_FUNCTION(readgzfile)
{
char *filename;
int filename_len;
int flags = REPORT_ERRORS;
php_stream *stream;
int size;
long use_include_path = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &filename, &filename_len, &use_include_path) == FAILURE) {
return;
}
if (use_include_path) {
flags |= USE_PATH;
}
stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC TSRMLS_CC);
if (!stream) {
RETURN_FALSE;
}
size = php_stream_passthru(stream);
php_stream_close(stream);
RETURN_LONG(size);
}
| 165,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,776 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Cluster* Segment::GetNext(const Cluster* pCurr)
{
assert(pCurr);
assert(pCurr != &m_eos);
assert(m_clusters);
long idx = pCurr->m_index;
if (idx >= 0)
{
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; //caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
}
assert(m_clusterPreloadCount > 0);
long long pos = pCurr->m_element_start;
assert(m_size >= 0); //TODO
const long long stop = m_start + m_size; //end of segment
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long id = ReadUInt(m_pReader, pos, len);
assert(id == 0x0F43B675); //Cluster ID
if (id != 0x0F43B675)
return NULL;
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size > 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
pos += size; //consume payload
}
long long off_next = 0;
while (pos < stop)
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long idpos = pos; //pos of next (potential) cluster
const long long id = ReadUInt(m_pReader, idpos, len);
assert(id > 0); //TODO
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size >= 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
if (size == 0) //weird
continue;
if (id == 0x0F43B675) //Cluster ID
{
const long long off_next_ = idpos - m_start;
long long pos_;
long len_;
const long status = Cluster::HasBlockEntries(
this,
off_next_,
pos_,
len_);
assert(status >= 0);
if (status > 0)
{
off_next = off_next_;
break;
}
}
pos += size; //consume payload
}
if (off_next <= 0)
return 0;
Cluster** const ii = m_clusters + m_clusterCount;
Cluster** i = ii;
Cluster** const jj = ii + m_clusterPreloadCount;
Cluster** j = jj;
while (i < j)
{
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pNext = *k;
assert(pNext);
assert(pNext->m_index < 0);
pos = pNext->GetPosition();
if (pos < off_next)
i = k + 1;
else if (pos > off_next)
j = k;
else
return pNext;
}
assert(i == j);
Cluster* const pNext = Cluster::Create(this,
-1,
off_next);
assert(pNext);
const ptrdiff_t idx_next = i - m_clusters; //insertion position
PreloadCluster(pNext, idx_next);
assert(m_clusters);
assert(idx_next < m_clusterSize);
assert(m_clusters[idx_next] == pNext);
return pNext;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cluster* Segment::GetNext(const Cluster* pCurr)
if (idx >= 0) {
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; // caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
| 174,347 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required,
SyncPromoUI::Source source)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
source_(source),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
| 171,245 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadVICARImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
c=ReadBlobByte(image);
count=1;
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
length=0;
image->columns=0;
image->rows=0;
while (isgraph(c) && ((image->columns == 0) || (image->rows == 0)))
{
if (isalnum(c) == MagickFalse)
{
c=ReadBlobByte(image);
count++;
}
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
count++;
}
if (value_expected == MagickFalse)
continue;
p=value;
while (isalnum(c))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"Label_RECORDS") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"LBLSIZE") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"RECORD_BYTES") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NS") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"LINES") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NL") == 0)
image->rows=StringToUnsignedLong(value);
}
while (isspace((int) ((unsigned char) c)) != 0)
{
c=ReadBlobByte(image);
count++;
}
}
while (count < (ssize_t) length)
{
c=ReadBlobByte(image);
count++;
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read VICAR pixels.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadVICARImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
c=ReadBlobByte(image);
count=1;
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
length=0;
image->columns=0;
image->rows=0;
while (isgraph(c) && ((image->columns == 0) || (image->rows == 0)))
{
if (isalnum(c) == MagickFalse)
{
c=ReadBlobByte(image);
count++;
}
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
count++;
}
if (value_expected == MagickFalse)
continue;
p=value;
while (isalnum(c))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"Label_RECORDS") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"LBLSIZE") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"RECORD_BYTES") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NS") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"LINES") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NL") == 0)
image->rows=StringToUnsignedLong(value);
}
while (isspace((int) ((unsigned char) c)) != 0)
{
c=ReadBlobByte(image);
count++;
}
}
while (count < (ssize_t) length)
{
c=ReadBlobByte(image);
count++;
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read VICAR pixels.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameHostImpl::RegisterMojoInterfaces() {
#if !defined(OS_ANDROID)
registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create));
#endif // !defined(OS_ANDROID)
PermissionControllerImpl* permission_controller =
PermissionControllerImpl::FromBrowserContext(
GetProcess()->GetBrowserContext());
if (delegate_) {
auto* geolocation_context = delegate_->GetGeolocationContext();
if (geolocation_context) {
geolocation_service_.reset(new GeolocationServiceImpl(
geolocation_context, permission_controller, this));
registry_->AddInterface(
base::Bind(&GeolocationServiceImpl::Bind,
base::Unretained(geolocation_service_.get())));
}
}
registry_->AddInterface<device::mojom::WakeLock>(base::Bind(
&RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this)));
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebNfc)) {
registry_->AddInterface<device::mojom::NFC>(base::Bind(
&RenderFrameHostImpl::BindNFCRequest, base::Unretained(this)));
}
#endif
if (!permission_service_context_)
permission_service_context_.reset(new PermissionServiceContext(this));
registry_->AddInterface(
base::Bind(&PermissionServiceContext::CreateService,
base::Unretained(permission_service_context_.get())));
registry_->AddInterface(
base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest,
base::Unretained(this)));
registry_->AddInterface(
base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this)));
registry_->AddInterface(base::Bind(
base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService),
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this)));
registry_->AddInterface<media::mojom::InterfaceFactory>(
base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest,
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateWebSocket, base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateDedicatedWorkerHostFactory,
base::Unretained(this)));
registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create,
process_->GetID(), routing_id_));
registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create));
registry_->AddInterface<device::mojom::VRService>(base::Bind(
&WebvrServiceProvider::BindWebvrService, base::Unretained(this)));
registry_->AddInterface(
base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory,
base::Unretained(this)));
registry_->AddInterface(
base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory,
base::Unretained(this)));
registry_->AddInterface(
base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this)));
if (BrowserMainLoop::GetInstance()) {
MediaStreamManager* media_stream_manager =
BrowserMainLoop::GetInstance()->media_stream_manager();
registry_->AddInterface(
base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(),
GetRoutingID(), base::Unretained(media_stream_manager)),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
registry_->AddInterface(
base::BindRepeating(
&RenderFrameHostImpl::CreateMediaStreamDispatcherHost,
base::Unretained(this), base::Unretained(media_stream_manager)),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
}
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind,
GetProcess()->GetID(), GetRoutingID()));
#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
registry_->AddInterface(base::BindRepeating(
&KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this)));
registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create));
#if !defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebAuth)) {
registry_->AddInterface(
base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest,
base::Unretained(this)));
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableWebAuthTestingAPI)) {
auto* environment_singleton =
ScopedVirtualAuthenticatorEnvironment::GetInstance();
registry_->AddInterface(base::BindRepeating(
&ScopedVirtualAuthenticatorEnvironment::AddBinding,
base::Unretained(environment_singleton)));
}
}
#endif // !defined(OS_ANDROID)
sensor_provider_proxy_.reset(
new SensorProviderProxyImpl(permission_controller, this));
registry_->AddInterface(
base::Bind(&SensorProviderProxyImpl::Bind,
base::Unretained(sensor_provider_proxy_.get())));
media::VideoDecodePerfHistory::SaveCallback save_stats_cb;
if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) {
save_stats_cb = GetSiteInstance()
->GetBrowserContext()
->GetVideoDecodePerfHistory()
->GetSaveCallback();
}
registry_->AddInterface(base::BindRepeating(
&media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(),
base::BindRepeating(
&RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource,
base::Unretained(delegate_)),
std::move(save_stats_cb)));
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
cc::switches::kEnableGpuBenchmarking)) {
registry_->AddInterface(
base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr()));
}
registry_->AddInterface(base::BindRepeating(
&QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_));
registry_->AddInterface(
base::BindRepeating(SpeechRecognitionDispatcherHost::Create,
GetProcess()->GetID(), routing_id_),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
file_system_manager_.reset(new FileSystemManagerImpl(
GetProcess()->GetID(), routing_id_,
GetProcess()->GetStoragePartition()->GetFileSystemContext(),
ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext())));
registry_->AddInterface(
base::BindRepeating(&FileSystemManagerImpl::BindRequest,
base::Unretained(file_system_manager_.get())),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
if (Portal::IsEnabled()) {
registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create),
base::Unretained(this)));
}
registry_->AddInterface(base::BindRepeating(
&BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_));
registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create));
registry_->AddInterface(
base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create,
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create,
base::Unretained(this)));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void RenderFrameHostImpl::RegisterMojoInterfaces() {
#if !defined(OS_ANDROID)
registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create));
#endif // !defined(OS_ANDROID)
PermissionControllerImpl* permission_controller =
PermissionControllerImpl::FromBrowserContext(
GetProcess()->GetBrowserContext());
if (delegate_) {
auto* geolocation_context = delegate_->GetGeolocationContext();
if (geolocation_context) {
geolocation_service_.reset(new GeolocationServiceImpl(
geolocation_context, permission_controller, this));
registry_->AddInterface(
base::Bind(&GeolocationServiceImpl::Bind,
base::Unretained(geolocation_service_.get())));
}
}
registry_->AddInterface<device::mojom::WakeLock>(base::Bind(
&RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this)));
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebNfc)) {
registry_->AddInterface<device::mojom::NFC>(base::Bind(
&RenderFrameHostImpl::BindNFCRequest, base::Unretained(this)));
}
#endif
if (!permission_service_context_)
permission_service_context_.reset(new PermissionServiceContext(this));
registry_->AddInterface(
base::Bind(&PermissionServiceContext::CreateService,
base::Unretained(permission_service_context_.get())));
registry_->AddInterface(
base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest,
base::Unretained(this)));
registry_->AddInterface(
base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this)));
registry_->AddInterface(base::Bind(
base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService),
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this)));
registry_->AddInterface<media::mojom::InterfaceFactory>(
base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest,
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateWebSocket, base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(
&RenderFrameHostImpl::CreateDedicatedWorkerHostFactory,
base::Unretained(this)));
registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create,
process_->GetID(), routing_id_));
registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create));
registry_->AddInterface<device::mojom::VRService>(base::Bind(
&WebvrServiceProvider::BindWebvrService, base::Unretained(this)));
registry_->AddInterface(
base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory,
base::Unretained(this)));
registry_->AddInterface(
base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory,
base::Unretained(this)));
registry_->AddInterface(
base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this)));
if (BrowserMainLoop::GetInstance()) {
MediaStreamManager* media_stream_manager =
BrowserMainLoop::GetInstance()->media_stream_manager();
registry_->AddInterface(
base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(),
GetRoutingID(), base::Unretained(media_stream_manager)),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
registry_->AddInterface(
base::BindRepeating(&MediaStreamDispatcherHost::Create,
GetProcess()->GetID(), GetRoutingID(),
base::Unretained(media_stream_manager)),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
}
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind,
GetProcess()->GetID(), GetRoutingID()));
#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
registry_->AddInterface(base::BindRepeating(
&KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this)));
registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create));
#if !defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebAuth)) {
registry_->AddInterface(
base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest,
base::Unretained(this)));
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableWebAuthTestingAPI)) {
auto* environment_singleton =
ScopedVirtualAuthenticatorEnvironment::GetInstance();
registry_->AddInterface(base::BindRepeating(
&ScopedVirtualAuthenticatorEnvironment::AddBinding,
base::Unretained(environment_singleton)));
}
}
#endif // !defined(OS_ANDROID)
sensor_provider_proxy_.reset(
new SensorProviderProxyImpl(permission_controller, this));
registry_->AddInterface(
base::Bind(&SensorProviderProxyImpl::Bind,
base::Unretained(sensor_provider_proxy_.get())));
media::VideoDecodePerfHistory::SaveCallback save_stats_cb;
if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) {
save_stats_cb = GetSiteInstance()
->GetBrowserContext()
->GetVideoDecodePerfHistory()
->GetSaveCallback();
}
registry_->AddInterface(base::BindRepeating(
&media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(),
base::BindRepeating(
&RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource,
base::Unretained(delegate_)),
std::move(save_stats_cb)));
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
cc::switches::kEnableGpuBenchmarking)) {
registry_->AddInterface(
base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr()));
}
registry_->AddInterface(base::BindRepeating(
&QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_));
registry_->AddInterface(
base::BindRepeating(SpeechRecognitionDispatcherHost::Create,
GetProcess()->GetID(), routing_id_),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
file_system_manager_.reset(new FileSystemManagerImpl(
GetProcess()->GetID(), routing_id_,
GetProcess()->GetStoragePartition()->GetFileSystemContext(),
ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext())));
registry_->AddInterface(
base::BindRepeating(&FileSystemManagerImpl::BindRequest,
base::Unretained(file_system_manager_.get())),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
if (Portal::IsEnabled()) {
registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create),
base::Unretained(this)));
}
registry_->AddInterface(base::BindRepeating(
&BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_));
registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create));
registry_->AddInterface(
base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create,
base::Unretained(this)));
registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create,
base::Unretained(this)));
}
| 173,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CURLcode Curl_close(struct Curl_easy *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire_clear(data); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy)
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
Curl_up_free(data);
Curl_safefree(data->state.buffer);
Curl_safefree(data->state.headerbuff);
Curl_safefree(data->state.ulbuf);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
Curl_freeset(data);
free(data);
return CURLE_OK;
}
Commit Message: Curl_close: clear data->multi_easy on free to avoid use-after-free
Regression from b46cfbc068 (7.59.0)
CVE-2018-16840
Reported-by: Brian Carpenter (Geeknik Labs)
Bug: https://curl.haxx.se/docs/CVE-2018-16840.html
CWE ID: CWE-416 | CURLcode Curl_close(struct Curl_easy *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire_clear(data); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy) {
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
data->multi_easy = NULL;
}
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
Curl_up_free(data);
Curl_safefree(data->state.buffer);
Curl_safefree(data->state.headerbuff);
Curl_safefree(data->state.ulbuf);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
Curl_freeset(data);
free(data);
return CURLE_OK;
}
| 169,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
Commit Message:
CWE ID: | hb_buffer_clear (hb_buffer_t *buffer)
{
buffer->have_output = FALSE;
buffer->have_positions = FALSE;
buffer->in_error = FALSE;
buffer->len = 0;
buffer->out_len = 0;
buffer->i = 0;
buffer->max_lig_id = 0;
buffer->max_lig_id = 0;
}
| 164,772 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void 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);
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: Use correct Request Context when EMBED or OBJECT requests an image
When an OBJECT or EMBED element requests an image, it does so using
an ImageLoader. To ensure that Content-Security-Policy restrictions
are applied correctly in this scenario, we must adjust the request's
context to indicate the originating element.
Bug: 811691
Change-Id: I0fd8010970a12e68e845a54310695acc0b3f7625
Reviewed-on: https://chromium-review.googlesource.com/924589
Commit-Queue: Eric Lawrence <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#537846}
CWE ID: CWE-20 | 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()));
}
// Correct the RequestContext if necessary.
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();
}
| 172,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_ms_alloc(int flags)
{
struct magic_set *ms;
size_t i, len;
if ((ms = CAST(struct magic_set *, calloc((size_t)1,
sizeof(struct magic_set)))) == NULL)
return NULL;
if (magic_setflags(ms, flags) == -1) {
errno = EINVAL;
goto free;
}
ms->o.buf = ms->o.pbuf = NULL;
len = (ms->c.len = 10) * sizeof(*ms->c.li);
if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
goto free;
ms->event_flags = 0;
ms->error = -1;
for (i = 0; i < MAGIC_SETS; i++)
ms->mlist[i] = NULL;
ms->file = "unknown";
ms->line = 0;
ms->indir_max = FILE_INDIR_MAX;
ms->name_max = FILE_NAME_MAX;
ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
return ms;
free:
free(ms);
return NULL;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | file_ms_alloc(int flags)
{
struct magic_set *ms;
size_t i, len;
if ((ms = CAST(struct magic_set *, calloc((size_t)1,
sizeof(struct magic_set)))) == NULL)
return NULL;
if (magic_setflags(ms, flags) == -1) {
errno = EINVAL;
goto free;
}
ms->o.buf = ms->o.pbuf = NULL;
len = (ms->c.len = 10) * sizeof(*ms->c.li);
if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
goto free;
ms->event_flags = 0;
ms->error = -1;
for (i = 0; i < MAGIC_SETS; i++)
ms->mlist[i] = NULL;
ms->file = "unknown";
ms->line = 0;
ms->indir_max = FILE_INDIR_MAX;
ms->name_max = FILE_NAME_MAX;
ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
ms->elf_notes_max = FILE_ELF_NOTES_MAX;
return ms;
free:
free(ms);
return NULL;
}
| 166,773 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Extension::InitFromValue(const DictionaryValue& source, int flags,
std::string* error) {
URLPattern::ParseOption parse_strictness =
(flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT
: URLPattern::PARSE_LENIENT);
if (source.HasKey(keys::kPublicKey)) {
std::string public_key_bytes;
if (!source.GetString(keys::kPublicKey,
&public_key_) ||
!ParsePEMKeyBytes(public_key_,
&public_key_bytes) ||
!GenerateId(public_key_bytes, &id_)) {
*error = errors::kInvalidKey;
return false;
}
} else if (flags & REQUIRE_KEY) {
*error = errors::kInvalidKey;
return false;
} else {
id_ = Extension::GenerateIdForPath(path());
if (id_.empty()) {
NOTREACHED() << "Could not create ID from path.";
return false;
}
}
manifest_value_.reset(source.DeepCopy());
extension_url_ = Extension::GetBaseURLFromExtensionId(id());
std::string version_str;
if (!source.GetString(keys::kVersion, &version_str)) {
*error = errors::kInvalidVersion;
return false;
}
version_.reset(Version::GetVersionFromString(version_str));
if (!version_.get() ||
version_->components().size() > 4) {
*error = errors::kInvalidVersion;
return false;
}
string16 localized_name;
if (!source.GetString(keys::kName, &localized_name)) {
*error = errors::kInvalidName;
return false;
}
base::i18n::AdjustStringForLocaleDirection(&localized_name);
name_ = UTF16ToUTF8(localized_name);
if (source.HasKey(keys::kDescription)) {
if (!source.GetString(keys::kDescription,
&description_)) {
*error = errors::kInvalidDescription;
return false;
}
}
if (source.HasKey(keys::kHomepageURL)) {
std::string tmp;
if (!source.GetString(keys::kHomepageURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, "");
return false;
}
homepage_url_ = GURL(tmp);
if (!homepage_url_.is_valid()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, tmp);
return false;
}
}
if (source.HasKey(keys::kUpdateURL)) {
std::string tmp;
if (!source.GetString(keys::kUpdateURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, "");
return false;
}
update_url_ = GURL(tmp);
if (!update_url_.is_valid() ||
update_url_.has_ref()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, tmp);
return false;
}
}
if (source.HasKey(keys::kMinimumChromeVersion)) {
std::string minimum_version_string;
if (!source.GetString(keys::kMinimumChromeVersion,
&minimum_version_string)) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
scoped_ptr<Version> minimum_version(
Version::GetVersionFromString(minimum_version_string));
if (!minimum_version.get()) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
chrome::VersionInfo current_version_info;
if (!current_version_info.is_valid()) {
NOTREACHED();
return false;
}
scoped_ptr<Version> current_version(
Version::GetVersionFromString(current_version_info.Version()));
if (!current_version.get()) {
DCHECK(false);
return false;
}
if (current_version->CompareTo(*minimum_version) < 0) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kChromeVersionTooLow,
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME),
minimum_version_string);
return false;
}
}
source.GetBoolean(keys::kConvertedFromUserScript,
&converted_from_user_script_);
if (source.HasKey(keys::kIcons)) {
DictionaryValue* icons_value = NULL;
if (!source.GetDictionary(keys::kIcons, &icons_value)) {
*error = errors::kInvalidIcons;
return false;
}
for (size_t i = 0; i < arraysize(kIconSizes); ++i) {
std::string key = base::IntToString(kIconSizes[i]);
if (icons_value->HasKey(key)) {
std::string icon_path;
if (!icons_value->GetString(key, &icon_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
if (!icon_path.empty() && icon_path[0] == '/')
icon_path = icon_path.substr(1);
if (icon_path.empty()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
icons_.Add(kIconSizes[i], icon_path);
}
}
}
is_theme_ = false;
if (source.HasKey(keys::kTheme)) {
if (ContainsNonThemeKeys(source)) {
*error = errors::kThemesCannotContainExtensions;
return false;
}
DictionaryValue* theme_value = NULL;
if (!source.GetDictionary(keys::kTheme, &theme_value)) {
*error = errors::kInvalidTheme;
return false;
}
is_theme_ = true;
DictionaryValue* images_value = NULL;
if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) {
for (DictionaryValue::key_iterator iter = images_value->begin_keys();
iter != images_value->end_keys(); ++iter) {
std::string val;
if (!images_value->GetString(*iter, &val)) {
*error = errors::kInvalidThemeImages;
return false;
}
}
theme_images_.reset(images_value->DeepCopy());
}
DictionaryValue* colors_value = NULL;
if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) {
for (DictionaryValue::key_iterator iter = colors_value->begin_keys();
iter != colors_value->end_keys(); ++iter) {
ListValue* color_list = NULL;
double alpha = 0.0;
int color = 0;
if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) ||
((color_list->GetSize() != 3) &&
((color_list->GetSize() != 4) ||
!color_list->GetDouble(3, &alpha))) ||
!color_list->GetInteger(0, &color) ||
!color_list->GetInteger(1, &color) ||
!color_list->GetInteger(2, &color)) {
*error = errors::kInvalidThemeColors;
return false;
}
}
theme_colors_.reset(colors_value->DeepCopy());
}
DictionaryValue* tints_value = NULL;
if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) {
for (DictionaryValue::key_iterator iter = tints_value->begin_keys();
iter != tints_value->end_keys(); ++iter) {
ListValue* tint_list = NULL;
double v = 0.0;
if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) ||
tint_list->GetSize() != 3 ||
!tint_list->GetDouble(0, &v) ||
!tint_list->GetDouble(1, &v) ||
!tint_list->GetDouble(2, &v)) {
*error = errors::kInvalidThemeTints;
return false;
}
}
theme_tints_.reset(tints_value->DeepCopy());
}
DictionaryValue* display_properties_value = NULL;
if (theme_value->GetDictionary(keys::kThemeDisplayProperties,
&display_properties_value)) {
theme_display_properties_.reset(
display_properties_value->DeepCopy());
}
return true;
}
if (source.HasKey(keys::kPlugins)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPlugins, &list_value)) {
*error = errors::kInvalidPlugins;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* plugin_value = NULL;
std::string path_str;
bool is_public = false;
if (!list_value->GetDictionary(i, &plugin_value)) {
*error = errors::kInvalidPlugins;
return false;
}
if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPath, base::IntToString(i));
return false;
}
if (plugin_value->HasKey(keys::kPluginsPublic)) {
if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPublic, base::IntToString(i));
return false;
}
}
#if !defined(OS_CHROMEOS)
plugins_.push_back(PluginInfo());
plugins_.back().path = path().AppendASCII(path_str);
plugins_.back().is_public = is_public;
#endif
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kNaClModules)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kNaClModules, &list_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* module_value = NULL;
std::string path_str;
std::string mime_type;
if (!list_value->GetDictionary(i, &module_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesPath, base::IntToString(i));
return false;
}
if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesMIMEType, base::IntToString(i));
return false;
}
nacl_modules_.push_back(NaClModuleInfo());
nacl_modules_.back().url = GetResourceURL(path_str);
nacl_modules_.back().mime_type = mime_type;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kToolstrips)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kToolstrips, &list_value)) {
*error = errors::kInvalidToolstrips;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
GURL toolstrip;
DictionaryValue* toolstrip_value = NULL;
std::string toolstrip_path;
if (list_value->GetString(i, &toolstrip_path)) {
toolstrip = GetResourceURL(toolstrip_path);
} else if (list_value->GetDictionary(i, &toolstrip_value)) {
if (!toolstrip_value->GetString(keys::kToolstripPath,
&toolstrip_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrip = GetResourceURL(toolstrip_path);
} else {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrips_.push_back(toolstrip);
}
}
if (source.HasKey(keys::kContentScripts)) {
ListValue* list_value;
if (!source.GetList(keys::kContentScripts, &list_value)) {
*error = errors::kInvalidContentScriptsList;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* content_script = NULL;
if (!list_value->GetDictionary(i, &content_script)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidContentScript, base::IntToString(i));
return false;
}
UserScript script;
if (!LoadUserScriptHelper(content_script, i, flags, error, &script))
return false; // Failed to parse script context definition.
script.set_extension_id(id());
if (converted_from_user_script_) {
script.set_emulate_greasemonkey(true);
script.set_match_all_frames(true); // Greasemonkey matches all frames.
}
content_scripts_.push_back(script);
}
}
DictionaryValue* page_action_value = NULL;
if (source.HasKey(keys::kPageActions)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPageActions, &list_value)) {
*error = errors::kInvalidPageActionsList;
return false;
}
size_t list_value_length = list_value->GetSize();
if (list_value_length == 0u) {
} else if (list_value_length == 1u) {
if (!list_value->GetDictionary(0, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
} else { // list_value_length > 1u.
*error = errors::kInvalidPageActionsListSize;
return false;
}
} else if (source.HasKey(keys::kPageAction)) {
if (!source.GetDictionary(keys::kPageAction, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
}
if (page_action_value) {
page_action_.reset(
LoadExtensionActionHelper(page_action_value, error));
if (!page_action_.get())
return false; // Failed to parse page action definition.
}
if (source.HasKey(keys::kBrowserAction)) {
DictionaryValue* browser_action_value = NULL;
if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) {
*error = errors::kInvalidBrowserAction;
return false;
}
browser_action_.reset(
LoadExtensionActionHelper(browser_action_value, error));
if (!browser_action_.get())
return false; // Failed to parse browser action definition.
}
if (source.HasKey(keys::kFileBrowserHandlers)) {
ListValue* file_browser_handlers_value = NULL;
if (!source.GetList(keys::kFileBrowserHandlers,
&file_browser_handlers_value)) {
*error = errors::kInvalidFileBrowserHandler;
return false;
}
file_browser_handlers_.reset(
LoadFileBrowserHandlers(file_browser_handlers_value, error));
if (!file_browser_handlers_.get())
return false; // Failed to parse file browser actions definition.
}
if (!LoadIsApp(manifest_value_.get(), error) ||
!LoadExtent(manifest_value_.get(), keys::kWebURLs,
&extent_,
errors::kInvalidWebURLs, errors::kInvalidWebURL,
parse_strictness, error) ||
!EnsureNotHybridApp(manifest_value_.get(), error) ||
!LoadLaunchURL(manifest_value_.get(), error) ||
!LoadLaunchContainer(manifest_value_.get(), error) ||
!LoadAppIsolation(manifest_value_.get(), error)) {
return false;
}
if (source.HasKey(keys::kOptionsPage)) {
std::string options_str;
if (!source.GetString(keys::kOptionsPage, &options_str)) {
*error = errors::kInvalidOptionsPage;
return false;
}
if (is_hosted_app()) {
GURL options_url(options_str);
if (!options_url.is_valid() ||
!(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) {
*error = errors::kInvalidOptionsPageInHostedApp;
return false;
}
options_url_ = options_url;
} else {
GURL absolute(options_str);
if (absolute.is_valid()) {
*error = errors::kInvalidOptionsPageExpectUrlInPackage;
return false;
}
options_url_ = GetResourceURL(options_str);
if (!options_url_.is_valid()) {
*error = errors::kInvalidOptionsPage;
return false;
}
}
}
if (source.HasKey(keys::kPermissions)) {
ListValue* permissions = NULL;
if (!source.GetList(keys::kPermissions, &permissions)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissions, "");
return false;
}
for (size_t i = 0; i < permissions->GetSize(); ++i) {
std::string permission_str;
if (!permissions->GetString(i, &permission_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermission, base::IntToString(i));
return false;
}
if (!IsComponentOnlyPermission(permission_str)
#ifndef NDEBUG
&& !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExposePrivateExtensionApi)
#endif
) {
continue;
}
if (permission_str == kOldUnlimitedStoragePermission)
permission_str = kUnlimitedStoragePermission;
if (web_extent().is_empty() || location() == Extension::COMPONENT) {
if (IsAPIPermission(permission_str)) {
if (permission_str == Extension::kExperimentalPermission &&
!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
location() != Extension::COMPONENT) {
*error = errors::kExperimentalFlagRequired;
return false;
}
api_permissions_.insert(permission_str);
continue;
}
} else {
if (IsHostedAppPermission(permission_str)) {
api_permissions_.insert(permission_str);
continue;
}
}
URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ?
URLPattern::SCHEME_ALL : kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = pattern.Parse(permission_str,
parse_strictness);
if (parse_result == URLPattern::PARSE_SUCCESS) {
if (!CanSpecifyHostPermission(pattern)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissionScheme, base::IntToString(i));
return false;
}
pattern.SetPath("/*");
if (pattern.MatchesScheme(chrome::kFileScheme) &&
!CanExecuteScriptEverywhere()) {
wants_file_access_ = true;
if (!(flags & ALLOW_FILE_ACCESS))
pattern.set_valid_schemes(
pattern.valid_schemes() & ~URLPattern::SCHEME_FILE);
}
host_permissions_.push_back(pattern);
}
}
}
if (source.HasKey(keys::kBackground)) {
std::string background_str;
if (!source.GetString(keys::kBackground, &background_str)) {
*error = errors::kInvalidBackground;
return false;
}
if (is_hosted_app()) {
if (api_permissions_.find(kBackgroundPermission) ==
api_permissions_.end()) {
*error = errors::kBackgroundPermissionNeeded;
return false;
}
GURL bg_page(background_str);
if (!bg_page.is_valid()) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
if (!(bg_page.SchemeIs("https") ||
(CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAllowHTTPBackgroundPage) &&
bg_page.SchemeIs("http")))) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
background_url_ = bg_page;
} else {
background_url_ = GetResourceURL(background_str);
}
}
if (source.HasKey(keys::kDefaultLocale)) {
if (!source.GetString(keys::kDefaultLocale, &default_locale_) ||
!l10n_util::IsValidLocaleSyntax(default_locale_)) {
*error = errors::kInvalidDefaultLocale;
return false;
}
}
if (source.HasKey(keys::kChromeURLOverrides)) {
DictionaryValue* overrides = NULL;
if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
for (DictionaryValue::key_iterator iter = overrides->begin_keys();
iter != overrides->end_keys(); ++iter) {
std::string page = *iter;
std::string val;
if ((page != chrome::kChromeUINewTabHost &&
#if defined(TOUCH_UI)
page != chrome::kChromeUIKeyboardHost &&
#endif
#if defined(OS_CHROMEOS)
page != chrome::kChromeUIActivationMessageHost &&
#endif
page != chrome::kChromeUIBookmarksHost &&
page != chrome::kChromeUIHistoryHost) ||
!overrides->GetStringWithoutPathExpansion(*iter, &val)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
chrome_url_overrides_[page] = GetResourceURL(val);
}
if (overrides->size() > 1) {
*error = errors::kMultipleOverrides;
return false;
}
}
if (source.HasKey(keys::kOmnibox)) {
if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) ||
omnibox_keyword_.empty()) {
*error = errors::kInvalidOmniboxKeyword;
return false;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kContentSecurityPolicy)) {
std::string content_security_policy;
if (!source.GetString(keys::kContentSecurityPolicy,
&content_security_policy)) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
const char kBadCSPCharacters[] = {'\r', '\n', '\0'};
if (content_security_policy.find_first_of(kBadCSPCharacters, 0,
arraysize(kBadCSPCharacters)) !=
std::string::npos) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
content_security_policy_ = content_security_policy;
}
if (source.HasKey(keys::kDevToolsPage)) {
std::string devtools_str;
if (!source.GetString(keys::kDevToolsPage, &devtools_str)) {
*error = errors::kInvalidDevToolsPage;
return false;
}
if (!HasApiPermission(Extension::kExperimentalPermission)) {
*error = errors::kDevToolsExperimental;
return false;
}
devtools_url_ = GetResourceURL(devtools_str);
}
if (source.HasKey(keys::kSidebar)) {
DictionaryValue* sidebar_value = NULL;
if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) {
*error = errors::kInvalidSidebar;
return false;
}
if (!HasApiPermission(Extension::kExperimentalPermission)) {
*error = errors::kSidebarExperimental;
return false;
}
sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error));
if (!sidebar_defaults_.get())
return false; // Failed to parse sidebar definition.
}
if (source.HasKey(keys::kTts)) {
DictionaryValue* tts_dict = NULL;
if (!source.GetDictionary(keys::kTts, &tts_dict)) {
*error = errors::kInvalidTts;
return false;
}
if (tts_dict->HasKey(keys::kTtsVoices)) {
ListValue* tts_voices = NULL;
if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) {
*error = errors::kInvalidTtsVoices;
return false;
}
for (size_t i = 0; i < tts_voices->GetSize(); i++) {
DictionaryValue* one_tts_voice = NULL;
if (!tts_voices->GetDictionary(i, &one_tts_voice)) {
*error = errors::kInvalidTtsVoices;
return false;
}
TtsVoice voice_data;
if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesVoiceName, &voice_data.voice_name)) {
*error = errors::kInvalidTtsVoicesVoiceName;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesLocale, &voice_data.locale) ||
!l10n_util::IsValidLocaleSyntax(voice_data.locale)) {
*error = errors::kInvalidTtsVoicesLocale;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesGender, &voice_data.gender) ||
(voice_data.gender != keys::kTtsGenderMale &&
voice_data.gender != keys::kTtsGenderFemale)) {
*error = errors::kInvalidTtsVoicesGender;
return false;
}
}
tts_voices_.push_back(voice_data);
}
}
}
incognito_split_mode_ = is_app();
if (source.HasKey(keys::kIncognito)) {
std::string value;
if (!source.GetString(keys::kIncognito, &value)) {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
if (value == values::kIncognitoSpanning) {
incognito_split_mode_ = false;
} else if (value == values::kIncognitoSplit) {
incognito_split_mode_ = true;
} else {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
}
if (HasMultipleUISurfaces()) {
*error = errors::kOneUISurfaceOnly;
return false;
}
InitEffectiveHostPermissions();
DCHECK(source.Equals(manifest_value_.get()));
return true;
}
Commit Message: Prevent extensions from defining homepages with schemes other than valid web extents.
BUG=84402
TEST=ExtensionManifestTest.ParseHomepageURLs
Review URL: http://codereview.chromium.org/7089014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87722 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool Extension::InitFromValue(const DictionaryValue& source, int flags,
std::string* error) {
URLPattern::ParseOption parse_strictness =
(flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT
: URLPattern::PARSE_LENIENT);
if (source.HasKey(keys::kPublicKey)) {
std::string public_key_bytes;
if (!source.GetString(keys::kPublicKey,
&public_key_) ||
!ParsePEMKeyBytes(public_key_,
&public_key_bytes) ||
!GenerateId(public_key_bytes, &id_)) {
*error = errors::kInvalidKey;
return false;
}
} else if (flags & REQUIRE_KEY) {
*error = errors::kInvalidKey;
return false;
} else {
id_ = Extension::GenerateIdForPath(path());
if (id_.empty()) {
NOTREACHED() << "Could not create ID from path.";
return false;
}
}
manifest_value_.reset(source.DeepCopy());
extension_url_ = Extension::GetBaseURLFromExtensionId(id());
std::string version_str;
if (!source.GetString(keys::kVersion, &version_str)) {
*error = errors::kInvalidVersion;
return false;
}
version_.reset(Version::GetVersionFromString(version_str));
if (!version_.get() ||
version_->components().size() > 4) {
*error = errors::kInvalidVersion;
return false;
}
string16 localized_name;
if (!source.GetString(keys::kName, &localized_name)) {
*error = errors::kInvalidName;
return false;
}
base::i18n::AdjustStringForLocaleDirection(&localized_name);
name_ = UTF16ToUTF8(localized_name);
if (source.HasKey(keys::kDescription)) {
if (!source.GetString(keys::kDescription,
&description_)) {
*error = errors::kInvalidDescription;
return false;
}
}
if (source.HasKey(keys::kHomepageURL)) {
std::string tmp;
if (!source.GetString(keys::kHomepageURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, "");
return false;
}
homepage_url_ = GURL(tmp);
if (!homepage_url_.is_valid() ||
(!homepage_url_.SchemeIs("http") &&
!homepage_url_.SchemeIs("https"))) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidHomepageURL, tmp);
return false;
}
}
if (source.HasKey(keys::kUpdateURL)) {
std::string tmp;
if (!source.GetString(keys::kUpdateURL, &tmp)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, "");
return false;
}
update_url_ = GURL(tmp);
if (!update_url_.is_valid() ||
update_url_.has_ref()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidUpdateURL, tmp);
return false;
}
}
if (source.HasKey(keys::kMinimumChromeVersion)) {
std::string minimum_version_string;
if (!source.GetString(keys::kMinimumChromeVersion,
&minimum_version_string)) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
scoped_ptr<Version> minimum_version(
Version::GetVersionFromString(minimum_version_string));
if (!minimum_version.get()) {
*error = errors::kInvalidMinimumChromeVersion;
return false;
}
chrome::VersionInfo current_version_info;
if (!current_version_info.is_valid()) {
NOTREACHED();
return false;
}
scoped_ptr<Version> current_version(
Version::GetVersionFromString(current_version_info.Version()));
if (!current_version.get()) {
DCHECK(false);
return false;
}
if (current_version->CompareTo(*minimum_version) < 0) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kChromeVersionTooLow,
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME),
minimum_version_string);
return false;
}
}
source.GetBoolean(keys::kConvertedFromUserScript,
&converted_from_user_script_);
if (source.HasKey(keys::kIcons)) {
DictionaryValue* icons_value = NULL;
if (!source.GetDictionary(keys::kIcons, &icons_value)) {
*error = errors::kInvalidIcons;
return false;
}
for (size_t i = 0; i < arraysize(kIconSizes); ++i) {
std::string key = base::IntToString(kIconSizes[i]);
if (icons_value->HasKey(key)) {
std::string icon_path;
if (!icons_value->GetString(key, &icon_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
if (!icon_path.empty() && icon_path[0] == '/')
icon_path = icon_path.substr(1);
if (icon_path.empty()) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidIconPath, key);
return false;
}
icons_.Add(kIconSizes[i], icon_path);
}
}
}
is_theme_ = false;
if (source.HasKey(keys::kTheme)) {
if (ContainsNonThemeKeys(source)) {
*error = errors::kThemesCannotContainExtensions;
return false;
}
DictionaryValue* theme_value = NULL;
if (!source.GetDictionary(keys::kTheme, &theme_value)) {
*error = errors::kInvalidTheme;
return false;
}
is_theme_ = true;
DictionaryValue* images_value = NULL;
if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) {
for (DictionaryValue::key_iterator iter = images_value->begin_keys();
iter != images_value->end_keys(); ++iter) {
std::string val;
if (!images_value->GetString(*iter, &val)) {
*error = errors::kInvalidThemeImages;
return false;
}
}
theme_images_.reset(images_value->DeepCopy());
}
DictionaryValue* colors_value = NULL;
if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) {
for (DictionaryValue::key_iterator iter = colors_value->begin_keys();
iter != colors_value->end_keys(); ++iter) {
ListValue* color_list = NULL;
double alpha = 0.0;
int color = 0;
if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) ||
((color_list->GetSize() != 3) &&
((color_list->GetSize() != 4) ||
!color_list->GetDouble(3, &alpha))) ||
!color_list->GetInteger(0, &color) ||
!color_list->GetInteger(1, &color) ||
!color_list->GetInteger(2, &color)) {
*error = errors::kInvalidThemeColors;
return false;
}
}
theme_colors_.reset(colors_value->DeepCopy());
}
DictionaryValue* tints_value = NULL;
if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) {
for (DictionaryValue::key_iterator iter = tints_value->begin_keys();
iter != tints_value->end_keys(); ++iter) {
ListValue* tint_list = NULL;
double v = 0.0;
if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) ||
tint_list->GetSize() != 3 ||
!tint_list->GetDouble(0, &v) ||
!tint_list->GetDouble(1, &v) ||
!tint_list->GetDouble(2, &v)) {
*error = errors::kInvalidThemeTints;
return false;
}
}
theme_tints_.reset(tints_value->DeepCopy());
}
DictionaryValue* display_properties_value = NULL;
if (theme_value->GetDictionary(keys::kThemeDisplayProperties,
&display_properties_value)) {
theme_display_properties_.reset(
display_properties_value->DeepCopy());
}
return true;
}
if (source.HasKey(keys::kPlugins)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPlugins, &list_value)) {
*error = errors::kInvalidPlugins;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* plugin_value = NULL;
std::string path_str;
bool is_public = false;
if (!list_value->GetDictionary(i, &plugin_value)) {
*error = errors::kInvalidPlugins;
return false;
}
if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPath, base::IntToString(i));
return false;
}
if (plugin_value->HasKey(keys::kPluginsPublic)) {
if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPluginsPublic, base::IntToString(i));
return false;
}
}
#if !defined(OS_CHROMEOS)
plugins_.push_back(PluginInfo());
plugins_.back().path = path().AppendASCII(path_str);
plugins_.back().is_public = is_public;
#endif
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kNaClModules)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kNaClModules, &list_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* module_value = NULL;
std::string path_str;
std::string mime_type;
if (!list_value->GetDictionary(i, &module_value)) {
*error = errors::kInvalidNaClModules;
return false;
}
if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesPath, base::IntToString(i));
return false;
}
if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidNaClModulesMIMEType, base::IntToString(i));
return false;
}
nacl_modules_.push_back(NaClModuleInfo());
nacl_modules_.back().url = GetResourceURL(path_str);
nacl_modules_.back().mime_type = mime_type;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kToolstrips)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kToolstrips, &list_value)) {
*error = errors::kInvalidToolstrips;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
GURL toolstrip;
DictionaryValue* toolstrip_value = NULL;
std::string toolstrip_path;
if (list_value->GetString(i, &toolstrip_path)) {
toolstrip = GetResourceURL(toolstrip_path);
} else if (list_value->GetDictionary(i, &toolstrip_value)) {
if (!toolstrip_value->GetString(keys::kToolstripPath,
&toolstrip_path)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrip = GetResourceURL(toolstrip_path);
} else {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidToolstrip, base::IntToString(i));
return false;
}
toolstrips_.push_back(toolstrip);
}
}
if (source.HasKey(keys::kContentScripts)) {
ListValue* list_value;
if (!source.GetList(keys::kContentScripts, &list_value)) {
*error = errors::kInvalidContentScriptsList;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* content_script = NULL;
if (!list_value->GetDictionary(i, &content_script)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidContentScript, base::IntToString(i));
return false;
}
UserScript script;
if (!LoadUserScriptHelper(content_script, i, flags, error, &script))
return false; // Failed to parse script context definition.
script.set_extension_id(id());
if (converted_from_user_script_) {
script.set_emulate_greasemonkey(true);
script.set_match_all_frames(true); // Greasemonkey matches all frames.
}
content_scripts_.push_back(script);
}
}
DictionaryValue* page_action_value = NULL;
if (source.HasKey(keys::kPageActions)) {
ListValue* list_value = NULL;
if (!source.GetList(keys::kPageActions, &list_value)) {
*error = errors::kInvalidPageActionsList;
return false;
}
size_t list_value_length = list_value->GetSize();
if (list_value_length == 0u) {
} else if (list_value_length == 1u) {
if (!list_value->GetDictionary(0, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
} else { // list_value_length > 1u.
*error = errors::kInvalidPageActionsListSize;
return false;
}
} else if (source.HasKey(keys::kPageAction)) {
if (!source.GetDictionary(keys::kPageAction, &page_action_value)) {
*error = errors::kInvalidPageAction;
return false;
}
}
if (page_action_value) {
page_action_.reset(
LoadExtensionActionHelper(page_action_value, error));
if (!page_action_.get())
return false; // Failed to parse page action definition.
}
if (source.HasKey(keys::kBrowserAction)) {
DictionaryValue* browser_action_value = NULL;
if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) {
*error = errors::kInvalidBrowserAction;
return false;
}
browser_action_.reset(
LoadExtensionActionHelper(browser_action_value, error));
if (!browser_action_.get())
return false; // Failed to parse browser action definition.
}
if (source.HasKey(keys::kFileBrowserHandlers)) {
ListValue* file_browser_handlers_value = NULL;
if (!source.GetList(keys::kFileBrowserHandlers,
&file_browser_handlers_value)) {
*error = errors::kInvalidFileBrowserHandler;
return false;
}
file_browser_handlers_.reset(
LoadFileBrowserHandlers(file_browser_handlers_value, error));
if (!file_browser_handlers_.get())
return false; // Failed to parse file browser actions definition.
}
if (!LoadIsApp(manifest_value_.get(), error) ||
!LoadExtent(manifest_value_.get(), keys::kWebURLs,
&extent_,
errors::kInvalidWebURLs, errors::kInvalidWebURL,
parse_strictness, error) ||
!EnsureNotHybridApp(manifest_value_.get(), error) ||
!LoadLaunchURL(manifest_value_.get(), error) ||
!LoadLaunchContainer(manifest_value_.get(), error) ||
!LoadAppIsolation(manifest_value_.get(), error)) {
return false;
}
if (source.HasKey(keys::kOptionsPage)) {
std::string options_str;
if (!source.GetString(keys::kOptionsPage, &options_str)) {
*error = errors::kInvalidOptionsPage;
return false;
}
if (is_hosted_app()) {
GURL options_url(options_str);
if (!options_url.is_valid() ||
!(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) {
*error = errors::kInvalidOptionsPageInHostedApp;
return false;
}
options_url_ = options_url;
} else {
GURL absolute(options_str);
if (absolute.is_valid()) {
*error = errors::kInvalidOptionsPageExpectUrlInPackage;
return false;
}
options_url_ = GetResourceURL(options_str);
if (!options_url_.is_valid()) {
*error = errors::kInvalidOptionsPage;
return false;
}
}
}
if (source.HasKey(keys::kPermissions)) {
ListValue* permissions = NULL;
if (!source.GetList(keys::kPermissions, &permissions)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissions, "");
return false;
}
for (size_t i = 0; i < permissions->GetSize(); ++i) {
std::string permission_str;
if (!permissions->GetString(i, &permission_str)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermission, base::IntToString(i));
return false;
}
if (!IsComponentOnlyPermission(permission_str)
#ifndef NDEBUG
&& !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExposePrivateExtensionApi)
#endif
) {
continue;
}
if (permission_str == kOldUnlimitedStoragePermission)
permission_str = kUnlimitedStoragePermission;
if (web_extent().is_empty() || location() == Extension::COMPONENT) {
if (IsAPIPermission(permission_str)) {
if (permission_str == Extension::kExperimentalPermission &&
!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
location() != Extension::COMPONENT) {
*error = errors::kExperimentalFlagRequired;
return false;
}
api_permissions_.insert(permission_str);
continue;
}
} else {
if (IsHostedAppPermission(permission_str)) {
api_permissions_.insert(permission_str);
continue;
}
}
URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ?
URLPattern::SCHEME_ALL : kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = pattern.Parse(permission_str,
parse_strictness);
if (parse_result == URLPattern::PARSE_SUCCESS) {
if (!CanSpecifyHostPermission(pattern)) {
*error = ExtensionErrorUtils::FormatErrorMessage(
errors::kInvalidPermissionScheme, base::IntToString(i));
return false;
}
pattern.SetPath("/*");
if (pattern.MatchesScheme(chrome::kFileScheme) &&
!CanExecuteScriptEverywhere()) {
wants_file_access_ = true;
if (!(flags & ALLOW_FILE_ACCESS))
pattern.set_valid_schemes(
pattern.valid_schemes() & ~URLPattern::SCHEME_FILE);
}
host_permissions_.push_back(pattern);
}
}
}
if (source.HasKey(keys::kBackground)) {
std::string background_str;
if (!source.GetString(keys::kBackground, &background_str)) {
*error = errors::kInvalidBackground;
return false;
}
if (is_hosted_app()) {
if (api_permissions_.find(kBackgroundPermission) ==
api_permissions_.end()) {
*error = errors::kBackgroundPermissionNeeded;
return false;
}
GURL bg_page(background_str);
if (!bg_page.is_valid()) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
if (!(bg_page.SchemeIs("https") ||
(CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAllowHTTPBackgroundPage) &&
bg_page.SchemeIs("http")))) {
*error = errors::kInvalidBackgroundInHostedApp;
return false;
}
background_url_ = bg_page;
} else {
background_url_ = GetResourceURL(background_str);
}
}
if (source.HasKey(keys::kDefaultLocale)) {
if (!source.GetString(keys::kDefaultLocale, &default_locale_) ||
!l10n_util::IsValidLocaleSyntax(default_locale_)) {
*error = errors::kInvalidDefaultLocale;
return false;
}
}
if (source.HasKey(keys::kChromeURLOverrides)) {
DictionaryValue* overrides = NULL;
if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
for (DictionaryValue::key_iterator iter = overrides->begin_keys();
iter != overrides->end_keys(); ++iter) {
std::string page = *iter;
std::string val;
if ((page != chrome::kChromeUINewTabHost &&
#if defined(TOUCH_UI)
page != chrome::kChromeUIKeyboardHost &&
#endif
#if defined(OS_CHROMEOS)
page != chrome::kChromeUIActivationMessageHost &&
#endif
page != chrome::kChromeUIBookmarksHost &&
page != chrome::kChromeUIHistoryHost) ||
!overrides->GetStringWithoutPathExpansion(*iter, &val)) {
*error = errors::kInvalidChromeURLOverrides;
return false;
}
chrome_url_overrides_[page] = GetResourceURL(val);
}
if (overrides->size() > 1) {
*error = errors::kMultipleOverrides;
return false;
}
}
if (source.HasKey(keys::kOmnibox)) {
if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) ||
omnibox_keyword_.empty()) {
*error = errors::kInvalidOmniboxKeyword;
return false;
}
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis) &&
source.HasKey(keys::kContentSecurityPolicy)) {
std::string content_security_policy;
if (!source.GetString(keys::kContentSecurityPolicy,
&content_security_policy)) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
const char kBadCSPCharacters[] = {'\r', '\n', '\0'};
if (content_security_policy.find_first_of(kBadCSPCharacters, 0,
arraysize(kBadCSPCharacters)) !=
std::string::npos) {
*error = errors::kInvalidContentSecurityPolicy;
return false;
}
content_security_policy_ = content_security_policy;
}
if (source.HasKey(keys::kDevToolsPage)) {
std::string devtools_str;
if (!source.GetString(keys::kDevToolsPage, &devtools_str)) {
*error = errors::kInvalidDevToolsPage;
return false;
}
if (!HasApiPermission(Extension::kExperimentalPermission)) {
*error = errors::kDevToolsExperimental;
return false;
}
devtools_url_ = GetResourceURL(devtools_str);
}
if (source.HasKey(keys::kSidebar)) {
DictionaryValue* sidebar_value = NULL;
if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) {
*error = errors::kInvalidSidebar;
return false;
}
if (!HasApiPermission(Extension::kExperimentalPermission)) {
*error = errors::kSidebarExperimental;
return false;
}
sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error));
if (!sidebar_defaults_.get())
return false; // Failed to parse sidebar definition.
}
if (source.HasKey(keys::kTts)) {
DictionaryValue* tts_dict = NULL;
if (!source.GetDictionary(keys::kTts, &tts_dict)) {
*error = errors::kInvalidTts;
return false;
}
if (tts_dict->HasKey(keys::kTtsVoices)) {
ListValue* tts_voices = NULL;
if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) {
*error = errors::kInvalidTtsVoices;
return false;
}
for (size_t i = 0; i < tts_voices->GetSize(); i++) {
DictionaryValue* one_tts_voice = NULL;
if (!tts_voices->GetDictionary(i, &one_tts_voice)) {
*error = errors::kInvalidTtsVoices;
return false;
}
TtsVoice voice_data;
if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesVoiceName, &voice_data.voice_name)) {
*error = errors::kInvalidTtsVoicesVoiceName;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesLocale, &voice_data.locale) ||
!l10n_util::IsValidLocaleSyntax(voice_data.locale)) {
*error = errors::kInvalidTtsVoicesLocale;
return false;
}
}
if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) {
if (!one_tts_voice->GetString(
keys::kTtsVoicesGender, &voice_data.gender) ||
(voice_data.gender != keys::kTtsGenderMale &&
voice_data.gender != keys::kTtsGenderFemale)) {
*error = errors::kInvalidTtsVoicesGender;
return false;
}
}
tts_voices_.push_back(voice_data);
}
}
}
incognito_split_mode_ = is_app();
if (source.HasKey(keys::kIncognito)) {
std::string value;
if (!source.GetString(keys::kIncognito, &value)) {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
if (value == values::kIncognitoSpanning) {
incognito_split_mode_ = false;
} else if (value == values::kIncognitoSplit) {
incognito_split_mode_ = true;
} else {
*error = errors::kInvalidIncognitoBehavior;
return false;
}
}
if (HasMultipleUISurfaces()) {
*error = errors::kOneUISurfaceOnly;
return false;
}
InitEffectiveHostPermissions();
DCHECK(source.Equals(manifest_value_.get()));
return true;
}
| 170,409 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WallpaperManager::OnDefaultWallpaperDecoded(
const base::FilePath& path,
const wallpaper::WallpaperLayout layout,
std::unique_ptr<user_manager::UserImage>* result_out,
MovableOnDestroyCallbackHolder on_finish,
std::unique_ptr<user_manager::UserImage> user_image) {
if (user_image->image().isNull()) {
LOG(ERROR) << "Failed to decode default wallpaper. ";
return;
}
*result_out = std::move(user_image);
WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT,
base::Time::Now().LocalMidnight());
SetWallpaper((*result_out)->image(), info);
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void WallpaperManager::OnDefaultWallpaperDecoded(
const base::FilePath& path,
const wallpaper::WallpaperLayout layout,
bool update_wallpaper,
std::unique_ptr<user_manager::UserImage>* result_out,
MovableOnDestroyCallbackHolder on_finish,
std::unique_ptr<user_manager::UserImage> user_image) {
if (user_image->image().isNull()) {
LOG(ERROR) << "Failed to decode default wallpaper. ";
return;
}
*result_out = std::move(user_image);
if (update_wallpaper) {
WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT,
base::Time::Now().LocalMidnight());
SetWallpaper((*result_out)->image(), info);
}
}
| 171,967 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: T42_Open_Face( T42_Face face )
{
T42_LoaderRec loader;
T42_Parser parser;
T1_Font type1 = &face->type1;
FT_Memory memory = face->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t42_loader_init( &loader, face );
parser = &loader.parser;
if ( FT_ALLOC( face->ttf_data, 12 ) )
goto Exit;
error = t42_parser_init( parser,
face->root.stream,
memory,
if ( error )
goto Exit;
if ( type1->font_type != 42 )
{
FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n",
type1->font_type ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* now, propagate the charstrings and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( !loader.charstrings.init )
{
FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* as defined in the CharStrings array. */
/* The index is then stored in type1.encoding.char_index, and */
/* the name in type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t42_loader_done( &loader );
return error;
}
Commit Message:
CWE ID: | T42_Open_Face( T42_Face face )
{
T42_LoaderRec loader;
T42_Parser parser;
T1_Font type1 = &face->type1;
FT_Memory memory = face->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t42_loader_init( &loader, face );
parser = &loader.parser;
if ( FT_ALLOC( face->ttf_data, 12 ) )
goto Exit;
/* while parsing the font we always update `face->ttf_size' so that */
/* even in case of buggy data (which might lead to premature end of */
/* scanning without causing an error) the call to `FT_Open_Face' in */
/* `T42_Face_Init' passes the correct size */
face->ttf_size = 12;
error = t42_parser_init( parser,
face->root.stream,
memory,
if ( error )
goto Exit;
if ( type1->font_type != 42 )
{
FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n",
type1->font_type ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* now, propagate the charstrings and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( !loader.charstrings.init )
{
FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* as defined in the CharStrings array. */
/* The index is then stored in type1.encoding.char_index, and */
/* the name in type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t42_loader_done( &loader );
return error;
}
| 164,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 ui4_payload_type, ui4_payload_size;
UWORD32 u4_bits;
WORD32 i4_status = 0;
do
{
ui4_payload_type = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits)
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_type += 255;
}
ui4_payload_type += u4_bits;
ui4_payload_size = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits)
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_size += 255;
}
ui4_payload_size += u4_bits;
i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type,
ui4_payload_size, ps_dec);
if(i4_status == -1)
{
i4_status = 0;
break;
}
if(i4_status != OK)
return i4_status;
if(ih264d_check_byte_aligned(ps_bitstrm) == 0)
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(0 == u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
while(0 == ih264d_check_byte_aligned(ps_bitstrm))
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
}
}
}
while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst);
return (i4_status);
}
Commit Message: Decoder: Increased allocation and added checks in sei parsing.
This prevents heap overflow while parsing sei_message.
Bug: 63122634
Test: ran PoC on unpatched/patched
Change-Id: I61c1ff4ac053a060be8c24da4671db985cac628c
(cherry picked from commit f2b70d353768af8d4ead7f32497be05f197925ef)
CWE ID: CWE-200 | WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 ui4_payload_type, ui4_payload_size;
UWORD32 u4_bits;
WORD32 i4_status = 0;
do
{
ui4_payload_type = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_type += 255;
}
ui4_payload_type += u4_bits;
ui4_payload_size = 0;
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8);
ui4_payload_size += 255;
}
ui4_payload_size += u4_bits;
i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type,
ui4_payload_size, ps_dec);
if(i4_status == -1)
{
i4_status = 0;
break;
}
if(i4_status != OK)
return i4_status;
if(ih264d_check_byte_aligned(ps_bitstrm) == 0)
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(0 == u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
while(0 == ih264d_check_byte_aligned(ps_bitstrm)
&& !EXCEED_OFFSET(ps_bitstrm))
{
u4_bits = ih264d_get_bit_h264(ps_bitstrm);
if(u4_bits)
{
H264_DEC_DEBUG_PRINT("\nError in parsing SEI message");
}
}
}
}
while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst);
return (i4_status);
}
| 174,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PasswordInputType::EnableSecureTextInput() {
LocalFrame* frame = GetElement().GetDocument().GetFrame();
if (!frame)
return;
frame->Selection().SetUseSecureKeyboardEntryWhenActive(true);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void PasswordInputType::EnableSecureTextInput() {
| 171,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pvscsi_convert_sglist(PVSCSIRequest *r)
{
int chunk_size;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length) {
while (!sg.resid) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
assert(data_length > 0);
chunk_size = MIN((unsigned) data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
Commit Message:
CWE ID: CWE-399 | pvscsi_convert_sglist(PVSCSIRequest *r)
{
uint32_t chunk_size, elmcnt = 0;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length && elmcnt < PVSCSI_MAX_SG_ELEM) {
while (!sg.resid && elmcnt++ < PVSCSI_MAX_SG_ELEM) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
chunk_size = MIN(data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
| 164,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AccessibilityOrientation AXNodeObject::orientation() const {
const AtomicString& ariaOrientation =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation);
AccessibilityOrientation orientation = AccessibilityOrientationUndefined;
if (equalIgnoringCase(ariaOrientation, "horizontal"))
orientation = AccessibilityOrientationHorizontal;
else if (equalIgnoringCase(ariaOrientation, "vertical"))
orientation = AccessibilityOrientationVertical;
switch (roleValue()) {
case ComboBoxRole:
case ListBoxRole:
case MenuRole:
case ScrollBarRole:
case TreeRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationVertical;
return orientation;
case MenuBarRole:
case SliderRole:
case SplitterRole:
case TabListRole:
case ToolbarRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationHorizontal;
return orientation;
case RadioGroupRole:
case TreeGridRole:
case TableRole:
return orientation;
default:
return AXObject::orientation();
}
}
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 | AccessibilityOrientation AXNodeObject::orientation() const {
const AtomicString& ariaOrientation =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation);
AccessibilityOrientation orientation = AccessibilityOrientationUndefined;
if (equalIgnoringASCIICase(ariaOrientation, "horizontal"))
orientation = AccessibilityOrientationHorizontal;
else if (equalIgnoringASCIICase(ariaOrientation, "vertical"))
orientation = AccessibilityOrientationVertical;
switch (roleValue()) {
case ComboBoxRole:
case ListBoxRole:
case MenuRole:
case ScrollBarRole:
case TreeRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationVertical;
return orientation;
case MenuBarRole:
case SliderRole:
case SplitterRole:
case TabListRole:
case ToolbarRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationHorizontal;
return orientation;
case RadioGroupRole:
case TreeGridRole:
case TableRole:
return orientation;
default:
return AXObject::orientation();
}
}
| 171,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
Commit Message:
CWE ID: CWE-320 | static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx = NULL;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
if (BN_num_bits(dh->p) > OPENSSL_DH_MAX_MODULUS_BITS) {
DHerr(DH_F_GENERATE_KEY, DH_R_MODULUS_TOO_LARGE);
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
| 165,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
{
ASSERT(&blob->registry() == this);
ThreadableBlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
{
ASSERT(&blob->registry() == this);
BlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
}
| 170,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
InputMethodDescriptors* descriptions = new InputMethodDescriptors;
descriptions->push_back(InputMethodDescriptor(
"xkb:nl::nld", "Netherlands", "nl", "nl", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::nld", "Belgium", "be", "be", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fr::fra", "France", "fr", "fr", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::fra", "Belgium", "be", "be", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca::fra", "Canada", "ca", "ca", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de::ger", "Germany", "de", "de", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::ger", "Belgium", "be", "be", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch::ger", "Switzerland", "ch", "ch", "ger"));
descriptions->push_back(InputMethodDescriptor(
"mozc", "Mozc (US keyboard layout)", "us", "us", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-dv",
"Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja"));
descriptions->push_back(InputMethodDescriptor(
"xkb:jp::jpn", "Japan", "jp", "jp", "jpn"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru::rus", "Russia", "ru", "ru", "rus"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru:phonetic:rus",
"Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:tis820", "tis820 (m17n)", "us", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:quick", "quick (m17n)", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:telex", "telex (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:vni", "vni (m17n)", "us", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us::eng", "USA", "us", "us", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:intl:eng",
"USA - International (with dead keys)", "us(intl)", "us(intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)",
"us(altgr-intl)", "us(altgr-intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:dvorak:eng",
"USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:colemak:eng",
"USA - Colemak", "us(colemak)", "us(colemak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko"));
descriptions->push_back(InputMethodDescriptor(
"pinyin", "Pinyin", "us", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"pinyin-dv", "Pinyin (for US Dvorak keyboard)",
"us(dvorak)", "us(dvorak)", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar"));
descriptions->push_back(InputMethodDescriptor(
"m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:br::por", "Brazil", "br", "br", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg::bul", "Bulgaria", "bg", "bg", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic",
"bg(phonetic)", "bg(phonetic)", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:cz::cze", "Czechia", "cz", "cz", "cze"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ee::est", "Estonia", "ee", "ee", "est"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es::spa", "Spain", "es", "es", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L",
"es(cat)", "es(cat)", "cat"));
descriptions->push_back(InputMethodDescriptor(
"xkb:dk::dan", "Denmark", "dk", "dk", "dan"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gr::gre", "Greece", "gr", "gr", "gre"));
descriptions->push_back(InputMethodDescriptor(
"xkb:il::heb", "Israel", "il", "il", "heb"));
descriptions->push_back(InputMethodDescriptor(
"xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible",
"kr(kr104)", "kr(kr104)", "kor"));
descriptions->push_back(InputMethodDescriptor(
"xkb:latam::spa", "Latin American", "latam", "latam", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lt::lit", "Lithuania", "lt", "lt", "lit"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant",
"lv(apostrophe)", "lv(apostrophe)", "lav"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hr::scr", "Croatia", "hr", "hr", "scr"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys",
"gb(extd)", "gb(extd)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:dvorak:eng", "United Kingdom - Dvorak",
"gb(dvorak)", "gb(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fi::fin", "Finland", "fi", "fi", "fin"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hu::hun", "Hungary", "hu", "hu", "hun"));
descriptions->push_back(InputMethodDescriptor(
"xkb:it::ita", "Italy", "it", "it", "ita"));
descriptions->push_back(InputMethodDescriptor(
"xkb:no::nob", "Norway", "no", "no", "nob"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pl::pol", "Poland", "pl", "pl", "pol"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pt::por", "Portugal", "pt", "pt", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ro::rum", "Romania", "ro", "ro", "rum"));
descriptions->push_back(InputMethodDescriptor(
"xkb:se::swe", "Sweden", "se", "se", "swe"));
descriptions->push_back(InputMethodDescriptor(
"xkb:sk::slo", "Slovakia", "sk", "sk", "slo"));
descriptions->push_back(InputMethodDescriptor(
"xkb:si::slv", "Slovenia", "si", "si", "slv"));
descriptions->push_back(InputMethodDescriptor(
"xkb:rs::srp", "Serbia", "rs", "rs", "srp"));
descriptions->push_back(InputMethodDescriptor(
"xkb:tr::tur", "Turkey", "tr", "tr", "tur"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr"));
return descriptions;
}
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 | InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
input_method::InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
input_method::InputMethodDescriptors* descriptions =
new input_method::InputMethodDescriptors;
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:nl::nld", "Netherlands", "nl", "nl", "nld"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:be::nld", "Belgium", "be", "be", "nld"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:fr::fra", "France", "fr", "fr", "fra"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:be::fra", "Belgium", "be", "be", "fra"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ca::fra", "Canada", "ca", "ca", "fra"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:de::ger", "Germany", "de", "de", "ger"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:be::ger", "Belgium", "be", "be", "ger"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ch::ger", "Switzerland", "ch", "ch", "ger"));
descriptions->push_back(input_method::InputMethodDescriptor(
"mozc", "Mozc (US keyboard layout)", "us", "us", "ja"));
descriptions->push_back(input_method::InputMethodDescriptor(
"mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja"));
descriptions->push_back(input_method::InputMethodDescriptor(
"mozc-dv",
"Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:jp::jpn", "Japan", "jp", "jp", "jpn"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ru::rus", "Russia", "ru", "ru", "rus"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ru:phonetic:rus",
"Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:th:tis820", "tis820 (m17n)", "us", "us", "th"));
descriptions->push_back(input_method::InputMethodDescriptor(
"mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:zh:quick", "quick (m17n)", "us", "us", "zh"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:vi:telex", "telex (m17n)", "us", "us", "vi"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:vi:vni", "vni (m17n)", "us", "us", "vi"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:us::eng", "USA", "us", "us", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:us:intl:eng",
"USA - International (with dead keys)", "us(intl)", "us(intl)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)",
"us(altgr-intl)", "us(altgr-intl)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:us:dvorak:eng",
"USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:us:colemak:eng",
"USA - Colemak", "us(colemak)", "us(colemak)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko"));
descriptions->push_back(input_method::InputMethodDescriptor(
"pinyin", "Pinyin", "us", "us", "zh"));
descriptions->push_back(input_method::InputMethodDescriptor(
"pinyin-dv", "Pinyin (for US Dvorak keyboard)",
"us(dvorak)", "us(dvorak)", "zh"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi"));
descriptions->push_back(input_method::InputMethodDescriptor(
"m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:br::por", "Brazil", "br", "br", "por"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:bg::bul", "Bulgaria", "bg", "bg", "bul"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic",
"bg(phonetic)", "bg(phonetic)", "bul"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:cz::cze", "Czechia", "cz", "cz", "cze"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ee::est", "Estonia", "ee", "ee", "est"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:es::spa", "Spain", "es", "es", "spa"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L",
"es(cat)", "es(cat)", "cat"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:dk::dan", "Denmark", "dk", "dk", "dan"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:gr::gre", "Greece", "gr", "gr", "gre"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:il::heb", "Israel", "il", "il", "heb"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible",
"kr(kr104)", "kr(kr104)", "kor"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:latam::spa", "Latin American", "latam", "latam", "spa"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:lt::lit", "Lithuania", "lt", "lt", "lit"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant",
"lv(apostrophe)", "lv(apostrophe)", "lav"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:hr::scr", "Croatia", "hr", "hr", "scr"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys",
"gb(extd)", "gb(extd)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:gb:dvorak:eng", "United Kingdom - Dvorak",
"gb(dvorak)", "gb(dvorak)", "eng"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:fi::fin", "Finland", "fi", "fi", "fin"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:hu::hun", "Hungary", "hu", "hu", "hun"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:it::ita", "Italy", "it", "it", "ita"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:no::nob", "Norway", "no", "no", "nob"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:pl::pol", "Poland", "pl", "pl", "pol"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:pt::por", "Portugal", "pt", "pt", "por"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ro::rum", "Romania", "ro", "ro", "rum"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:se::swe", "Sweden", "se", "se", "swe"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:sk::slo", "Slovakia", "sk", "sk", "slo"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:si::slv", "Slovenia", "si", "si", "slv"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:rs::srp", "Serbia", "rs", "rs", "srp"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:tr::tur", "Turkey", "tr", "tr", "tur"));
descriptions->push_back(input_method::InputMethodDescriptor(
"xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr"));
return descriptions;
}
| 170,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: exit_ext2_xattr(void)
{
mb_cache_destroy(ext2_xattr_cache);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | exit_ext2_xattr(void)
void ext2_xattr_destroy_cache(struct mb2_cache *cache)
{
if (cache)
mb2_cache_destroy(cache);
}
| 169,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AcceleratedStaticBitmapImage::CopyToTexture(
gpu::gles2::GLES2Interface* dest_gl,
GLenum dest_target,
GLuint dest_texture_id,
bool unpack_premultiply_alpha,
bool unpack_flip_y,
const IntPoint& dest_point,
const IntRect& source_sub_rectangle) {
CheckThread();
if (!IsValid())
return false;
DCHECK(texture_holder_->IsCrossThread() ||
dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL());
EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST);
dest_gl->WaitSyncTokenCHROMIUM(
texture_holder_->GetSyncToken().GetConstData());
GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM(
texture_holder_->GetMailbox().name);
dest_gl->CopySubTextureCHROMIUM(
source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(),
dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(),
source_sub_rectangle.Width(), source_sub_rectangle.Height(),
unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE,
unpack_premultiply_alpha ? GL_FALSE : GL_TRUE);
dest_gl->DeleteTextures(1, &source_texture_id);
gpu::SyncToken sync_token;
dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData());
texture_holder_->UpdateSyncToken(sync_token);
return true;
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | bool AcceleratedStaticBitmapImage::CopyToTexture(
gpu::gles2::GLES2Interface* dest_gl,
GLenum dest_target,
GLuint dest_texture_id,
bool unpack_premultiply_alpha,
bool unpack_flip_y,
const IntPoint& dest_point,
const IntRect& source_sub_rectangle) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!IsValid())
return false;
DCHECK(texture_holder_->IsCrossThread() ||
dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL());
EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST);
dest_gl->WaitSyncTokenCHROMIUM(
texture_holder_->GetSyncToken().GetConstData());
GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM(
texture_holder_->GetMailbox().name);
dest_gl->CopySubTextureCHROMIUM(
source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(),
dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(),
source_sub_rectangle.Width(), source_sub_rectangle.Height(),
unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE,
unpack_premultiply_alpha ? GL_FALSE : GL_TRUE);
dest_gl->DeleteTextures(1, &source_texture_id);
gpu::SyncToken sync_token;
dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData());
texture_holder_->UpdateSyncToken(sync_token);
return true;
}
| 172,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: enum ImapAuthRes imap_auth_gss(struct ImapData *idata, const char *method)
{
gss_buffer_desc request_buf, send_token;
gss_buffer_t sec_token;
gss_name_t target_name;
gss_ctx_id_t context;
gss_OID mech_name;
char server_conf_flags;
gss_qop_t quality;
int cflags;
OM_uint32 maj_stat, min_stat;
char buf1[GSS_BUFSIZE], buf2[GSS_BUFSIZE];
unsigned long buf_size;
int rc;
if (!mutt_bit_isset(idata->capabilities, AGSSAPI))
return IMAP_AUTH_UNAVAIL;
if (mutt_account_getuser(&idata->conn->account) < 0)
return IMAP_AUTH_FAILURE;
/* get an IMAP service ticket for the server */
snprintf(buf1, sizeof(buf1), "imap@%s", idata->conn->account.host);
request_buf.value = buf1;
request_buf.length = strlen(buf1);
maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name, &target_name);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Couldn't get service name for [%s]\n", buf1);
return IMAP_AUTH_UNAVAIL;
}
else if (DebugLevel >= 2)
{
gss_display_name(&min_stat, target_name, &request_buf, &mech_name);
mutt_debug(2, "Using service name [%s]\n", (char *) request_buf.value);
gss_release_buffer(&min_stat, &request_buf);
}
/* Acquire initial credentials - without a TGT GSSAPI is UNAVAIL */
sec_token = GSS_C_NO_BUFFER;
context = GSS_C_NO_CONTEXT;
/* build token */
maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name,
GSS_C_NO_OID, GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
0, GSS_C_NO_CHANNEL_BINDINGS, sec_token, NULL,
&send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error acquiring credentials - no TGT?\n");
gss_release_name(&min_stat, &target_name);
return IMAP_AUTH_UNAVAIL;
}
/* now begin login */
mutt_message(_("Authenticating (GSSAPI)..."));
imap_cmd_start(idata, "AUTHENTICATE GSSAPI");
/* expect a null continuation response ("+") */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(2, "Invalid response from server: %s\n", buf1);
gss_release_name(&min_stat, &target_name);
goto bail;
}
/* now start the security context initialisation loop... */
mutt_debug(2, "Sending credentials\n");
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
while (maj_stat == GSS_S_CONTINUE_NEEDED)
{
/* Read server data */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#1 Error receiving server response.\n");
gss_release_name(&min_stat, &target_name);
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);
request_buf.value = buf2;
sec_token = &request_buf;
/* Write client data */
maj_stat = gss_init_sec_context(
&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name, GSS_C_NO_OID,
GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 0, GSS_C_NO_CHANNEL_BINDINGS,
sec_token, NULL, &send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error exchanging credentials\n");
gss_release_name(&min_stat, &target_name);
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
}
gss_release_name(&min_stat, &target_name);
/* get security flags and buffer size */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#2 Error receiving server response.\n");
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);
request_buf.value = buf2;
maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token, &cflags, &quality);
if (maj_stat != GSS_S_COMPLETE)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(2, "Couldn't unwrap security level data\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
mutt_debug(2, "Credential exchange complete\n");
/* first octet is security levels supported. We want NONE */
server_conf_flags = ((char *) send_token.value)[0];
if (!(((char *) send_token.value)[0] & GSS_AUTH_P_NONE))
{
mutt_debug(2, "Server requires integrity or privacy\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
/* we don't care about buffer size if we don't wrap content. But here it is */
((char *) send_token.value)[0] = '\0';
buf_size = ntohl(*((long *) send_token.value));
gss_release_buffer(&min_stat, &send_token);
mutt_debug(2, "Unwrapped security level flags: %c%c%c\n",
(server_conf_flags & GSS_AUTH_P_NONE) ? 'N' : '-',
(server_conf_flags & GSS_AUTH_P_INTEGRITY) ? 'I' : '-',
(server_conf_flags & GSS_AUTH_P_PRIVACY) ? 'P' : '-');
mutt_debug(2, "Maximum GSS token size is %ld\n", buf_size);
/* agree to terms (hack!) */
buf_size = htonl(buf_size); /* not relevant without integrity/privacy */
memcpy(buf1, &buf_size, 4);
buf1[0] = GSS_AUTH_P_NONE;
/* server decides if principal can log in as user */
strncpy(buf1 + 4, idata->conn->account.user, sizeof(buf1) - 4);
request_buf.value = buf1;
request_buf.length = 4 + strlen(idata->conn->account.user);
maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
&cflags, &send_token);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Error creating login request\n");
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
mutt_debug(2, "Requesting authorisation as %s\n", idata->conn->account.user);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
/* Joy of victory or agony of defeat? */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
mutt_debug(1, "Unexpected server continuation request.\n");
goto err_abort_cmd;
}
if (imap_code(idata->buf))
{
/* flush the security context */
mutt_debug(2, "Releasing GSS credentials\n");
maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
if (maj_stat != GSS_S_COMPLETE)
mutt_debug(1, "Error releasing credentials\n");
/* send_token may contain a notification to the server to flush
* credentials. RFC1731 doesn't specify what to do, and since this
* support is only for authentication, we'll assume the server knows
* enough to flush its own credentials */
gss_release_buffer(&min_stat, &send_token);
return IMAP_AUTH_SUCCESS;
}
else
goto bail;
err_abort_cmd:
mutt_socket_send(idata->conn, "*\r\n");
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
bail:
mutt_error(_("GSSAPI authentication failed."));
return IMAP_AUTH_FAILURE;
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119 | enum ImapAuthRes imap_auth_gss(struct ImapData *idata, const char *method)
{
gss_buffer_desc request_buf, send_token;
gss_buffer_t sec_token;
gss_name_t target_name;
gss_ctx_id_t context;
gss_OID mech_name;
char server_conf_flags;
gss_qop_t quality;
int cflags;
OM_uint32 maj_stat, min_stat;
char buf1[GSS_BUFSIZE], buf2[GSS_BUFSIZE];
unsigned long buf_size;
int rc;
if (!mutt_bit_isset(idata->capabilities, AGSSAPI))
return IMAP_AUTH_UNAVAIL;
if (mutt_account_getuser(&idata->conn->account) < 0)
return IMAP_AUTH_FAILURE;
/* get an IMAP service ticket for the server */
snprintf(buf1, sizeof(buf1), "imap@%s", idata->conn->account.host);
request_buf.value = buf1;
request_buf.length = strlen(buf1);
maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name, &target_name);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Couldn't get service name for [%s]\n", buf1);
return IMAP_AUTH_UNAVAIL;
}
else if (DebugLevel >= 2)
{
gss_display_name(&min_stat, target_name, &request_buf, &mech_name);
mutt_debug(2, "Using service name [%s]\n", (char *) request_buf.value);
gss_release_buffer(&min_stat, &request_buf);
}
/* Acquire initial credentials - without a TGT GSSAPI is UNAVAIL */
sec_token = GSS_C_NO_BUFFER;
context = GSS_C_NO_CONTEXT;
/* build token */
maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name,
GSS_C_NO_OID, GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
0, GSS_C_NO_CHANNEL_BINDINGS, sec_token, NULL,
&send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error acquiring credentials - no TGT?\n");
gss_release_name(&min_stat, &target_name);
return IMAP_AUTH_UNAVAIL;
}
/* now begin login */
mutt_message(_("Authenticating (GSSAPI)..."));
imap_cmd_start(idata, "AUTHENTICATE GSSAPI");
/* expect a null continuation response ("+") */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(2, "Invalid response from server: %s\n", buf1);
gss_release_name(&min_stat, &target_name);
goto bail;
}
/* now start the security context initialisation loop... */
mutt_debug(2, "Sending credentials\n");
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
while (maj_stat == GSS_S_CONTINUE_NEEDED)
{
/* Read server data */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#1 Error receiving server response.\n");
gss_release_name(&min_stat, &target_name);
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2, sizeof(buf2));
request_buf.value = buf2;
sec_token = &request_buf;
/* Write client data */
maj_stat = gss_init_sec_context(
&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name, GSS_C_NO_OID,
GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 0, GSS_C_NO_CHANNEL_BINDINGS,
sec_token, NULL, &send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error exchanging credentials\n");
gss_release_name(&min_stat, &target_name);
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
}
gss_release_name(&min_stat, &target_name);
/* get security flags and buffer size */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#2 Error receiving server response.\n");
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2, sizeof(buf2));
request_buf.value = buf2;
maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token, &cflags, &quality);
if (maj_stat != GSS_S_COMPLETE)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(2, "Couldn't unwrap security level data\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
mutt_debug(2, "Credential exchange complete\n");
/* first octet is security levels supported. We want NONE */
server_conf_flags = ((char *) send_token.value)[0];
if (!(((char *) send_token.value)[0] & GSS_AUTH_P_NONE))
{
mutt_debug(2, "Server requires integrity or privacy\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
/* we don't care about buffer size if we don't wrap content. But here it is */
((char *) send_token.value)[0] = '\0';
buf_size = ntohl(*((long *) send_token.value));
gss_release_buffer(&min_stat, &send_token);
mutt_debug(2, "Unwrapped security level flags: %c%c%c\n",
(server_conf_flags & GSS_AUTH_P_NONE) ? 'N' : '-',
(server_conf_flags & GSS_AUTH_P_INTEGRITY) ? 'I' : '-',
(server_conf_flags & GSS_AUTH_P_PRIVACY) ? 'P' : '-');
mutt_debug(2, "Maximum GSS token size is %ld\n", buf_size);
/* agree to terms (hack!) */
buf_size = htonl(buf_size); /* not relevant without integrity/privacy */
memcpy(buf1, &buf_size, 4);
buf1[0] = GSS_AUTH_P_NONE;
/* server decides if principal can log in as user */
strncpy(buf1 + 4, idata->conn->account.user, sizeof(buf1) - 4);
request_buf.value = buf1;
request_buf.length = 4 + strlen(idata->conn->account.user);
maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
&cflags, &send_token);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Error creating login request\n");
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
mutt_debug(2, "Requesting authorisation as %s\n", idata->conn->account.user);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
/* Joy of victory or agony of defeat? */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
mutt_debug(1, "Unexpected server continuation request.\n");
goto err_abort_cmd;
}
if (imap_code(idata->buf))
{
/* flush the security context */
mutt_debug(2, "Releasing GSS credentials\n");
maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
if (maj_stat != GSS_S_COMPLETE)
mutt_debug(1, "Error releasing credentials\n");
/* send_token may contain a notification to the server to flush
* credentials. RFC1731 doesn't specify what to do, and since this
* support is only for authentication, we'll assume the server knows
* enough to flush its own credentials */
gss_release_buffer(&min_stat, &send_token);
return IMAP_AUTH_SUCCESS;
}
else
goto bail;
err_abort_cmd:
mutt_socket_send(idata->conn, "*\r\n");
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
bail:
mutt_error(_("GSSAPI authentication failed."));
return IMAP_AUTH_FAILURE;
}
| 169,127 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: TileIndependenceTest()
: EncoderTest(GET_PARAM(0)),
md5_fw_order_(),
md5_inv_order_(),
n_tiles_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg;
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
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 | TileIndependenceTest()
: EncoderTest(GET_PARAM(0)),
md5_fw_order_(),
md5_inv_order_(),
n_tiles_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
| 174,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext2_xattr_cache_insert(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext2_xattr_cache, GFP_NOFS);
if (!ce)
return -ENOMEM;
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache (%d cache entries)",
atomic_read(&ext2_xattr_cache->c_entry_count));
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x] (%d cache entries)", (int)hash,
atomic_read(&ext2_xattr_cache->c_entry_count));
mb_cache_entry_release(ce);
}
return error;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_cache_insert(struct buffer_head *bh)
ext2_xattr_cache_insert(struct mb2_cache *cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(HDR(bh)->h_hash);
int error;
error = mb2_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr);
if (error) {
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache (%d cache entries)",
atomic_read(&ext2_xattr_cache->c_entry_count));
error = 0;
}
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
return error;
}
| 169,978 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight)
{
uch sig[8];
/* first do a quick check that the file really is a PNG image; could
* have used slightly more general png_sig_cmp() function instead */
fread(sig, 1, 8, infile);
if (png_sig_cmp(sig, 0, 8))
return 1; /* bad signature */
/* could pass pointers to user-defined error handlers instead of NULLs: */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 4; /* out of memory */
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters) */
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}
png_init_io(png_ptr, infile);
png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */
png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
/* alternatively, could make separate calls to png_get_image_width(),
* etc., but want bit_depth and color_type for later [don't care about
* compression_type and filter_type => NULLs] */
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
*pWidth = width;
*pHeight = height;
/* OK, that's all we need for now; return happy */
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight)
{
uch sig[8];
/* first do a quick check that the file really is a PNG image; could
* have used slightly more general png_sig_cmp() function instead */
fread(sig, 1, 8, infile);
if (png_sig_cmp(sig, 0, 8))
return 1; /* bad signature */
/* could pass pointers to user-defined error handlers instead of NULLs: */
png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), NULL, NULL,
NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 4; /* out of memory */
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters) */
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}
png_init_io(png_ptr, infile);
png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */
png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
/* alternatively, could make separate calls to png_get_image_width(),
* etc., but want bit_depth and color_type for later [don't care about
* compression_type and filter_type => NULLs] */
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
*pWidth = width;
*pHeight = height;
/* OK, that's all we need for now; return happy */
return 0;
}
| 173,567 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _TIFFmalloc(tmsize_t s)
{
return (malloc((size_t) s));
}
Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not
require malloc() to return NULL pointer if requested allocation
size is zero. Assure that _TIFFmalloc does.
CWE ID: CWE-369 | _TIFFmalloc(tmsize_t s)
{
if (s == 0)
return ((void *) NULL);
return (malloc((size_t) s));
}
| 169,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXTableCell::isColumnHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringCase(scope, "col") ||
equalIgnoringCase(scope, "colgroup");
}
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 | bool AXTableCell::isColumnHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringASCIICase(scope, "col") ||
equalIgnoringASCIICase(scope, "colgroup");
}
| 171,932 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size - 1) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
}
Commit Message: fix #6857
CWE ID: CWE-125 | static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
}
| 168,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName)
{
char nameBuf[512];
char absoluteFile[sizeof(nameBuf)];
const size_t kBufLen = sizeof(nameBuf) - 1;
const char* dataRoot;
char* cp;
/*
* Get the absolute path of the Jar or DEX file.
*/
absoluteFile[0] = '\0';
if (fileName[0] != '/') {
/*
* Generate the absolute path. This doesn't do everything it
* should, e.g. if filename is "./out/whatever" it doesn't crunch
* the leading "./" out, but it'll do.
*/
if (getcwd(absoluteFile, kBufLen) == NULL) {
ALOGE("Can't get CWD while opening jar file");
return NULL;
}
strncat(absoluteFile, "/", kBufLen);
}
strncat(absoluteFile, fileName, kBufLen);
/*
* Append the name of the Jar file entry, if any. This is not currently
* required, but will be if we start putting more than one DEX file
* in a Jar.
*/
if (subFileName != NULL) {
strncat(absoluteFile, "/", kBufLen);
strncat(absoluteFile, subFileName, kBufLen);
}
/* Turn the path into a flat filename by replacing
* any slashes after the first one with '@' characters.
*/
cp = absoluteFile + 1;
while (*cp != '\0') {
if (*cp == '/') {
*cp = '@';
}
cp++;
}
/* Build the name of the cache directory.
*/
dataRoot = getenv("ANDROID_DATA");
if (dataRoot == NULL)
dataRoot = "/data";
snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
/* Tack on the file name for the actual cache file path.
*/
strncat(nameBuf, absoluteFile, kBufLen);
ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf);
return strdup(nameBuf);
}
Commit Message: Fix potential buffer overrun.
BUG=27840771
Change-Id: I240f188b2e8f4b45d90138cfb3b14869cf506452
CWE ID: CWE-119 | char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName)
{
char nameBuf[512];
char absoluteFile[sizeof(nameBuf)];
const size_t kBufLen = sizeof(nameBuf) - 1;
const char* dataRoot;
char* cp;
/*
* Get the absolute path of the Jar or DEX file.
*/
absoluteFile[0] = '\0';
if (fileName[0] != '/') {
/*
* Generate the absolute path. This doesn't do everything it
* should, e.g. if filename is "./out/whatever" it doesn't crunch
* the leading "./" out, but it'll do.
*/
if (getcwd(absoluteFile, kBufLen) == NULL) {
ALOGE("Can't get CWD while opening jar file");
return NULL;
}
strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile));
}
strncat(absoluteFile, fileName, kBufLen - strlen(absoluteFile));
/*
* Append the name of the Jar file entry, if any. This is not currently
* required, but will be if we start putting more than one DEX file
* in a Jar.
*/
if (subFileName != NULL) {
strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile));
strncat(absoluteFile, subFileName, kBufLen - strlen(absoluteFile));
}
/* Turn the path into a flat filename by replacing
* any slashes after the first one with '@' characters.
*/
cp = absoluteFile + 1;
while (*cp != '\0') {
if (*cp == '/') {
*cp = '@';
}
cp++;
}
/* Build the name of the cache directory.
*/
dataRoot = getenv("ANDROID_DATA");
if (dataRoot == NULL)
dataRoot = "/data";
snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
/* Tack on the file name for the actual cache file path.
*/
strncat(nameBuf, absoluteFile, kBufLen - strlen(nameBuf));
ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf);
return strdup(nameBuf);
}
| 173,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615
CWE ID: CWE-119 | static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
rows;
rows=MagickMax(GetImageListLength(images),
(size_t) GetMagickResourceLimit(ThreadResource));
pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) rows; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
| 169,595 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RTCPeerConnectionHandlerChromium::setLocalDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
{
if (!m_webHandler)
return;
m_webHandler->setLocalDescription(request, sessionDescription);
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void RTCPeerConnectionHandlerChromium::setLocalDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
| 170,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = poll(pfds, 1, 50);
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void *btif_hh_poll_event_thread(void *arg)
{
btif_hh_device_t *p_dev = arg;
APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
struct pollfd pfds[1];
int ret;
pfds[0].fd = p_dev->fd;
pfds[0].events = POLLIN;
uhid_set_non_blocking(p_dev->fd);
while(p_dev->hh_keep_polling){
ret = TEMP_FAILURE_RETRY(poll(pfds, 1, 50));
if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
break;
}
if (pfds[0].revents & POLLIN) {
APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
ret = uhid_event(p_dev);
if (ret){
break;
}
}
}
p_dev->hh_poll_thread_id = -1;
return 0;
}
| 173,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)
if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {
sym = j;
break;
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) {
int indidx = bin->sects[i].reserved1 + j;
if (indidx < 0 || indidx >= bin->nindirectsyms) {
break;
}
if (idx == bin->indirectsyms[indidx]) {
sym = j;
break;
}
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
| 169,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Block::IsKey() const
{
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 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 | bool Block::IsKey() const
void Block::SetKey(bool bKey) {
if (bKey)
m_flags |= static_cast<unsigned char>(1 << 7);
else
m_flags &= 0x7F;
}
| 174,392 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.