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 void tv_details_row_activated(
GtkTreeView *tree_view,
GtkTreePath *tree_path_UNUSED,
GtkTreeViewColumn *column,
gpointer user_data)
{
gchar *item_name;
struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name);
if (!item || !(item->flags & CD_FLAG_TXT))
goto ret;
if (!strchr(item->content, '\n')) /* one line? */
goto ret; /* yes */
gint exitcode;
gchar *arg[3];
arg[0] = (char *) "xdg-open";
arg[1] = concat_path_file(g_dump_dir_name, item_name);
arg[2] = NULL;
const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
NULL, NULL, NULL, NULL, &exitcode, NULL);
if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS)
{
GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"),
GTK_WINDOW(g_wnd_assistant),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL);
GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);
GtkWidget *textview = gtk_text_view_new();
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK);
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0);
gtk_widget_set_size_request(scrolled, 640, 480);
gtk_widget_show(scrolled);
#if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8))
/* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */
/* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview);
#else
/* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */
gtk_container_add(GTK_CONTAINER(scrolled), textview);
#endif
gtk_widget_show(textview);
load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK)
save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name);
gtk_widget_destroy(textview);
gtk_widget_destroy(scrolled);
gtk_widget_destroy(dialog);
}
free(arg[1]);
ret:
g_free(item_name);
}
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 tv_details_row_activated(
GtkTreeView *tree_view,
GtkTreePath *tree_path_UNUSED,
GtkTreeViewColumn *column,
gpointer user_data)
{
gchar *item_name;
struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name);
if (!item || !(item->flags & CD_FLAG_TXT))
goto ret;
if (!strchr(item->content, '\n')) /* one line? */
goto ret; /* yes */
gint exitcode;
gchar *arg[3];
arg[0] = (char *) "xdg-open";
arg[1] = concat_path_file(g_dump_dir_name, item_name);
arg[2] = NULL;
const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
NULL, NULL, NULL, NULL, &exitcode, NULL);
if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS)
{
GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"),
GTK_WINDOW(g_wnd_assistant),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL);
GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);
GtkWidget *textview = gtk_text_view_new();
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK);
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0);
gtk_widget_set_size_request(scrolled, 640, 480);
gtk_widget_show(scrolled);
#if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8))
/* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */
/* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview);
#else
/* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */
gtk_container_add(GTK_CONTAINER(scrolled), textview);
#endif
gtk_widget_show(textview);
load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK)
{
save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name);
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
}
gtk_widget_destroy(textview);
gtk_widget_destroy(scrolled);
gtk_widget_destroy(dialog);
}
free(arg[1]);
ret:
g_free(item_name);
}
| 166,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 HTMLFormControlElement::updateVisibleValidationMessage() {
Page* page = document().page();
if (!page)
return;
String message;
if (layoutObject() && willValidate())
message = validationMessage().stripWhiteSpace();
m_hasValidationMessage = true;
ValidationMessageClient* client = &page->validationMessageClient();
TextDirection messageDir = LTR;
TextDirection subMessageDir = LTR;
String subMessage = validationSubMessage().stripWhiteSpace();
if (message.isEmpty())
client->hideValidationMessage(*this);
else
findCustomValidationMessageTextDirection(message, messageDir, subMessage,
subMessageDir);
client->showValidationMessage(*this, message, messageDir, subMessage,
subMessageDir);
}
Commit Message: Form validation: Do not show validation bubble if the page is invisible.
BUG=673163
Review-Url: https://codereview.chromium.org/2572813003
Cr-Commit-Position: refs/heads/master@{#438476}
CWE ID: CWE-1021 | void HTMLFormControlElement::updateVisibleValidationMessage() {
Page* page = document().page();
if (!page || !page->isPageVisible())
return;
String message;
if (layoutObject() && willValidate())
message = validationMessage().stripWhiteSpace();
m_hasValidationMessage = true;
ValidationMessageClient* client = &page->validationMessageClient();
TextDirection messageDir = LTR;
TextDirection subMessageDir = LTR;
String subMessage = validationSubMessage().stripWhiteSpace();
if (message.isEmpty())
client->hideValidationMessage(*this);
else
findCustomValidationMessageTextDirection(message, messageDir, subMessage,
subMessageDir);
client->showValidationMessage(*this, message, messageDir, subMessage,
subMessageDir);
}
| 172,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t punch_start, punch_stop;
handle_t *handle;
unsigned int credits;
loff_t new_size, ioffset;
int ret;
/*
* We need to test this early because xfstests assumes that a
* collapse range of (0, 1) will return EOPNOTSUPP if the file
* system does not support collapse range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Collapse range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
trace_ext4_collapse_range(inode, offset, len);
punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Need to round down offset to be aligned with page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
return ret;
/* Take mutex lock */
mutex_lock(&inode->i_mutex);
/*
* There is no need to overlap collapse range with EOF, in which case
* it is effectively a truncate operation
*/
if (offset + len >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
truncate_pagecache(inode, ioffset);
/* Wait for existing dio to complete */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_dio;
}
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, punch_start,
EXT_MAX_BLOCKS - punch_start);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ext4_discard_preallocations(inode);
ret = ext4_ext_shift_extents(inode, handle, punch_stop,
punch_stop - punch_start, SHIFT_LEFT);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
new_size = i_size_read(inode) - len;
i_size_write(inode, new_size);
EXT4_I(inode)->i_disksize = new_size;
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
out_stop:
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
ext4_lblk_t punch_start, punch_stop;
handle_t *handle;
unsigned int credits;
loff_t new_size, ioffset;
int ret;
/*
* We need to test this early because xfstests assumes that a
* collapse range of (0, 1) will return EOPNOTSUPP if the file
* system does not support collapse range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Collapse range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
trace_ext4_collapse_range(inode, offset, len);
punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Need to round down offset to be aligned with page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
return ret;
/* Take mutex lock */
mutex_lock(&inode->i_mutex);
/*
* There is no need to overlap collapse range with EOF, in which case
* it is effectively a truncate operation
*/
if (offset + len >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Wait for existing dio to complete */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
ret = ext4_es_remove_extent(inode, punch_start,
EXT_MAX_BLOCKS - punch_start);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
ext4_discard_preallocations(inode);
ret = ext4_ext_shift_extents(inode, handle, punch_stop,
punch_stop - punch_start, SHIFT_LEFT);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
new_size = i_size_read(inode) - len;
i_size_write(inode, new_size);
EXT4_I(inode)->i_disksize = new_size;
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
| 167,483 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BindSkiaToInProcessGL() {
static bool host_StubGL_installed = false;
if (!host_StubGL_installed) {
GrGLBinding binding;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationNone:
NOTREACHED();
return;
case gfx::kGLImplementationDesktopGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationOSMesaGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationEGLGLES2:
binding = kES2_GrGLBinding;
break;
case gfx::kGLImplementationMockGL:
NOTREACHED();
return;
}
static GrGLInterface host_gl_interface = {
binding,
kProbe_GrGLCapability, // NPOTRenderTargetSupport
kProbe_GrGLCapability, // MinRenderTargetHeight
kProbe_GrGLCapability, // MinRenderTargetWidth
StubGLActiveTexture,
StubGLAttachShader,
StubGLBindAttribLocation,
StubGLBindBuffer,
StubGLBindTexture,
StubGLBlendColor,
StubGLBlendFunc,
StubGLBufferData,
StubGLBufferSubData,
StubGLClear,
StubGLClearColor,
StubGLClearStencil,
NULL, // glClientActiveTexture
NULL, // glColor4ub
StubGLColorMask,
NULL, // glColorPointer
StubGLCompileShader,
StubGLCompressedTexImage2D,
StubGLCreateProgram,
StubGLCreateShader,
StubGLCullFace,
StubGLDeleteBuffers,
StubGLDeleteProgram,
StubGLDeleteShader,
StubGLDeleteTextures,
StubGLDepthMask,
StubGLDisable,
NULL, // glDisableClientState
StubGLDisableVertexAttribArray,
StubGLDrawArrays,
StubGLDrawElements,
StubGLEnable,
NULL, // glEnableClientState
StubGLEnableVertexAttribArray,
StubGLFrontFace,
StubGLGenBuffers,
StubGLGenTextures,
StubGLGetBufferParameteriv,
StubGLGetError,
StubGLGetIntegerv,
StubGLGetProgramInfoLog,
StubGLGetProgramiv,
StubGLGetShaderInfoLog,
StubGLGetShaderiv,
StubGLGetString,
StubGLGetUniformLocation,
StubGLLineWidth,
StubGLLinkProgram,
NULL, // glLoadMatrixf
NULL, // glMatrixMode
StubGLPixelStorei,
NULL, // glPointSize
StubGLReadPixels,
StubGLScissor,
NULL, // glShadeModel
StubGLShaderSource,
StubGLStencilFunc,
StubGLStencilFuncSeparate,
StubGLStencilMask,
StubGLStencilMaskSeparate,
StubGLStencilOp,
StubGLStencilOpSeparate,
NULL, // glTexCoordPointer
NULL, // glTexEnvi
StubGLTexImage2D,
StubGLTexParameteri,
StubGLTexSubImage2D,
StubGLUniform1f,
StubGLUniform1i,
StubGLUniform1fv,
StubGLUniform1iv,
StubGLUniform2f,
StubGLUniform2i,
StubGLUniform2fv,
StubGLUniform2iv,
StubGLUniform3f,
StubGLUniform3i,
StubGLUniform3fv,
StubGLUniform3iv,
StubGLUniform4f,
StubGLUniform4i,
StubGLUniform4fv,
StubGLUniform4iv,
StubGLUniformMatrix2fv,
StubGLUniformMatrix3fv,
StubGLUniformMatrix4fv,
StubGLUseProgram,
StubGLVertexAttrib4fv,
StubGLVertexAttribPointer,
NULL, // glVertexPointer
StubGLViewport,
StubGLBindFramebuffer,
StubGLBindRenderbuffer,
StubGLCheckFramebufferStatus,
StubGLDeleteFramebuffers,
StubGLDeleteRenderbuffers,
StubGLFramebufferRenderbuffer,
StubGLFramebufferTexture2D,
StubGLGenFramebuffers,
StubGLGenRenderbuffers,
StubGLRenderBufferStorage,
StubGLRenderbufferStorageMultisample,
StubGLBlitFramebuffer,
NULL, // glResolveMultisampleFramebuffer
StubGLMapBuffer,
StubGLUnmapBuffer,
NULL, // glBindFragDataLocationIndexed
GrGLInterface::kStaticInitEndGuard,
};
GrGLSetGLInterface(&host_gl_interface);
host_StubGL_installed = true;
}
}
Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror.
It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp)
Remove now-redudant code that's implied by chromium_code: 1.
Fix the warnings that have crept in since chromium_code: 1 was removed.
BUG=none
TEST=none
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598
Review URL: http://codereview.chromium.org/7227009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void BindSkiaToInProcessGL() {
static bool host_StubGL_installed = false;
if (!host_StubGL_installed) {
GrGLBinding binding;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationNone:
NOTREACHED();
return;
case gfx::kGLImplementationDesktopGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationOSMesaGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationEGLGLES2:
binding = kES2_GrGLBinding;
break;
case gfx::kGLImplementationMockGL:
NOTREACHED();
return;
default:
NOTREACHED();
return;
}
static GrGLInterface host_gl_interface = {
binding,
kProbe_GrGLCapability, // NPOTRenderTargetSupport
kProbe_GrGLCapability, // MinRenderTargetHeight
kProbe_GrGLCapability, // MinRenderTargetWidth
StubGLActiveTexture,
StubGLAttachShader,
StubGLBindAttribLocation,
StubGLBindBuffer,
StubGLBindTexture,
StubGLBlendColor,
StubGLBlendFunc,
StubGLBufferData,
StubGLBufferSubData,
StubGLClear,
StubGLClearColor,
StubGLClearStencil,
NULL, // glClientActiveTexture
NULL, // glColor4ub
StubGLColorMask,
NULL, // glColorPointer
StubGLCompileShader,
StubGLCompressedTexImage2D,
StubGLCreateProgram,
StubGLCreateShader,
StubGLCullFace,
StubGLDeleteBuffers,
StubGLDeleteProgram,
StubGLDeleteShader,
StubGLDeleteTextures,
StubGLDepthMask,
StubGLDisable,
NULL, // glDisableClientState
StubGLDisableVertexAttribArray,
StubGLDrawArrays,
StubGLDrawElements,
StubGLEnable,
NULL, // glEnableClientState
StubGLEnableVertexAttribArray,
StubGLFrontFace,
StubGLGenBuffers,
StubGLGenTextures,
StubGLGetBufferParameteriv,
StubGLGetError,
StubGLGetIntegerv,
StubGLGetProgramInfoLog,
StubGLGetProgramiv,
StubGLGetShaderInfoLog,
StubGLGetShaderiv,
StubGLGetString,
StubGLGetUniformLocation,
StubGLLineWidth,
StubGLLinkProgram,
NULL, // glLoadMatrixf
NULL, // glMatrixMode
StubGLPixelStorei,
NULL, // glPointSize
StubGLReadPixels,
StubGLScissor,
NULL, // glShadeModel
StubGLShaderSource,
StubGLStencilFunc,
StubGLStencilFuncSeparate,
StubGLStencilMask,
StubGLStencilMaskSeparate,
StubGLStencilOp,
StubGLStencilOpSeparate,
NULL, // glTexCoordPointer
NULL, // glTexEnvi
StubGLTexImage2D,
StubGLTexParameteri,
StubGLTexSubImage2D,
StubGLUniform1f,
StubGLUniform1i,
StubGLUniform1fv,
StubGLUniform1iv,
StubGLUniform2f,
StubGLUniform2i,
StubGLUniform2fv,
StubGLUniform2iv,
StubGLUniform3f,
StubGLUniform3i,
StubGLUniform3fv,
StubGLUniform3iv,
StubGLUniform4f,
StubGLUniform4i,
StubGLUniform4fv,
StubGLUniform4iv,
StubGLUniformMatrix2fv,
StubGLUniformMatrix3fv,
StubGLUniformMatrix4fv,
StubGLUseProgram,
StubGLVertexAttrib4fv,
StubGLVertexAttribPointer,
NULL, // glVertexPointer
StubGLViewport,
StubGLBindFramebuffer,
StubGLBindRenderbuffer,
StubGLCheckFramebufferStatus,
StubGLDeleteFramebuffers,
StubGLDeleteRenderbuffers,
StubGLFramebufferRenderbuffer,
StubGLFramebufferTexture2D,
StubGLGenFramebuffers,
StubGLGenRenderbuffers,
StubGLRenderBufferStorage,
StubGLRenderbufferStorageMultisample,
StubGLBlitFramebuffer,
NULL, // glResolveMultisampleFramebuffer
StubGLMapBuffer,
StubGLUnmapBuffer,
NULL, // glBindFragDataLocationIndexed
GrGLInterface::kStaticInitEndGuard,
};
GrGLSetGLInterface(&host_gl_interface);
host_StubGL_installed = true;
}
}
| 170,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (key->state == KEY_IS_UNINSTANTIATED) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
mark_key_instantiated(key, 0);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret;
}
| 167,696 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() {
Profile* profile =
Profile::FromBrowserContext(GetWebContents()->GetBrowserContext());
Profile* original_profile = profile->GetOriginalProfile();
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(original_profile->GetPrefs()));
TranslateAcceptLanguages* accept_languages =
TranslateTabHelper::GetTranslateAcceptLanguages(original_profile);
return translate_prefs->CanTranslateLanguage(accept_languages,
original_language_code());
}
Commit Message: Remove dependency of TranslateInfobarDelegate on profile
This CL uses TranslateTabHelper instead of Profile and also cleans up
some unused code and irrelevant dependencies.
BUG=371845
Review URL: https://codereview.chromium.org/286973003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | bool TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() {
TranslateTabHelper* translate_tab_helper =
TranslateTabHelper::FromWebContents(GetWebContents());
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(
translate_tab_helper->GetPrefs()));
TranslateAcceptLanguages* accept_languages =
translate_tab_helper->GetTranslateAcceptLanguages();
return translate_prefs->CanTranslateLanguage(accept_languages,
original_language_code());
}
| 171,174 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCacheUpdateJob::OnResponseInfoLoaded(
AppCacheResponseInfo* response_info,
int64_t response_id) {
const net::HttpResponseInfo* http_info =
response_info ? &response_info->http_response_info() : nullptr;
if (internal_state_ == FETCH_MANIFEST) {
if (http_info)
manifest_fetcher_->set_existing_response_headers(
http_info->headers.get());
manifest_fetcher_->Start();
return;
}
auto found = loading_responses_.find(response_id);
DCHECK(found != loading_responses_.end());
const GURL& url = found->second;
if (!http_info) {
LoadFromNewestCacheFailed(url, nullptr); // no response found
} else if (!CanUseExistingResource(http_info)) {
LoadFromNewestCacheFailed(url, response_info);
} else {
DCHECK(group_->newest_complete_cache());
AppCacheEntry* copy_me = group_->newest_complete_cache()->GetEntry(url);
DCHECK(copy_me);
DCHECK_EQ(copy_me->response_id(), response_id);
auto it = url_file_list_.find(url);
DCHECK(it != url_file_list_.end());
AppCacheEntry& entry = it->second;
entry.set_response_id(response_id);
entry.set_response_size(copy_me->response_size());
inprogress_cache_->AddOrModifyEntry(url, entry);
NotifyAllProgress(url);
++url_fetches_completed_;
}
loading_responses_.erase(found);
MaybeCompleteUpdate();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCacheUpdateJob::OnResponseInfoLoaded(
AppCacheResponseInfo* response_info,
int64_t response_id) {
const net::HttpResponseInfo* http_info =
response_info ? &response_info->http_response_info() : nullptr;
if (internal_state_ == FETCH_MANIFEST) {
if (http_info)
manifest_fetcher_->set_existing_response_headers(
http_info->headers.get());
manifest_fetcher_->Start();
return;
}
auto found = loading_responses_.find(response_id);
DCHECK(found != loading_responses_.end());
const GURL& url = found->second;
if (!http_info) {
LoadFromNewestCacheFailed(url, nullptr); // no response found
} else if (!CanUseExistingResource(http_info)) {
LoadFromNewestCacheFailed(url, response_info);
} else {
DCHECK(group_->newest_complete_cache());
AppCacheEntry* copy_me = group_->newest_complete_cache()->GetEntry(url);
DCHECK(copy_me);
DCHECK_EQ(copy_me->response_id(), response_id);
auto it = url_file_list_.find(url);
DCHECK(it != url_file_list_.end());
AppCacheEntry& entry = it->second;
entry.set_response_id(response_id);
entry.SetResponseAndPaddingSizes(copy_me->response_size(),
copy_me->padding_size());
inprogress_cache_->AddOrModifyEntry(url, entry);
NotifyAllProgress(url);
++url_fetches_completed_;
}
loading_responses_.erase(found);
MaybeCompleteUpdate();
}
| 172,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
uint32_t key, insamples;
uint32_t repeat, outsamples;
GPMF_stream find_stream;
if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;
key = GPMF_Key(gs);
repeat = GPMF_Repeat(gs);
if (rate == 0.0)
rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);
if (rate == 0.0)
{
*in = *out = 0.0;
return 0.0;
}
GPMF_CopyState(gs, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
insamples = outsamples - repeat;
*in = ((double)insamples / (double)rate);
*out = ((double)outsamples / (double)rate);
}
else
{
*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
}
return rate;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL))
GPMF_FormattedData(&find_stream, &timo, 4, 0, 1);
double first, last;
first = -intercept / rate - timo;
last = first + (double)totalsamples / rate;
//printf("%c%c%c%c first sample at time %.3fms, last at %.3fms\n", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last);
if (firstsampletime) *firstsampletime = first;
if (lastsampletime) *lastsampletime = last;
}
}
}
}
cleanup:
if (payload)
FreePayload(payload);
payload = NULL;
return rate;
}
| 169,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(FilesystemIterator, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
} else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC);
} else {
RETURN_ZVAL(getThis(), 1, 0);
/*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(FilesystemIterator, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
} else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC);
} else {
RETURN_ZVAL(getThis(), 1, 0);
/*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/
}
}
| 167,036 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SupervisedUserService::InitSync(const std::string& refresh_token) {
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
token_service->UpdateCredentials(supervised_users::kSupervisedUserPseudoEmail,
refresh_token);
}
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 SupervisedUserService::InitSync(const std::string& refresh_token) {
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
token_service->UpdateCredentials(
supervised_users::kSupervisedUserPseudoEmail, refresh_token,
signin_metrics::SourceForRefreshTokenOperation::kSupervisedUser_InitSync);
}
| 172,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
bool source_is_modifiable) {
DCHECK(print_preview_rfh_);
if (rfh != print_preview_rfh_)
return;
PrintPreviewDialogController* dialog_controller =
PrintPreviewDialogController::GetInstance();
if (!dialog_controller) {
PrintPreviewDone();
return;
}
dialog_controller->PrintPreview(web_contents());
PrintHostMsg_RequestPrintPreview_Params params;
params.is_modifiable = source_is_modifiable;
PrintPreviewUI::SetInitialParams(
dialog_controller->GetPrintPreviewForContents(web_contents()), params);
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh,
bool source_is_modifiable) {
DCHECK(print_preview_rfh_);
if (rfh != print_preview_rfh_)
return;
PrintPreviewDialogController* dialog_controller =
PrintPreviewDialogController::GetInstance();
if (!dialog_controller) {
PrintPreviewDone();
return;
}
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (web_contents()->IsFullscreenForCurrentTab())
web_contents()->ExitFullscreen(true);
dialog_controller->PrintPreview(web_contents());
PrintHostMsg_RequestPrintPreview_Params params;
params.is_modifiable = source_is_modifiable;
PrintPreviewUI::SetInitialParams(
dialog_controller->GetPrintPreviewForContents(web_contents()), params);
}
| 172,314 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
return -ENODEV;
ops = kvm_device_ops_table[cd->type];
if (ops == NULL)
return -ENODEV;
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
mutex_lock(&kvm->lock);
ret = ops->create(dev, cd->type);
if (ret < 0) {
mutex_unlock(&kvm->lock);
kfree(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
mutex_unlock(&kvm->lock);
if (ops->init)
ops->init(dev);
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
ops->destroy(dev);
mutex_lock(&kvm->lock);
list_del(&dev->vm_node);
mutex_unlock(&kvm->lock);
return ret;
}
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
}
Commit Message: KVM: use after free in kvm_ioctl_create_device()
We should move the ops->destroy(dev) after the list_del(&dev->vm_node)
so that we don't use "dev" after freeing it.
Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock")
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-416 | static int kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
return -ENODEV;
ops = kvm_device_ops_table[cd->type];
if (ops == NULL)
return -ENODEV;
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
mutex_lock(&kvm->lock);
ret = ops->create(dev, cd->type);
if (ret < 0) {
mutex_unlock(&kvm->lock);
kfree(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
mutex_unlock(&kvm->lock);
if (ops->init)
ops->init(dev);
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
mutex_lock(&kvm->lock);
list_del(&dev->vm_node);
mutex_unlock(&kvm->lock);
ops->destroy(dev);
return ret;
}
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
}
| 168,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 char* Chapters::Display::GetCountry() const
{
return m_country;
}
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 char* Chapters::Display::GetCountry() const
| 174,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119 | void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
| 169,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
{
if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject"))
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"invalid incoming object");
return FALSE;
}
*outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2";
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
| 165,114 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SendTabToSelfInfoBarDelegate::SendTabToSelfInfoBarDelegate(
const SendTabToSelfEntry* entry) {
entry_ = entry;
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190 | SendTabToSelfInfoBarDelegate::SendTabToSelfInfoBarDelegate(
content::WebContents* web_contents,
const SendTabToSelfEntry* entry) {
web_contents_ = web_contents;
entry_ = entry;
}
| 172,542 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXIBarrierReleasePointer(ClientPtr client)
{
xXIBarrierReleasePointerInfo *info;
REQUEST(xXIBarrierReleasePointerReq);
int i;
swaps(&stuff->length);
REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq);
swapl(&stuff->num_barriers);
REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo));
info = (xXIBarrierReleasePointerInfo*) &stuff[1];
swapl(&info->barrier);
swapl(&info->eventid);
}
Commit Message:
CWE ID: CWE-190 | SProcXIBarrierReleasePointer(ClientPtr client)
{
xXIBarrierReleasePointerInfo *info;
REQUEST(xXIBarrierReleasePointerReq);
int i;
swaps(&stuff->length);
REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq);
swapl(&stuff->num_barriers);
if (stuff->num_barriers > UINT32_MAX / sizeof(xXIBarrierReleasePointerInfo))
return BadLength;
REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo));
info = (xXIBarrierReleasePointerInfo*) &stuff[1];
swapl(&info->barrier);
swapl(&info->eventid);
}
| 165,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XGetDeviceControl(
register Display *dpy,
XDevice *dev,
int control)
{
XDeviceControl *Device = NULL;
XDeviceControl *Sav = NULL;
xDeviceState *d = NULL;
xDeviceState *sav = NULL;
xGetDeviceControlReq *req;
xGetDeviceControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
return NULL;
GetReq(GetDeviceControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceControl;
req->deviceid = dev->device_id;
req->control = control;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
if (rep.length < (INT_MAX >> 2)) {
nbytes = (unsigned long) rep.length << 2;
d = Xmalloc(nbytes);
}
_XEatDataWords(dpy, rep.length);
goto out;
}
sav = d;
_XRead(dpy, (char *)d, nbytes);
/* In theory, we should just be able to use d->length to get the size.
* Turns out that a number of X servers (up to and including server
* 1.4) sent the wrong length value down the wire. So to not break
* apps that run against older servers, we have to calculate the size
* manually.
*/
switch (d->control) {
case DEVICE_RESOLUTION:
{
xDeviceResolutionState *r;
size_t val_size;
size_t val_size;
r = (xDeviceResolutionState *) d;
if (r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
goto out;
val_size = 3 * sizeof(int) * r->num_valuators;
if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
break;
}
case DEVICE_ABS_CALIB:
{
if (sizeof(xDeviceAbsCalibState) > nbytes)
goto out;
size = sizeof(XDeviceAbsCalibState);
break;
}
case DEVICE_ABS_AREA:
{
if (sizeof(xDeviceAbsAreaState) > nbytes)
goto out;
size = sizeof(XDeviceAbsAreaState);
break;
}
case DEVICE_CORE:
{
if (sizeof(xDeviceCoreState) > nbytes)
goto out;
size = sizeof(XDeviceCoreState);
break;
}
default:
if (d->length > nbytes)
goto out;
size = d->length;
break;
}
Device = Xmalloc(size);
if (!Device)
goto out;
Sav = Device;
d = sav;
switch (control) {
case DEVICE_RESOLUTION:
{
int *iptr, *iptr2;
xDeviceResolutionState *r;
XDeviceResolutionState *R;
unsigned int i;
r = (xDeviceResolutionState *) d;
R = (XDeviceResolutionState *) Device;
R->control = DEVICE_RESOLUTION;
R->length = sizeof(XDeviceResolutionState);
R->num_valuators = r->num_valuators;
iptr = (int *)(R + 1);
iptr2 = (int *)(r + 1);
R->resolutions = iptr;
R->min_resolutions = iptr + R->num_valuators;
R->max_resolutions = iptr + (2 * R->num_valuators);
for (i = 0; i < (3 * R->num_valuators); i++)
*iptr++ = *iptr2++;
break;
}
case DEVICE_ABS_CALIB:
{
xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;
C->control = DEVICE_ABS_CALIB;
C->length = sizeof(XDeviceAbsCalibState);
C->min_x = c->min_x;
C->max_x = c->max_x;
C->min_y = c->min_y;
C->max_y = c->max_y;
C->flip_x = c->flip_x;
C->flip_y = c->flip_y;
C->rotation = c->rotation;
C->button_threshold = c->button_threshold;
break;
}
case DEVICE_ABS_AREA:
{
xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;
A->control = DEVICE_ABS_AREA;
A->length = sizeof(XDeviceAbsAreaState);
A->offset_x = a->offset_x;
A->offset_y = a->offset_y;
A->width = a->width;
A->height = a->height;
A->screen = a->screen;
A->following = a->following;
break;
}
case DEVICE_CORE:
{
xDeviceCoreState *c = (xDeviceCoreState *) d;
XDeviceCoreState *C = (XDeviceCoreState *) Device;
C->control = DEVICE_CORE;
C->length = sizeof(XDeviceCoreState);
C->status = c->status;
C->iscore = c->iscore;
break;
}
case DEVICE_ENABLE:
{
xDeviceEnableState *e = (xDeviceEnableState *) d;
XDeviceEnableState *E = (XDeviceEnableState *) Device;
E->control = DEVICE_ENABLE;
E->length = sizeof(E);
E->enable = e->enable;
break;
}
default:
break;
}
}
Commit Message:
CWE ID: CWE-284 | XGetDeviceControl(
register Display *dpy,
XDevice *dev,
int control)
{
XDeviceControl *Device = NULL;
XDeviceControl *Sav = NULL;
xDeviceState *d = NULL;
xDeviceState *sav = NULL;
xGetDeviceControlReq *req;
xGetDeviceControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
return NULL;
GetReq(GetDeviceControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceControl;
req->deviceid = dev->device_id;
req->control = control;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
if (rep.length < (INT_MAX >> 2) &&
(rep.length << 2) >= sizeof(xDeviceState)) {
nbytes = (unsigned long) rep.length << 2;
d = Xmalloc(nbytes);
}
_XEatDataWords(dpy, rep.length);
goto out;
}
sav = d;
_XRead(dpy, (char *)d, nbytes);
/* In theory, we should just be able to use d->length to get the size.
* Turns out that a number of X servers (up to and including server
* 1.4) sent the wrong length value down the wire. So to not break
* apps that run against older servers, we have to calculate the size
* manually.
*/
switch (d->control) {
case DEVICE_RESOLUTION:
{
xDeviceResolutionState *r;
size_t val_size;
size_t val_size;
r = (xDeviceResolutionState *) d;
if (sizeof(xDeviceResolutionState) > nbytes ||
r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
goto out;
val_size = 3 * sizeof(int) * r->num_valuators;
if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
break;
}
case DEVICE_ABS_CALIB:
{
if (sizeof(xDeviceAbsCalibState) > nbytes)
goto out;
size = sizeof(XDeviceAbsCalibState);
break;
}
case DEVICE_ABS_AREA:
{
if (sizeof(xDeviceAbsAreaState) > nbytes)
goto out;
size = sizeof(XDeviceAbsAreaState);
break;
}
case DEVICE_CORE:
{
if (sizeof(xDeviceCoreState) > nbytes)
goto out;
size = sizeof(XDeviceCoreState);
break;
}
default:
if (d->length > nbytes)
goto out;
size = d->length;
break;
}
Device = Xmalloc(size);
if (!Device)
goto out;
Sav = Device;
d = sav;
switch (control) {
case DEVICE_RESOLUTION:
{
int *iptr, *iptr2;
xDeviceResolutionState *r;
XDeviceResolutionState *R;
unsigned int i;
r = (xDeviceResolutionState *) d;
R = (XDeviceResolutionState *) Device;
R->control = DEVICE_RESOLUTION;
R->length = sizeof(XDeviceResolutionState);
R->num_valuators = r->num_valuators;
iptr = (int *)(R + 1);
iptr2 = (int *)(r + 1);
R->resolutions = iptr;
R->min_resolutions = iptr + R->num_valuators;
R->max_resolutions = iptr + (2 * R->num_valuators);
for (i = 0; i < (3 * R->num_valuators); i++)
*iptr++ = *iptr2++;
break;
}
case DEVICE_ABS_CALIB:
{
xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;
C->control = DEVICE_ABS_CALIB;
C->length = sizeof(XDeviceAbsCalibState);
C->min_x = c->min_x;
C->max_x = c->max_x;
C->min_y = c->min_y;
C->max_y = c->max_y;
C->flip_x = c->flip_x;
C->flip_y = c->flip_y;
C->rotation = c->rotation;
C->button_threshold = c->button_threshold;
break;
}
case DEVICE_ABS_AREA:
{
xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;
A->control = DEVICE_ABS_AREA;
A->length = sizeof(XDeviceAbsAreaState);
A->offset_x = a->offset_x;
A->offset_y = a->offset_y;
A->width = a->width;
A->height = a->height;
A->screen = a->screen;
A->following = a->following;
break;
}
case DEVICE_CORE:
{
xDeviceCoreState *c = (xDeviceCoreState *) d;
XDeviceCoreState *C = (XDeviceCoreState *) Device;
C->control = DEVICE_CORE;
C->length = sizeof(XDeviceCoreState);
C->status = c->status;
C->iscore = c->iscore;
break;
}
case DEVICE_ENABLE:
{
xDeviceEnableState *e = (xDeviceEnableState *) d;
XDeviceEnableState *E = (XDeviceEnableState *) Device;
E->control = DEVICE_ENABLE;
E->length = sizeof(E);
E->enable = e->enable;
break;
}
default:
break;
}
}
| 164,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex)
: mGraphicBuffer(graphicBuffer),
mIsBackup(false),
mPortIndex(portIndex) {
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex)
: mGraphicBuffer(graphicBuffer),
mCopyFromOmx(false),
mCopyToOmx(false),
mPortIndex(portIndex),
mBackup(NULL) {
}
| 174,126 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
Commit Message: Use strncmp when checking for large ascii multigets.
CWE ID: CWE-20 | static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
| 165,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AppListController::Init(Profile* initial_profile) {
if (win8::IsSingleWindowMetroMode())
return;
PrefService* prefs = g_browser_process->local_state();
if (prefs->HasPrefPath(prefs::kRestartWithAppList) &&
prefs->GetBoolean(prefs::kRestartWithAppList)) {
prefs->SetBoolean(prefs::kRestartWithAppList, false);
AppListController::GetInstance()->
ShowAppListDuringModeSwitch(initial_profile);
}
AppListController::GetInstance();
ScheduleWarmup();
MigrateAppLauncherEnabledPref();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList))
EnableAppList();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList))
DisableAppList();
}
Commit Message: Upgrade old app host to new app launcher on startup
This patch is a continuation of https://codereview.chromium.org/16805002/.
BUG=248825
Review URL: https://chromiumcodereview.appspot.com/17022015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AppListController::Init(Profile* initial_profile) {
if (win8::IsSingleWindowMetroMode())
return;
PrefService* prefs = g_browser_process->local_state();
if (prefs->HasPrefPath(prefs::kRestartWithAppList) &&
prefs->GetBoolean(prefs::kRestartWithAppList)) {
prefs->SetBoolean(prefs::kRestartWithAppList, false);
AppListController::GetInstance()->
ShowAppListDuringModeSwitch(initial_profile);
}
// Migrate from legacy app launcher if we are on a non-canary and non-chromium
// build.
#if defined(GOOGLE_CHROME_BUILD)
if (!InstallUtil::IsChromeSxSProcess() &&
!chrome_launcher_support::GetAnyAppHostPath().empty()) {
chrome_launcher_support::InstallationState state =
chrome_launcher_support::GetAppLauncherInstallationState();
if (state == chrome_launcher_support::NOT_INSTALLED) {
// If app_host.exe is found but can't be located in the registry,
// skip the migration as this is likely a developer build.
return;
} else if (state == chrome_launcher_support::INSTALLED_AT_SYSTEM_LEVEL) {
chrome_launcher_support::UninstallLegacyAppLauncher(
chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION);
} else if (state == chrome_launcher_support::INSTALLED_AT_USER_LEVEL) {
chrome_launcher_support::UninstallLegacyAppLauncher(
chrome_launcher_support::USER_LEVEL_INSTALLATION);
}
EnableAppList();
}
#endif
AppListController::GetInstance();
ScheduleWarmup();
MigrateAppLauncherEnabledPref();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList))
EnableAppList();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList))
DisableAppList();
}
| 171,337 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
}
| 170,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
if (UNEXPECTED(Z_ISUNDEF_P(data))) {
if (Z_TYPE(key) == IS_LONG) {
zend_hash_index_del(ht, Z_LVAL(key));
} else {
zend_hash_del_ind(ht, Z_STR(key));
}
} else {
var_push_dtor(var_hash, data);
}
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
Commit Message: Fixed bug #74103 and bug #75054
Directly fail unserialization when trying to acquire an r/R
reference to an UNDEF HT slot. Previously this left an UNDEF and
later deleted the index/key from the HT.
What actually caused the issue here is a combination of two
factors: First, the key deletion was performed using the hash API,
rather than the symtable API, such that the element was not actually
removed if it used an integral string key. Second, a subsequent
deletion operation, while collecting trailing UNDEF ranges, would
mark the element as available for reuse (leaving a corrupted HT
state with nNumOfElemnts > nNumUsed).
Fix this by failing early and dropping the deletion code.
CWE ID: CWE-416 | static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
var_push_dtor(var_hash, data);
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 167,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation =
args.confirmation_required;
if (start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST &&
confirmation == OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN) {
confirmation = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
confirmation);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
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 | void StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
args.confirmation_required,
args.source);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
| 171,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/362
CWE ID: CWE-200 | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
| 167,810 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SynchronousCompositorOutputSurface::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(HasClient());
DCHECK(context_provider_.get());
surface_size_ = surface_size;
InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority,
transform_for_tile_priority, true);
return frame_holder_.Pass();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | SynchronousCompositorOutputSurface::DemandDrawHw(
const gfx::Size& surface_size,
const gfx::Transform& transform,
const gfx::Rect& viewport,
const gfx::Rect& clip,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(HasClient());
DCHECK(context_provider_.get());
surface_size_ = surface_size;
InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority,
transform_for_tile_priority, true);
return frame_holder_.Pass();
}
| 171,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 CSoundFile::ReadSTP(FileReader &file, ModLoadingFlags loadFlags)
{
file.Rewind();
STPFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return false;
}
if(!ValidateHeader(fileHeader))
{
return false;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
InitializeGlobals(MOD_TYPE_STP);
m_nChannels = 4;
m_nSamples = 0;
m_nDefaultSpeed = fileHeader.speed;
m_nDefaultTempo = ConvertTempo(fileHeader.timerCount);
m_nMinPeriod = 14 * 4;
m_nMaxPeriod = 3424 * 4;
ReadOrderFromArray(Order(), fileHeader.orderList, fileHeader.numOrders);
std::vector<STPLoopList> loopInfo;
std::vector<SAMPLEINDEX> nonLooped;
SAMPLEINDEX samplesInFile = 0;
for(SAMPLEINDEX smp = 0; smp < fileHeader.numSamples; smp++)
{
SAMPLEINDEX actualSmp = file.ReadUint16BE();
if(actualSmp == 0 || actualSmp >= MAX_SAMPLES)
return false;
uint32 chunkSize = fileHeader.sampleStructSize;
if(fileHeader.version == 2)
chunkSize = file.ReadUint32BE() - 2;
FileReader chunk = file.ReadChunk(chunkSize);
samplesInFile = m_nSamples = std::max(m_nSamples, actualSmp);
ModSample &mptSmp = Samples[actualSmp];
mptSmp.Initialize(MOD_TYPE_MOD);
if(fileHeader.version < 2)
{
chunk.ReadString<mpt::String::maybeNullTerminated>(mptSmp.filename, 31);
chunk.Skip(1);
chunk.ReadString<mpt::String::maybeNullTerminated>(m_szNames[actualSmp], 30);
} else
{
std::string str;
chunk.ReadNullString(str, 257);
mpt::String::Copy(mptSmp.filename, str);
chunk.Skip(1);
chunk.ReadNullString(str, 31);
mpt::String::Copy(m_szNames[actualSmp], str);
if(chunk.GetPosition() % 2u)
chunk.Skip(1);
}
STPSampleHeader sampleHeader;
chunk.ReadStruct(sampleHeader);
sampleHeader.ConvertToMPT(mptSmp);
if(fileHeader.version == 2)
{
mptSmp.nFineTune = static_cast<int8>(sampleHeader.finetune << 3);
}
if(fileHeader.version >= 1)
{
nonLooped.resize(samplesInFile);
loopInfo.resize(samplesInFile);
STPLoopList &loopList = loopInfo[actualSmp - 1];
loopList.clear();
uint16 numLoops = file.ReadUint16BE();
loopList.reserve(numLoops);
STPLoopInfo loop;
loop.looped = loop.nonLooped = 0;
if(numLoops == 0 && mptSmp.uFlags[CHN_LOOP])
{
loop.loopStart = mptSmp.nLoopStart;
loop.loopLength = mptSmp.nLoopEnd - mptSmp.nLoopStart;
loopList.push_back(loop);
} else for(uint16 i = 0; i < numLoops; i++)
{
loop.loopStart = file.ReadUint32BE();
loop.loopLength = file.ReadUint32BE();
loopList.push_back(loop);
}
}
}
uint16 numPatterns = 128;
if(fileHeader.version == 0)
numPatterns = file.ReadUint16BE();
uint16 patternLength = fileHeader.patternLength;
CHANNELINDEX channels = 4;
if(fileHeader.version > 0)
{
FileReader::off_t patOffset = file.GetPosition();
for(uint16 pat = 0; pat < numPatterns; pat++)
{
PATTERNINDEX actualPat = file.ReadUint16BE();
if(actualPat == 0xFFFF)
break;
patternLength = file.ReadUint16BE();
channels = file.ReadUint16BE();
m_nChannels = std::max(m_nChannels, channels);
file.Skip(channels * patternLength * 4u);
}
file.Seek(patOffset);
if(m_nChannels > MAX_BASECHANNELS)
return false;
}
struct ChannelMemory
{
uint8 autoFinePorta, autoPortaUp, autoPortaDown, autoVolSlide, autoVibrato;
uint8 vibratoMem, autoTremolo, autoTonePorta, tonePortaMem;
};
std::vector<ChannelMemory> channelMemory(m_nChannels);
uint8 globalVolSlide = 0;
for(uint16 pat = 0; pat < numPatterns; pat++)
{
PATTERNINDEX actualPat = pat;
if(fileHeader.version > 0)
{
actualPat = file.ReadUint16BE();
if(actualPat == 0xFFFF)
break;
patternLength = file.ReadUint16BE();
channels = file.ReadUint16BE();
}
if(!(loadFlags & loadPatternData) || !Patterns.Insert(actualPat, patternLength))
{
file.Skip(channels * patternLength * 4u);
continue;
}
for(ROWINDEX row = 0; row < patternLength; row++)
{
auto rowBase = Patterns[actualPat].GetRow(row);
bool didGlobalVolSlide = false;
bool shouldDelay;
switch(fileHeader.speedFrac & 3)
{
default: shouldDelay = false; break;
case 1: shouldDelay = (row & 3) == 0; break;
case 2: shouldDelay = (row & 1) == 0; break;
case 3: shouldDelay = (row & 3) != 3; break;
}
for(CHANNELINDEX chn = 0; chn < channels; chn++)
{
ChannelMemory &chnMem = channelMemory[chn];
ModCommand &m = rowBase[chn];
uint8 data[4];
file.ReadArray(data);
m.instr = data[0];
m.note = data[1];
m.command = data[2];
m.param = data[3];
if(m.note)
{
m.note += 24 + NOTE_MIN;
chnMem = ChannelMemory();
}
uint8 swapped = (m.param >> 4) | (m.param << 4);
if((m.command & 0xF0) == 0xF0)
{
uint16 ciaTempo = (static_cast<uint16>(m.command & 0x0F) << 8) | m.param;
if(ciaTempo)
{
m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::Round(ConvertTempo(ciaTempo).ToDouble()));
m.command = CMD_TEMPO;
} else
{
m.command = CMD_NONE;
}
} else switch(m.command)
{
case 0x00: // arpeggio
if(m.param)
m.command = CMD_ARPEGGIO;
break;
case 0x01: // portamento up
m.command = CMD_PORTAMENTOUP;
break;
case 0x02: // portamento down
m.command = CMD_PORTAMENTODOWN;
break;
case 0x03: // auto fine portamento up
chnMem.autoFinePorta = 0x10 | std::min(m.param, ModCommand::PARAM(15));
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = m.param = 0;
break;
case 0x04: // auto fine portamento down
chnMem.autoFinePorta = 0x20 | std::min(m.param, ModCommand::PARAM(15));
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = m.param = 0;
break;
case 0x05: // auto portamento up
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = m.param;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = m.param = 0;
break;
case 0x06: // auto portamento down
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = m.param;
chnMem.autoTonePorta = 0;
m.command = m.param = 0;
break;
case 0x07: // set global volume
m.command = CMD_GLOBALVOLUME;
globalVolSlide = 0;
break;
case 0x08: // auto global fine volume slide
globalVolSlide = swapped;
m.command = m.param = 0;
break;
case 0x09: // fine portamento up
m.command = CMD_MODCMDEX;
m.param = 0x10 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x0A: // fine portamento down
m.command = CMD_MODCMDEX;
m.param = 0x20 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x0B: // auto fine volume slide
chnMem.autoVolSlide = swapped;
m.command = m.param = 0;
break;
case 0x0C: // set volume
m.volcmd = VOLCMD_VOLUME;
m.vol = m.param;
chnMem.autoVolSlide = 0;
m.command = m.param = 0;
break;
case 0x0D: // volume slide (param is swapped compared to .mod)
if(m.param & 0xF0)
{
m.volcmd = VOLCMD_VOLSLIDEDOWN;
m.vol = m.param >> 4;
} else if(m.param & 0x0F)
{
m.volcmd = VOLCMD_VOLSLIDEUP;
m.vol = m.param & 0xF;
}
chnMem.autoVolSlide = 0;
m.command = m.param = 0;
break;
case 0x0E: // set filter (also uses opposite value compared to .mod)
m.command = CMD_MODCMDEX;
m.param = 1 ^ (m.param ? 1 : 0);
break;
case 0x0F: // set speed
m.command = CMD_SPEED;
fileHeader.speedFrac = m.param & 0xF;
m.param >>= 4;
break;
case 0x10: // auto vibrato
chnMem.autoVibrato = m.param;
chnMem.vibratoMem = 0;
m.command = m.param = 0;
break;
case 0x11: // auto tremolo
if(m.param & 0xF)
chnMem.autoTremolo = m.param;
else
chnMem.autoTremolo = 0;
m.command = m.param = 0;
break;
case 0x12: // pattern break
m.command = CMD_PATTERNBREAK;
break;
case 0x13: // auto tone portamento
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = m.param;
chnMem.tonePortaMem = 0;
m.command = m.param = 0;
break;
case 0x14: // position jump
m.command = CMD_POSITIONJUMP;
break;
case 0x16: // start loop sequence
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < std::min(mpt::size(ModSample().cues), loopList.size()))
{
m.volcmd = VOLCMD_OFFSET;
m.vol = m.param;
}
}
m.command = m.param = 0;
break;
case 0x17: // play only loop nn
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < loopList.size())
{
if(!loopList[m.param].looped && m_nSamples < MAX_SAMPLES - 1)
loopList[m.param].looped = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].looped);
}
}
m.command = m.param = 0;
break;
case 0x18: // play sequence without loop
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < std::min(mpt::size(ModSample().cues), loopList.size()))
{
m.volcmd = VOLCMD_OFFSET;
m.vol = m.param;
}
if(!nonLooped[m.instr - 1] && m_nSamples < MAX_SAMPLES - 1)
nonLooped[m.instr - 1] = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(nonLooped[m.instr - 1]);
}
m.command = m.param = 0;
break;
case 0x19: // play only loop nn without loop
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < loopList.size())
{
if(!loopList[m.param].nonLooped && m_nSamples < MAX_SAMPLES-1)
loopList[m.param].nonLooped = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].nonLooped);
}
}
m.command = m.param = 0;
break;
case 0x1D: // fine volume slide (nibble order also swapped)
m.command = CMD_VOLUMESLIDE;
m.param = swapped;
if(m.param & 0xF0) // slide down
m.param |= 0x0F;
else if(m.param & 0x0F)
m.param |= 0xF0;
break;
case 0x20: // "delayed fade"
if(m.param & 0xF0)
{
chnMem.autoVolSlide = m.param >> 4;
m.command = m.param = 0;
} else
{
m.command = CMD_MODCMDEX;
m.param = 0xC0 | (m.param & 0xF);
}
break;
case 0x21: // note delay
m.command = CMD_MODCMDEX;
m.param = 0xD0 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x22: // retrigger note
m.command = CMD_MODCMDEX;
m.param = 0x90 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x49: // set sample offset
m.command = CMD_OFFSET;
break;
case 0x4E: // other protracker commands (pattern loop / delay)
if((m.param & 0xF0) == 0x60 || (m.param & 0xF0) == 0xE0)
m.command = CMD_MODCMDEX;
else
m.command = m.param = 0;
break;
case 0x4F: // set speed/tempo
if(m.param < 0x20)
{
m.command = CMD_SPEED;
fileHeader.speedFrac = 0;
} else
{
m.command = CMD_TEMPO;
}
break;
default:
m.command = CMD_NONE;
break;
}
bool didVolSlide = false;
if(chnMem.autoVolSlide && !m.volcmd)
{
if(chnMem.autoVolSlide & 0xF0)
{
m.volcmd = VOLCMD_FINEVOLUP;
m.vol = chnMem.autoVolSlide >> 4;
} else
{
m.volcmd = VOLCMD_FINEVOLDOWN;
m.vol = chnMem.autoVolSlide & 0xF;
}
didVolSlide = true;
}
if(m.command == CMD_NONE)
{
if(chnMem.autoPortaUp)
{
m.command = CMD_PORTAMENTOUP;
m.param = chnMem.autoPortaUp;
} else if(chnMem.autoPortaDown)
{
m.command = CMD_PORTAMENTODOWN;
m.param = chnMem.autoPortaDown;
} else if(chnMem.autoFinePorta)
{
m.command = CMD_MODCMDEX;
m.param = chnMem.autoFinePorta;
} else if(chnMem.autoTonePorta)
{
m.command = CMD_TONEPORTAMENTO;
m.param = chnMem.tonePortaMem = chnMem.autoTonePorta;
} else if(chnMem.autoVibrato)
{
m.command = CMD_VIBRATO;
m.param = chnMem.vibratoMem = chnMem.autoVibrato;
} else if(!didVolSlide && chnMem.autoVolSlide)
{
m.command = CMD_VOLUMESLIDE;
m.param = chnMem.autoVolSlide;
if(m.param & 0x0F)
m.param |= 0xF0;
else if(m.param & 0xF0)
m.param |= 0x0F;
didVolSlide = true;
} else if(chnMem.autoTremolo)
{
m.command = CMD_TREMOLO;
m.param = chnMem.autoTremolo;
} else if(shouldDelay)
{
m.command = CMD_S3MCMDEX;
m.param = 0x61;
shouldDelay = false;
} else if(!didGlobalVolSlide && globalVolSlide)
{
m.command = CMD_GLOBALVOLSLIDE;
m.param = globalVolSlide;
if(m.param & 0x0F)
m.param |= 0xF0;
else if(m.param & 0xF0)
m.param |= 0x0F;
didGlobalVolSlide = true;
}
}
}
}
}
m_nSamplePreAmp = 256 / m_nChannels;
SetupMODPanning(true);
if(fileHeader.version > 0)
{
while(file.CanRead(2))
{
uint16 scriptNum = file.ReadUint16BE();
if(scriptNum == 0xFFFF)
break;
file.Skip(2);
uint32 length = file.ReadUint32BE();
file.Skip(length);
}
file.Skip(17 * 2);
}
if(loadFlags & loadSampleData)
{
for(SAMPLEINDEX smp = 1; smp <= samplesInFile; smp++) if(Samples[smp].nLength)
{
SampleIO(
SampleIO::_8bit,
SampleIO::mono,
SampleIO::littleEndian,
SampleIO::signedPCM)
.ReadSample(Samples[smp], file);
if(smp > loopInfo.size())
continue;
ConvertLoopSequence(Samples[smp], loopInfo[smp - 1]);
if(nonLooped[smp - 1])
{
ConvertLoopSlice(Samples[smp], Samples[nonLooped[smp - 1]], 0, Samples[smp].nLength, false);
}
for(const auto &info : loopInfo[smp - 1])
{
if(info.looped)
{
ConvertLoopSlice(Samples[smp], Samples[info.looped], info.loopStart, info.loopLength, true);
}
if(info.nonLooped)
{
ConvertLoopSlice(Samples[smp], Samples[info.nonLooped], info.loopStart, info.loopLength, false);
}
}
}
}
return true;
}
Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz).
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27
CWE ID: CWE-125 | bool CSoundFile::ReadSTP(FileReader &file, ModLoadingFlags loadFlags)
{
file.Rewind();
STPFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return false;
}
if(!ValidateHeader(fileHeader))
{
return false;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
InitializeGlobals(MOD_TYPE_STP);
m_nChannels = 4;
m_nSamples = 0;
m_nDefaultSpeed = fileHeader.speed;
m_nDefaultTempo = ConvertTempo(fileHeader.timerCount);
m_nMinPeriod = 14 * 4;
m_nMaxPeriod = 3424 * 4;
ReadOrderFromArray(Order(), fileHeader.orderList, fileHeader.numOrders);
std::vector<STPLoopList> loopInfo;
// Non-looped versions of samples with loops (when needed)
std::vector<SAMPLEINDEX> nonLooped;
SAMPLEINDEX samplesInFile = 0;
for(SAMPLEINDEX smp = 0; smp < fileHeader.numSamples; smp++)
{
SAMPLEINDEX actualSmp = file.ReadUint16BE();
if(actualSmp == 0 || actualSmp >= MAX_SAMPLES)
return false;
uint32 chunkSize = fileHeader.sampleStructSize;
if(fileHeader.version == 2)
chunkSize = file.ReadUint32BE() - 2;
FileReader chunk = file.ReadChunk(chunkSize);
samplesInFile = m_nSamples = std::max(m_nSamples, actualSmp);
ModSample &mptSmp = Samples[actualSmp];
mptSmp.Initialize(MOD_TYPE_MOD);
if(fileHeader.version < 2)
{
chunk.ReadString<mpt::String::maybeNullTerminated>(mptSmp.filename, 31);
chunk.Skip(1);
chunk.ReadString<mpt::String::maybeNullTerminated>(m_szNames[actualSmp], 30);
} else
{
std::string str;
chunk.ReadNullString(str, 257);
mpt::String::Copy(mptSmp.filename, str);
chunk.Skip(1);
chunk.ReadNullString(str, 31);
mpt::String::Copy(m_szNames[actualSmp], str);
if(chunk.GetPosition() % 2u)
chunk.Skip(1);
}
STPSampleHeader sampleHeader;
chunk.ReadStruct(sampleHeader);
sampleHeader.ConvertToMPT(mptSmp);
if(fileHeader.version == 2)
{
mptSmp.nFineTune = static_cast<int8>(sampleHeader.finetune << 3);
}
if(fileHeader.version >= 1)
{
nonLooped.resize(samplesInFile);
loopInfo.resize(samplesInFile);
STPLoopList &loopList = loopInfo[actualSmp - 1];
loopList.clear();
uint16 numLoops = file.ReadUint16BE();
loopList.reserve(numLoops);
STPLoopInfo loop;
loop.looped = loop.nonLooped = 0;
if(numLoops == 0 && mptSmp.uFlags[CHN_LOOP])
{
loop.loopStart = mptSmp.nLoopStart;
loop.loopLength = mptSmp.nLoopEnd - mptSmp.nLoopStart;
loopList.push_back(loop);
} else for(uint16 i = 0; i < numLoops; i++)
{
loop.loopStart = file.ReadUint32BE();
loop.loopLength = file.ReadUint32BE();
loopList.push_back(loop);
}
}
}
uint16 numPatterns = 128;
if(fileHeader.version == 0)
numPatterns = file.ReadUint16BE();
uint16 patternLength = fileHeader.patternLength;
CHANNELINDEX channels = 4;
if(fileHeader.version > 0)
{
FileReader::off_t patOffset = file.GetPosition();
for(uint16 pat = 0; pat < numPatterns; pat++)
{
PATTERNINDEX actualPat = file.ReadUint16BE();
if(actualPat == 0xFFFF)
break;
patternLength = file.ReadUint16BE();
channels = file.ReadUint16BE();
m_nChannels = std::max(m_nChannels, channels);
file.Skip(channels * patternLength * 4u);
}
file.Seek(patOffset);
if(m_nChannels > MAX_BASECHANNELS)
return false;
}
struct ChannelMemory
{
uint8 autoFinePorta, autoPortaUp, autoPortaDown, autoVolSlide, autoVibrato;
uint8 vibratoMem, autoTremolo, autoTonePorta, tonePortaMem;
};
std::vector<ChannelMemory> channelMemory(m_nChannels);
uint8 globalVolSlide = 0;
uint8 speedFrac = static_cast<uint8>(fileHeader.speedFrac);
for(uint16 pat = 0; pat < numPatterns; pat++)
{
PATTERNINDEX actualPat = pat;
if(fileHeader.version > 0)
{
actualPat = file.ReadUint16BE();
if(actualPat == 0xFFFF)
break;
patternLength = file.ReadUint16BE();
channels = file.ReadUint16BE();
}
if(!(loadFlags & loadPatternData) || !Patterns.Insert(actualPat, patternLength))
{
file.Skip(channels * patternLength * 4u);
continue;
}
for(ROWINDEX row = 0; row < patternLength; row++)
{
auto rowBase = Patterns[actualPat].GetRow(row);
bool didGlobalVolSlide = false;
bool shouldDelay;
switch(speedFrac & 3)
{
default: shouldDelay = false; break;
case 1: shouldDelay = (row & 3) == 0; break;
case 2: shouldDelay = (row & 1) == 0; break;
case 3: shouldDelay = (row & 3) != 3; break;
}
for(CHANNELINDEX chn = 0; chn < channels; chn++)
{
ChannelMemory &chnMem = channelMemory[chn];
ModCommand &m = rowBase[chn];
uint8 data[4];
file.ReadArray(data);
m.instr = data[0];
m.note = data[1];
m.command = data[2];
m.param = data[3];
if(m.note)
{
m.note += 24 + NOTE_MIN;
chnMem = ChannelMemory();
}
uint8 swapped = (m.param >> 4) | (m.param << 4);
if((m.command & 0xF0) == 0xF0)
{
uint16 ciaTempo = (static_cast<uint16>(m.command & 0x0F) << 8) | m.param;
if(ciaTempo)
{
m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::Round(ConvertTempo(ciaTempo).ToDouble()));
m.command = CMD_TEMPO;
} else
{
m.command = CMD_NONE;
}
} else switch(m.command)
{
case 0x00: // arpeggio
if(m.param)
m.command = CMD_ARPEGGIO;
break;
case 0x01: // portamento up
m.command = CMD_PORTAMENTOUP;
break;
case 0x02: // portamento down
m.command = CMD_PORTAMENTODOWN;
break;
case 0x03: // auto fine portamento up
chnMem.autoFinePorta = 0x10 | std::min(m.param, ModCommand::PARAM(15));
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = CMD_NONE;
break;
case 0x04: // auto fine portamento down
chnMem.autoFinePorta = 0x20 | std::min(m.param, ModCommand::PARAM(15));
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = CMD_NONE;
break;
case 0x05: // auto portamento up
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = m.param;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = 0;
m.command = CMD_NONE;
break;
case 0x06: // auto portamento down
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = m.param;
chnMem.autoTonePorta = 0;
m.command = CMD_NONE;
break;
case 0x07: // set global volume
m.command = CMD_GLOBALVOLUME;
globalVolSlide = 0;
break;
case 0x08: // auto global fine volume slide
globalVolSlide = swapped;
m.command = CMD_NONE;
break;
case 0x09: // fine portamento up
m.command = CMD_MODCMDEX;
m.param = 0x10 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x0A: // fine portamento down
m.command = CMD_MODCMDEX;
m.param = 0x20 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x0B: // auto fine volume slide
chnMem.autoVolSlide = swapped;
m.command = CMD_NONE;
break;
case 0x0C: // set volume
m.volcmd = VOLCMD_VOLUME;
m.vol = m.param;
chnMem.autoVolSlide = 0;
m.command = CMD_NONE;
break;
case 0x0D: // volume slide (param is swapped compared to .mod)
if(m.param & 0xF0)
{
m.volcmd = VOLCMD_VOLSLIDEDOWN;
m.vol = m.param >> 4;
} else if(m.param & 0x0F)
{
m.volcmd = VOLCMD_VOLSLIDEUP;
m.vol = m.param & 0xF;
}
chnMem.autoVolSlide = 0;
m.command = CMD_NONE;
break;
case 0x0E: // set filter (also uses opposite value compared to .mod)
m.command = CMD_MODCMDEX;
m.param = 1 ^ (m.param ? 1 : 0);
break;
case 0x0F: // set speed
m.command = CMD_SPEED;
speedFrac = m.param & 0x0F;
m.param >>= 4;
break;
case 0x10: // auto vibrato
chnMem.autoVibrato = m.param;
chnMem.vibratoMem = 0;
m.command = CMD_NONE;
break;
case 0x11: // auto tremolo
if(m.param & 0xF)
chnMem.autoTremolo = m.param;
else
chnMem.autoTremolo = 0;
m.command = CMD_NONE;
break;
case 0x12: // pattern break
m.command = CMD_PATTERNBREAK;
break;
case 0x13: // auto tone portamento
chnMem.autoFinePorta = 0;
chnMem.autoPortaUp = 0;
chnMem.autoPortaDown = 0;
chnMem.autoTonePorta = m.param;
chnMem.tonePortaMem = 0;
m.command = CMD_NONE;
break;
case 0x14: // position jump
m.command = CMD_POSITIONJUMP;
break;
case 0x16: // start loop sequence
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < std::min(mpt::size(ModSample().cues), loopList.size()))
{
m.volcmd = VOLCMD_OFFSET;
m.vol = m.param;
}
}
m.command = CMD_NONE;
break;
case 0x17: // play only loop nn
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < loopList.size())
{
if(!loopList[m.param].looped && m_nSamples < MAX_SAMPLES - 1)
loopList[m.param].looped = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].looped);
}
}
m.command = CMD_NONE;
break;
case 0x18: // play sequence without loop
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < std::min(mpt::size(ModSample().cues), loopList.size()))
{
m.volcmd = VOLCMD_OFFSET;
m.vol = m.param;
}
if(!nonLooped[m.instr - 1] && m_nSamples < MAX_SAMPLES - 1)
nonLooped[m.instr - 1] = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(nonLooped[m.instr - 1]);
}
m.command = CMD_NONE;
break;
case 0x19: // play only loop nn without loop
if(m.instr && m.instr <= loopInfo.size())
{
STPLoopList &loopList = loopInfo[m.instr - 1];
m.param--;
if(m.param < loopList.size())
{
if(!loopList[m.param].nonLooped && m_nSamples < MAX_SAMPLES-1)
loopList[m.param].nonLooped = ++m_nSamples;
m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].nonLooped);
}
}
m.command = CMD_NONE;
break;
case 0x1D: // fine volume slide (nibble order also swapped)
m.command = CMD_VOLUMESLIDE;
m.param = swapped;
if(m.param & 0xF0) // slide down
m.param |= 0x0F;
else if(m.param & 0x0F)
m.param |= 0xF0;
break;
case 0x20: // "delayed fade"
if(m.param & 0xF0)
{
chnMem.autoVolSlide = m.param >> 4;
m.command = CMD_NONE;
} else
{
m.command = CMD_MODCMDEX;
m.param = 0xC0 | (m.param & 0xF);
}
break;
case 0x21: // note delay
m.command = CMD_MODCMDEX;
m.param = 0xD0 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x22: // retrigger note
m.command = CMD_MODCMDEX;
m.param = 0x90 | std::min(m.param, ModCommand::PARAM(15));
break;
case 0x49: // set sample offset
m.command = CMD_OFFSET;
break;
case 0x4E: // other protracker commands (pattern loop / delay)
if((m.param & 0xF0) == 0x60 || (m.param & 0xF0) == 0xE0)
m.command = CMD_MODCMDEX;
else
m.command = CMD_NONE;
break;
case 0x4F: // set speed/tempo
if(m.param < 0x20)
{
m.command = CMD_SPEED;
speedFrac = 0;
} else
{
m.command = CMD_TEMPO;
}
break;
default:
m.command = CMD_NONE;
break;
}
bool didVolSlide = false;
if(chnMem.autoVolSlide && m.volcmd == VOLCMD_NONE)
{
if(chnMem.autoVolSlide & 0xF0)
{
m.volcmd = VOLCMD_FINEVOLUP;
m.vol = chnMem.autoVolSlide >> 4;
} else
{
m.volcmd = VOLCMD_FINEVOLDOWN;
m.vol = chnMem.autoVolSlide & 0xF;
}
didVolSlide = true;
}
if(m.command == CMD_NONE)
{
if(chnMem.autoPortaUp)
{
m.command = CMD_PORTAMENTOUP;
m.param = chnMem.autoPortaUp;
} else if(chnMem.autoPortaDown)
{
m.command = CMD_PORTAMENTODOWN;
m.param = chnMem.autoPortaDown;
} else if(chnMem.autoFinePorta)
{
m.command = CMD_MODCMDEX;
m.param = chnMem.autoFinePorta;
} else if(chnMem.autoTonePorta)
{
m.command = CMD_TONEPORTAMENTO;
m.param = chnMem.tonePortaMem = chnMem.autoTonePorta;
} else if(chnMem.autoVibrato)
{
m.command = CMD_VIBRATO;
m.param = chnMem.vibratoMem = chnMem.autoVibrato;
} else if(!didVolSlide && chnMem.autoVolSlide)
{
m.command = CMD_VOLUMESLIDE;
m.param = chnMem.autoVolSlide;
if(m.param & 0x0F)
m.param |= 0xF0;
else if(m.param & 0xF0)
m.param |= 0x0F;
didVolSlide = true;
} else if(chnMem.autoTremolo)
{
m.command = CMD_TREMOLO;
m.param = chnMem.autoTremolo;
} else if(shouldDelay)
{
m.command = CMD_S3MCMDEX;
m.param = 0x61;
shouldDelay = false;
} else if(!didGlobalVolSlide && globalVolSlide)
{
m.command = CMD_GLOBALVOLSLIDE;
m.param = globalVolSlide;
if(m.param & 0x0F)
m.param |= 0xF0;
else if(m.param & 0xF0)
m.param |= 0x0F;
didGlobalVolSlide = true;
}
}
}
}
}
m_nSamplePreAmp = 256 / m_nChannels;
SetupMODPanning(true);
if(fileHeader.version > 0)
{
while(file.CanRead(2))
{
uint16 scriptNum = file.ReadUint16BE();
if(scriptNum == 0xFFFF)
break;
file.Skip(2);
uint32 length = file.ReadUint32BE();
file.Skip(length);
}
file.Skip(17 * 2);
}
if(loadFlags & loadSampleData)
{
for(SAMPLEINDEX smp = 1; smp <= samplesInFile; smp++) if(Samples[smp].nLength)
{
SampleIO(
SampleIO::_8bit,
SampleIO::mono,
SampleIO::littleEndian,
SampleIO::signedPCM)
.ReadSample(Samples[smp], file);
if(smp > loopInfo.size())
continue;
ConvertLoopSequence(Samples[smp], loopInfo[smp - 1]);
if(nonLooped[smp - 1])
{
ConvertLoopSlice(Samples[smp], Samples[nonLooped[smp - 1]], 0, Samples[smp].nLength, false);
}
for(const auto &info : loopInfo[smp - 1])
{
if(info.looped)
{
ConvertLoopSlice(Samples[smp], Samples[info.looped], info.loopStart, info.loopLength, true);
}
if(info.nonLooped)
{
ConvertLoopSlice(Samples[smp], Samples[info.nonLooped], info.loopStart, info.loopLength, false);
}
}
}
}
return true;
}
| 169,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static PHP_MINIT_FUNCTION(zip)
{
#ifdef PHP_ZIP_USE_OO
zend_class_entry ce;
memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
zip_object_handlers.clone_obj = NULL;
zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr;
zip_object_handlers.get_properties = php_zip_get_properties;
zip_object_handlers.read_property = php_zip_read_property;
zip_object_handlers.has_property = php_zip_has_property;
INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions);
ce.create_object = php_zip_object_new;
zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1);
php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC);
REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE);
REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL);
REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS);
REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR);
REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED);
REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT);
REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4);
REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA);
REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77);
REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD);
/* Error code */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */
REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */
php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC);
#endif
le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number);
le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number);
return SUCCESS;
}
Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize
CWE ID: CWE-416 | static PHP_MINIT_FUNCTION(zip)
{
#ifdef PHP_ZIP_USE_OO
zend_class_entry ce;
memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
zip_object_handlers.clone_obj = NULL;
zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr;
zip_object_handlers.get_gc = php_zip_get_gc;
zip_object_handlers.get_properties = php_zip_get_properties;
zip_object_handlers.read_property = php_zip_read_property;
zip_object_handlers.has_property = php_zip_has_property;
INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions);
ce.create_object = php_zip_object_new;
zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1);
php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC);
REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE);
REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL);
REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS);
REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR);
REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED);
REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT);
REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4);
REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA);
REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77);
REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD);
/* Error code */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */
REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */
php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC);
#endif
le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number);
le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number);
return SUCCESS;
}
| 167,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode(
const scoped_refptr<VP9Picture>& pic,
const Vp9SegmentationParams& seg,
const Vp9LoopFilterParams& lf,
const std::vector<scoped_refptr<VP9Picture>>& ref_pictures,
const base::Closure& done_cb) {
DCHECK(done_cb.is_null());
VADecPictureParameterBufferVP9 pic_param;
memset(&pic_param, 0, sizeof(pic_param));
const Vp9FrameHeader* frame_hdr = pic->frame_hdr.get();
DCHECK(frame_hdr);
pic_param.frame_width = base::checked_cast<uint16_t>(frame_hdr->frame_width);
pic_param.frame_height =
base::checked_cast<uint16_t>(frame_hdr->frame_height);
CHECK_EQ(ref_pictures.size(), arraysize(pic_param.reference_frames));
for (size_t i = 0; i < arraysize(pic_param.reference_frames); ++i) {
VASurfaceID va_surface_id;
if (ref_pictures[i]) {
scoped_refptr<VaapiDecodeSurface> surface =
VP9PictureToVaapiDecodeSurface(ref_pictures[i]);
va_surface_id = surface->va_surface()->id();
} else {
va_surface_id = VA_INVALID_SURFACE;
}
pic_param.reference_frames[i] = va_surface_id;
}
#define FHDR_TO_PP_PF1(a) pic_param.pic_fields.bits.a = frame_hdr->a
#define FHDR_TO_PP_PF2(a, b) pic_param.pic_fields.bits.a = b
FHDR_TO_PP_PF2(subsampling_x, frame_hdr->subsampling_x == 1);
FHDR_TO_PP_PF2(subsampling_y, frame_hdr->subsampling_y == 1);
FHDR_TO_PP_PF2(frame_type, frame_hdr->IsKeyframe() ? 0 : 1);
FHDR_TO_PP_PF1(show_frame);
FHDR_TO_PP_PF1(error_resilient_mode);
FHDR_TO_PP_PF1(intra_only);
FHDR_TO_PP_PF1(allow_high_precision_mv);
FHDR_TO_PP_PF2(mcomp_filter_type, frame_hdr->interpolation_filter);
FHDR_TO_PP_PF1(frame_parallel_decoding_mode);
FHDR_TO_PP_PF1(reset_frame_context);
FHDR_TO_PP_PF1(refresh_frame_context);
FHDR_TO_PP_PF2(frame_context_idx, frame_hdr->frame_context_idx_to_save_probs);
FHDR_TO_PP_PF2(segmentation_enabled, seg.enabled);
FHDR_TO_PP_PF2(segmentation_temporal_update, seg.temporal_update);
FHDR_TO_PP_PF2(segmentation_update_map, seg.update_map);
FHDR_TO_PP_PF2(last_ref_frame, frame_hdr->ref_frame_idx[0]);
FHDR_TO_PP_PF2(last_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_LAST]);
FHDR_TO_PP_PF2(golden_ref_frame, frame_hdr->ref_frame_idx[1]);
FHDR_TO_PP_PF2(golden_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_GOLDEN]);
FHDR_TO_PP_PF2(alt_ref_frame, frame_hdr->ref_frame_idx[2]);
FHDR_TO_PP_PF2(alt_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_ALTREF]);
FHDR_TO_PP_PF2(lossless_flag, frame_hdr->quant_params.IsLossless());
#undef FHDR_TO_PP_PF2
#undef FHDR_TO_PP_PF1
pic_param.filter_level = lf.level;
pic_param.sharpness_level = lf.sharpness;
pic_param.log2_tile_rows = frame_hdr->tile_rows_log2;
pic_param.log2_tile_columns = frame_hdr->tile_cols_log2;
pic_param.frame_header_length_in_bytes = frame_hdr->uncompressed_header_size;
pic_param.first_partition_size = frame_hdr->header_size_in_bytes;
ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, seg.tree_probs);
ARRAY_MEMCPY_CHECKED(pic_param.segment_pred_probs, seg.pred_probs);
pic_param.profile = frame_hdr->profile;
pic_param.bit_depth = frame_hdr->bit_depth;
DCHECK((pic_param.profile == 0 && pic_param.bit_depth == 8) ||
(pic_param.profile == 2 && pic_param.bit_depth == 10));
if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType,
sizeof(pic_param), &pic_param))
return false;
VASliceParameterBufferVP9 slice_param;
memset(&slice_param, 0, sizeof(slice_param));
slice_param.slice_data_size = frame_hdr->frame_size;
slice_param.slice_data_offset = 0;
slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
static_assert(arraysize(Vp9SegmentationParams::feature_enabled) ==
arraysize(slice_param.seg_param),
"seg_param array of incorrect size");
for (size_t i = 0; i < arraysize(slice_param.seg_param); ++i) {
VASegmentParameterVP9& seg_param = slice_param.seg_param[i];
#define SEG_TO_SP_SF(a, b) seg_param.segment_flags.fields.a = b
SEG_TO_SP_SF(
segment_reference_enabled,
seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME));
SEG_TO_SP_SF(segment_reference,
seg.FeatureData(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME));
SEG_TO_SP_SF(segment_reference_skipped,
seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_SKIP));
#undef SEG_TO_SP_SF
ARRAY_MEMCPY_CHECKED(seg_param.filter_level, lf.lvl[i]);
seg_param.luma_dc_quant_scale = seg.y_dequant[i][0];
seg_param.luma_ac_quant_scale = seg.y_dequant[i][1];
seg_param.chroma_dc_quant_scale = seg.uv_dequant[i][0];
seg_param.chroma_ac_quant_scale = seg.uv_dequant[i][1];
}
if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType,
sizeof(slice_param), &slice_param))
return false;
void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data);
if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType,
frame_hdr->frame_size, non_const_ptr))
return false;
scoped_refptr<VaapiDecodeSurface> dec_surface =
VP9PictureToVaapiDecodeSurface(pic);
return vaapi_dec_->DecodeSurface(dec_surface);
}
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372}
CWE ID: CWE-362 | bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode(
const scoped_refptr<VP9Picture>& pic,
const Vp9SegmentationParams& seg,
const Vp9LoopFilterParams& lf,
const std::vector<scoped_refptr<VP9Picture>>& ref_pictures,
const base::Closure& done_cb) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(done_cb.is_null());
VADecPictureParameterBufferVP9 pic_param;
memset(&pic_param, 0, sizeof(pic_param));
const Vp9FrameHeader* frame_hdr = pic->frame_hdr.get();
DCHECK(frame_hdr);
pic_param.frame_width = base::checked_cast<uint16_t>(frame_hdr->frame_width);
pic_param.frame_height =
base::checked_cast<uint16_t>(frame_hdr->frame_height);
CHECK_EQ(ref_pictures.size(), arraysize(pic_param.reference_frames));
for (size_t i = 0; i < arraysize(pic_param.reference_frames); ++i) {
VASurfaceID va_surface_id;
if (ref_pictures[i]) {
scoped_refptr<VaapiDecodeSurface> surface =
VP9PictureToVaapiDecodeSurface(ref_pictures[i]);
va_surface_id = surface->va_surface()->id();
} else {
va_surface_id = VA_INVALID_SURFACE;
}
pic_param.reference_frames[i] = va_surface_id;
}
#define FHDR_TO_PP_PF1(a) pic_param.pic_fields.bits.a = frame_hdr->a
#define FHDR_TO_PP_PF2(a, b) pic_param.pic_fields.bits.a = b
FHDR_TO_PP_PF2(subsampling_x, frame_hdr->subsampling_x == 1);
FHDR_TO_PP_PF2(subsampling_y, frame_hdr->subsampling_y == 1);
FHDR_TO_PP_PF2(frame_type, frame_hdr->IsKeyframe() ? 0 : 1);
FHDR_TO_PP_PF1(show_frame);
FHDR_TO_PP_PF1(error_resilient_mode);
FHDR_TO_PP_PF1(intra_only);
FHDR_TO_PP_PF1(allow_high_precision_mv);
FHDR_TO_PP_PF2(mcomp_filter_type, frame_hdr->interpolation_filter);
FHDR_TO_PP_PF1(frame_parallel_decoding_mode);
FHDR_TO_PP_PF1(reset_frame_context);
FHDR_TO_PP_PF1(refresh_frame_context);
FHDR_TO_PP_PF2(frame_context_idx, frame_hdr->frame_context_idx_to_save_probs);
FHDR_TO_PP_PF2(segmentation_enabled, seg.enabled);
FHDR_TO_PP_PF2(segmentation_temporal_update, seg.temporal_update);
FHDR_TO_PP_PF2(segmentation_update_map, seg.update_map);
FHDR_TO_PP_PF2(last_ref_frame, frame_hdr->ref_frame_idx[0]);
FHDR_TO_PP_PF2(last_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_LAST]);
FHDR_TO_PP_PF2(golden_ref_frame, frame_hdr->ref_frame_idx[1]);
FHDR_TO_PP_PF2(golden_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_GOLDEN]);
FHDR_TO_PP_PF2(alt_ref_frame, frame_hdr->ref_frame_idx[2]);
FHDR_TO_PP_PF2(alt_ref_frame_sign_bias,
frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_ALTREF]);
FHDR_TO_PP_PF2(lossless_flag, frame_hdr->quant_params.IsLossless());
#undef FHDR_TO_PP_PF2
#undef FHDR_TO_PP_PF1
pic_param.filter_level = lf.level;
pic_param.sharpness_level = lf.sharpness;
pic_param.log2_tile_rows = frame_hdr->tile_rows_log2;
pic_param.log2_tile_columns = frame_hdr->tile_cols_log2;
pic_param.frame_header_length_in_bytes = frame_hdr->uncompressed_header_size;
pic_param.first_partition_size = frame_hdr->header_size_in_bytes;
ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, seg.tree_probs);
ARRAY_MEMCPY_CHECKED(pic_param.segment_pred_probs, seg.pred_probs);
pic_param.profile = frame_hdr->profile;
pic_param.bit_depth = frame_hdr->bit_depth;
DCHECK((pic_param.profile == 0 && pic_param.bit_depth == 8) ||
(pic_param.profile == 2 && pic_param.bit_depth == 10));
if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType,
sizeof(pic_param), &pic_param))
return false;
VASliceParameterBufferVP9 slice_param;
memset(&slice_param, 0, sizeof(slice_param));
slice_param.slice_data_size = frame_hdr->frame_size;
slice_param.slice_data_offset = 0;
slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
static_assert(arraysize(Vp9SegmentationParams::feature_enabled) ==
arraysize(slice_param.seg_param),
"seg_param array of incorrect size");
for (size_t i = 0; i < arraysize(slice_param.seg_param); ++i) {
VASegmentParameterVP9& seg_param = slice_param.seg_param[i];
#define SEG_TO_SP_SF(a, b) seg_param.segment_flags.fields.a = b
SEG_TO_SP_SF(
segment_reference_enabled,
seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME));
SEG_TO_SP_SF(segment_reference,
seg.FeatureData(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME));
SEG_TO_SP_SF(segment_reference_skipped,
seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_SKIP));
#undef SEG_TO_SP_SF
ARRAY_MEMCPY_CHECKED(seg_param.filter_level, lf.lvl[i]);
seg_param.luma_dc_quant_scale = seg.y_dequant[i][0];
seg_param.luma_ac_quant_scale = seg.y_dequant[i][1];
seg_param.chroma_dc_quant_scale = seg.uv_dequant[i][0];
seg_param.chroma_ac_quant_scale = seg.uv_dequant[i][1];
}
if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType,
sizeof(slice_param), &slice_param))
return false;
void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data);
if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType,
frame_hdr->frame_size, non_const_ptr))
return false;
scoped_refptr<VaapiDecodeSurface> dec_surface =
VP9PictureToVaapiDecodeSurface(pic);
return vaapi_dec_->DecodeSurface(dec_surface);
}
| 172,810 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release());
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID: | void DocumentLoader::DidInstallNewDocument(Document* document) {
void DocumentLoader::DidInstallNewDocument(
Document* document,
const ContentSecurityPolicy* previous_csp) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release(),
nullptr, previous_csp);
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
| 172,617 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len)
{
jas_stream_t *in;
jas_iccprof_t *prof;
if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
goto error;
if (!(prof = jas_iccprof_load(in)))
goto error;
jas_stream_close(in);
return prof;
error:
if (in)
jas_stream_close(in);
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len)
jas_iccprof_t *jas_iccprof_createfrombuf(jas_uchar *buf, int len)
{
jas_stream_t *in;
jas_iccprof_t *prof;
if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
goto error;
if (!(prof = jas_iccprof_load(in)))
goto error;
jas_stream_close(in);
return prof;
error:
if (in)
jas_stream_close(in);
return 0;
}
| 168,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-189 | void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
| 164,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 recv_files(int f_in, int f_out, char *local_name)
{
int fd1,fd2;
STRUCT_STAT st;
int iflags, xlen;
char *fname, fbuf[MAXPATHLEN];
char xname[MAXPATHLEN];
char fnametmp[MAXPATHLEN];
char *fnamecmp, *partialptr;
char fnamecmpbuf[MAXPATHLEN];
uchar fnamecmp_type;
struct file_struct *file;
int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
enum logcode log_code = log_before_transfer ? FLOG : FINFO;
int max_phase = protocol_version >= 29 ? 2 : 1;
int dflt_perms = (ACCESSPERMS & ~orig_umask);
#ifdef SUPPORT_ACLS
const char *parent_dirname = "";
#endif
int ndx, recv_ok;
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
if (delay_updates)
delayed_bits = bitbag_create(cur_flist->used + 1);
while (1) {
cleanup_disable();
/* This call also sets cur_flist. */
ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type,
xname, &xlen);
if (ndx == NDX_DONE) {
if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {
set_current_file_index(NULL, 0);
end_progress(0);
}
if (inc_recurse && first_flist) {
if (read_batch) {
ndx = first_flist->used + first_flist->ndx_start;
gen_wants_ndx(ndx, first_flist->flist_num);
}
flist_free(first_flist);
if (first_flist)
continue;
} else if (read_batch && first_flist) {
ndx = first_flist->used;
gen_wants_ndx(ndx, first_flist->flist_num);
}
if (++phase > max_phase)
break;
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files phase=%d\n", phase);
if (phase == 2 && delay_updates)
handle_delayed_updates(local_name);
write_int(f_out, NDX_DONE);
continue;
}
if (ndx - cur_flist->ndx_start >= 0)
file = cur_flist->files[ndx - cur_flist->ndx_start];
else
file = dir_flist->files[cur_flist->parent_ndx];
fname = local_name ? local_name : f_name(file, fbuf);
if (daemon_filter_list.head
&& check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {
rprintf(FERROR, "attempt to hack rsync failed.\n");
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files(%s)\n", fname);
#ifdef SUPPORT_XATTRS
if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
&& !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)))
recv_xattr_request(file, f_in);
#endif
if (!(iflags & ITEM_TRANSFER)) {
maybe_log_item(file, iflags, itemizing, xname);
#ifdef SUPPORT_XATTRS
if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
&& !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
set_file_attrs(fname, file, NULL, fname, 0);
#endif
if (iflags & ITEM_IS_NEW) {
stats.created_files++;
if (S_ISREG(file->mode)) {
/* Nothing further to count. */
} else if (S_ISDIR(file->mode))
stats.created_dirs++;
#ifdef SUPPORT_LINKS
else if (S_ISLNK(file->mode))
stats.created_symlinks++;
#endif
else if (IS_DEVICE(file->mode))
stats.created_devices++;
else
stats.created_specials++;
}
continue;
}
if (phase == 2) {
rprintf(FERROR,
"got transfer request in phase 2 [%s]\n",
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (file->flags & FLAG_FILE_SENT) {
if (csum_length == SHORT_SUM_LENGTH) {
if (keep_partial && !partial_dir)
make_backups = -make_backups; /* prevents double backup */
if (append_mode)
sparse_files = -sparse_files;
append_mode = -append_mode;
csum_length = SUM_LENGTH;
redoing = 1;
}
} else {
if (csum_length != SHORT_SUM_LENGTH) {
if (keep_partial && !partial_dir)
make_backups = -make_backups;
if (append_mode)
sparse_files = -sparse_files;
append_mode = -append_mode;
csum_length = SHORT_SUM_LENGTH;
redoing = 0;
}
if (iflags & ITEM_IS_NEW)
stats.created_files++;
}
if (!am_server && INFO_GTE(PROGRESS, 1))
set_current_file_index(file, ndx);
stats.xferred_files++;
stats.total_transferred_size += F_LENGTH(file);
cleanup_got_literal = 0;
if (read_batch) {
int wanted = redoing
? we_want_redo(ndx)
: gen_wants_ndx(ndx, cur_flist->flist_num);
if (!wanted) {
rprintf(FINFO,
"(Skipping batched update for%s \"%s\")\n",
redoing ? " resend of" : "",
fname);
discard_receive_data(f_in, F_LENGTH(file));
file->flags |= FLAG_FILE_SENT;
continue;
}
}
remember_initial_stats();
if (!do_xfers) { /* log the transfer */
log_item(FCLIENT, file, iflags, NULL);
if (read_batch)
discard_receive_data(f_in, F_LENGTH(file));
continue;
}
if (write_batch < 0) {
log_item(FCLIENT, file, iflags, NULL);
if (!am_server)
discard_receive_data(f_in, F_LENGTH(file));
if (inc_recurse)
send_msg_int(MSG_SUCCESS, ndx);
continue;
}
partialptr = partial_dir ? partial_dir_fname(fname) : fname;
if (protocol_version >= 29) {
switch (fnamecmp_type) {
case FNAMECMP_FNAME:
fnamecmp = fname;
break;
case FNAMECMP_PARTIAL_DIR:
fnamecmp = partialptr;
break;
case FNAMECMP_BACKUP:
fnamecmp = get_backup_name(fname);
break;
case FNAMECMP_FUZZY:
if (file->dirname) {
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname);
fnamecmp = fnamecmpbuf;
} else
fnamecmp = xname;
break;
default:
if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) {
fnamecmp_type -= FNAMECMP_FUZZY + 1;
if (file->dirname) {
stringjoin(fnamecmpbuf, sizeof fnamecmpbuf,
basis_dir[fnamecmp_type], "/", file->dirname, "/", xname, NULL);
} else
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname);
} else if (fnamecmp_type >= basis_dir_cnt) {
rprintf(FERROR,
"invalid basis_dir index: %d.\n",
fnamecmp_type);
exit_cleanup(RERR_PROTOCOL);
} else
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname);
fnamecmp = fnamecmpbuf;
break;
}
if (!fnamecmp || (daemon_filter_list.head
&& check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) {
fnamecmp = fname;
fnamecmp_type = FNAMECMP_FNAME;
}
} else {
/* Reminder: --inplace && --partial-dir are never
* enabled at the same time. */
if (inplace && make_backups > 0) {
if (!(fnamecmp = get_backup_name(fname)))
fnamecmp = fname;
else
fnamecmp_type = FNAMECMP_BACKUP;
} else if (partial_dir && partialptr)
fnamecmp = partialptr;
else
fnamecmp = fname;
}
/* open the file */
fd1 = do_open(fnamecmp, O_RDONLY, 0);
if (fd1 == -1 && protocol_version < 29) {
if (fnamecmp != fname) {
fnamecmp = fname;
fd1 = do_open(fnamecmp, O_RDONLY, 0);
}
if (fd1 == -1 && basis_dir[0]) {
/* pre-29 allowed only one alternate basis */
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
basis_dir[0], fname);
fnamecmp = fnamecmpbuf;
fd1 = do_open(fnamecmp, O_RDONLY, 0);
}
}
updating_basis_or_equiv = inplace
&& (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);
if (fd1 == -1) {
st.st_mode = 0;
st.st_size = 0;
} else if (do_fstat(fd1,&st) != 0) {
rsyserr(FERROR_XFER, errno, "fstat %s failed",
full_fname(fnamecmp));
discard_receive_data(f_in, F_LENGTH(file));
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
/* this special handling for directories
* wouldn't be necessary if robust_rename()
* and the underlying robust_unlink could cope
* with directories
*/
rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
full_fname(fnamecmp));
discard_receive_data(f_in, F_LENGTH(file));
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
if (fd1 != -1 && !S_ISREG(st.st_mode)) {
close(fd1);
fd1 = -1;
}
/* If we're not preserving permissions, change the file-list's
* mode based on the local permissions and some heuristics. */
if (!preserve_perms) {
int exists = fd1 != -1;
#ifdef SUPPORT_ACLS
const char *dn = file->dirname ? file->dirname : ".";
if (parent_dirname != dn
&& strcmp(parent_dirname, dn) != 0) {
dflt_perms = default_perms_for_dir(dn);
parent_dirname = dn;
}
#endif
file->mode = dest_mode(file->mode, st.st_mode,
dflt_perms, exists);
}
/* We now check to see if we are writing the file "inplace" */
if (inplace) {
fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
if (fd2 == -1) {
rsyserr(FERROR_XFER, errno, "open %s failed",
full_fname(fname));
} else if (updating_basis_or_equiv)
cleanup_set(NULL, NULL, file, fd1, fd2);
} else {
fd2 = open_tmpfile(fnametmp, fname, file);
if (fd2 != -1)
cleanup_set(fnametmp, partialptr, file, fd1, fd2);
}
if (fd2 == -1) {
discard_receive_data(f_in, F_LENGTH(file));
if (fd1 != -1)
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
/* log the transfer */
if (log_before_transfer)
log_item(FCLIENT, file, iflags, NULL);
else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
rprintf(FINFO, "%s\n", fname);
/* recv file data */
recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
fname, fd2, F_LENGTH(file));
log_item(log_code, file, iflags, NULL);
if (fd1 != -1)
close(fd1);
if (close(fd2) < 0) {
rsyserr(FERROR, errno, "close failed on %s",
full_fname(fnametmp));
exit_cleanup(RERR_FILEIO);
}
if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
if (partialptr == fname)
partialptr = NULL;
if (!finish_transfer(fname, fnametmp, fnamecmp,
partialptr, file, recv_ok, 1))
recv_ok = -1;
else if (fnamecmp == partialptr) {
do_unlink(partialptr);
handle_partial_dir(partialptr, PDIR_DELETE);
}
} else if (keep_partial && partialptr) {
if (!handle_partial_dir(partialptr, PDIR_CREATE)) {
rprintf(FERROR,
"Unable to create partial-dir for %s -- discarding %s.\n",
local_name ? local_name : f_name(file, NULL),
recv_ok ? "completed file" : "partial file");
do_unlink(fnametmp);
recv_ok = -1;
} else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
file, recv_ok, !partial_dir))
recv_ok = -1;
else if (delay_updates && recv_ok) {
bitbag_set_bit(delayed_bits, ndx);
recv_ok = 2;
} else
partialptr = NULL;
} else
do_unlink(fnametmp);
cleanup_disable();
if (read_batch)
file->flags |= FLAG_FILE_SENT;
switch (recv_ok) {
case 2:
break;
case 1:
if (remove_source_files || inc_recurse
|| (preserve_hard_links && F_IS_HLINKED(file)))
send_msg_int(MSG_SUCCESS, ndx);
break;
case 0: {
enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {
char *errstr, *redostr, *keptstr;
if (!(keep_partial && partialptr) && !inplace)
keptstr = "discarded";
else if (partial_dir)
keptstr = "put into partial-dir";
else
keptstr = "retained";
if (msgtype == FERROR_XFER) {
errstr = "ERROR";
redostr = "";
} else {
errstr = "WARNING";
redostr = read_batch ? " (may try again)"
: " (will try again)";
}
rprintf(msgtype,
"%s: %s failed verification -- update %s%s.\n",
errstr, local_name ? f_name(file, NULL) : fname,
keptstr, redostr);
}
if (!redoing) {
if (read_batch)
flist_ndx_push(&batch_redo_list, ndx);
send_msg_int(MSG_REDO, ndx);
file->flags |= FLAG_FILE_SENT;
} else if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
break;
}
case -1:
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
break;
}
}
if (make_backups < 0)
make_backups = -make_backups;
if (phase == 2 && delay_updates) /* for protocol_version < 29 */
handle_delayed_updates(local_name);
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO,"recv_files finished\n");
return 0;
}
Commit Message:
CWE ID: | int recv_files(int f_in, int f_out, char *local_name)
{
int fd1,fd2;
STRUCT_STAT st;
int iflags, xlen;
char *fname, fbuf[MAXPATHLEN];
char xname[MAXPATHLEN];
char fnametmp[MAXPATHLEN];
char *fnamecmp, *partialptr;
char fnamecmpbuf[MAXPATHLEN];
uchar fnamecmp_type;
struct file_struct *file;
int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
enum logcode log_code = log_before_transfer ? FLOG : FINFO;
int max_phase = protocol_version >= 29 ? 2 : 1;
int dflt_perms = (ACCESSPERMS & ~orig_umask);
#ifdef SUPPORT_ACLS
const char *parent_dirname = "";
#endif
int ndx, recv_ok;
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
if (delay_updates)
delayed_bits = bitbag_create(cur_flist->used + 1);
while (1) {
cleanup_disable();
/* This call also sets cur_flist. */
ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type,
xname, &xlen);
if (ndx == NDX_DONE) {
if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {
set_current_file_index(NULL, 0);
end_progress(0);
}
if (inc_recurse && first_flist) {
if (read_batch) {
ndx = first_flist->used + first_flist->ndx_start;
gen_wants_ndx(ndx, first_flist->flist_num);
}
flist_free(first_flist);
if (first_flist)
continue;
} else if (read_batch && first_flist) {
ndx = first_flist->used;
gen_wants_ndx(ndx, first_flist->flist_num);
}
if (++phase > max_phase)
break;
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files phase=%d\n", phase);
if (phase == 2 && delay_updates)
handle_delayed_updates(local_name);
write_int(f_out, NDX_DONE);
continue;
}
if (ndx - cur_flist->ndx_start >= 0)
file = cur_flist->files[ndx - cur_flist->ndx_start];
else
file = dir_flist->files[cur_flist->parent_ndx];
fname = local_name ? local_name : f_name(file, fbuf);
if (daemon_filter_list.head
&& check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {
rprintf(FERROR, "attempt to hack rsync failed.\n");
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO, "recv_files(%s)\n", fname);
#ifdef SUPPORT_XATTRS
if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
&& !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)))
recv_xattr_request(file, f_in);
#endif
if (!(iflags & ITEM_TRANSFER)) {
maybe_log_item(file, iflags, itemizing, xname);
#ifdef SUPPORT_XATTRS
if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
&& !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
set_file_attrs(fname, file, NULL, fname, 0);
#endif
if (iflags & ITEM_IS_NEW) {
stats.created_files++;
if (S_ISREG(file->mode)) {
/* Nothing further to count. */
} else if (S_ISDIR(file->mode))
stats.created_dirs++;
#ifdef SUPPORT_LINKS
else if (S_ISLNK(file->mode))
stats.created_symlinks++;
#endif
else if (IS_DEVICE(file->mode))
stats.created_devices++;
else
stats.created_specials++;
}
continue;
}
if (phase == 2) {
rprintf(FERROR,
"got transfer request in phase 2 [%s]\n",
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (file->flags & FLAG_FILE_SENT) {
if (csum_length == SHORT_SUM_LENGTH) {
if (keep_partial && !partial_dir)
make_backups = -make_backups; /* prevents double backup */
if (append_mode)
sparse_files = -sparse_files;
append_mode = -append_mode;
csum_length = SUM_LENGTH;
redoing = 1;
}
} else {
if (csum_length != SHORT_SUM_LENGTH) {
if (keep_partial && !partial_dir)
make_backups = -make_backups;
if (append_mode)
sparse_files = -sparse_files;
append_mode = -append_mode;
csum_length = SHORT_SUM_LENGTH;
redoing = 0;
}
if (iflags & ITEM_IS_NEW)
stats.created_files++;
}
if (!am_server && INFO_GTE(PROGRESS, 1))
set_current_file_index(file, ndx);
stats.xferred_files++;
stats.total_transferred_size += F_LENGTH(file);
cleanup_got_literal = 0;
if (read_batch) {
int wanted = redoing
? we_want_redo(ndx)
: gen_wants_ndx(ndx, cur_flist->flist_num);
if (!wanted) {
rprintf(FINFO,
"(Skipping batched update for%s \"%s\")\n",
redoing ? " resend of" : "",
fname);
discard_receive_data(f_in, F_LENGTH(file));
file->flags |= FLAG_FILE_SENT;
continue;
}
}
remember_initial_stats();
if (!do_xfers) { /* log the transfer */
log_item(FCLIENT, file, iflags, NULL);
if (read_batch)
discard_receive_data(f_in, F_LENGTH(file));
continue;
}
if (write_batch < 0) {
log_item(FCLIENT, file, iflags, NULL);
if (!am_server)
discard_receive_data(f_in, F_LENGTH(file));
if (inc_recurse)
send_msg_int(MSG_SUCCESS, ndx);
continue;
}
partialptr = partial_dir ? partial_dir_fname(fname) : fname;
if (protocol_version >= 29) {
switch (fnamecmp_type) {
case FNAMECMP_FNAME:
fnamecmp = fname;
break;
case FNAMECMP_PARTIAL_DIR:
fnamecmp = partialptr;
break;
case FNAMECMP_BACKUP:
fnamecmp = get_backup_name(fname);
break;
case FNAMECMP_FUZZY:
if (file->dirname) {
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname);
fnamecmp = fnamecmpbuf;
} else
fnamecmp = xname;
break;
default:
if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) {
fnamecmp_type -= FNAMECMP_FUZZY + 1;
if (file->dirname) {
stringjoin(fnamecmpbuf, sizeof fnamecmpbuf,
basis_dir[fnamecmp_type], "/", file->dirname, "/", xname, NULL);
} else
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname);
} else if (fnamecmp_type >= basis_dir_cnt) {
rprintf(FERROR,
"invalid basis_dir index: %d.\n",
fnamecmp_type);
exit_cleanup(RERR_PROTOCOL);
} else
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname);
fnamecmp = fnamecmpbuf;
break;
}
if (!fnamecmp || (daemon_filter_list.head
&& check_filter(&daemon_filter_list, FLOG, fnamecmp, 0) < 0)) {
fnamecmp = fname;
fnamecmp_type = FNAMECMP_FNAME;
}
} else {
/* Reminder: --inplace && --partial-dir are never
* enabled at the same time. */
if (inplace && make_backups > 0) {
if (!(fnamecmp = get_backup_name(fname)))
fnamecmp = fname;
else
fnamecmp_type = FNAMECMP_BACKUP;
} else if (partial_dir && partialptr)
fnamecmp = partialptr;
else
fnamecmp = fname;
}
/* open the file */
fd1 = do_open(fnamecmp, O_RDONLY, 0);
if (fd1 == -1 && protocol_version < 29) {
if (fnamecmp != fname) {
fnamecmp = fname;
fd1 = do_open(fnamecmp, O_RDONLY, 0);
}
if (fd1 == -1 && basis_dir[0]) {
/* pre-29 allowed only one alternate basis */
pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
basis_dir[0], fname);
fnamecmp = fnamecmpbuf;
fd1 = do_open(fnamecmp, O_RDONLY, 0);
}
}
updating_basis_or_equiv = inplace
&& (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);
if (fd1 == -1) {
st.st_mode = 0;
st.st_size = 0;
} else if (do_fstat(fd1,&st) != 0) {
rsyserr(FERROR_XFER, errno, "fstat %s failed",
full_fname(fnamecmp));
discard_receive_data(f_in, F_LENGTH(file));
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
/* this special handling for directories
* wouldn't be necessary if robust_rename()
* and the underlying robust_unlink could cope
* with directories
*/
rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
full_fname(fnamecmp));
discard_receive_data(f_in, F_LENGTH(file));
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
if (fd1 != -1 && !S_ISREG(st.st_mode)) {
close(fd1);
fd1 = -1;
}
/* If we're not preserving permissions, change the file-list's
* mode based on the local permissions and some heuristics. */
if (!preserve_perms) {
int exists = fd1 != -1;
#ifdef SUPPORT_ACLS
const char *dn = file->dirname ? file->dirname : ".";
if (parent_dirname != dn
&& strcmp(parent_dirname, dn) != 0) {
dflt_perms = default_perms_for_dir(dn);
parent_dirname = dn;
}
#endif
file->mode = dest_mode(file->mode, st.st_mode,
dflt_perms, exists);
}
/* We now check to see if we are writing the file "inplace" */
if (inplace) {
fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
if (fd2 == -1) {
rsyserr(FERROR_XFER, errno, "open %s failed",
full_fname(fname));
} else if (updating_basis_or_equiv)
cleanup_set(NULL, NULL, file, fd1, fd2);
} else {
fd2 = open_tmpfile(fnametmp, fname, file);
if (fd2 != -1)
cleanup_set(fnametmp, partialptr, file, fd1, fd2);
}
if (fd2 == -1) {
discard_receive_data(f_in, F_LENGTH(file));
if (fd1 != -1)
close(fd1);
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
continue;
}
/* log the transfer */
if (log_before_transfer)
log_item(FCLIENT, file, iflags, NULL);
else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
rprintf(FINFO, "%s\n", fname);
/* recv file data */
recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
fname, fd2, F_LENGTH(file));
log_item(log_code, file, iflags, NULL);
if (fd1 != -1)
close(fd1);
if (close(fd2) < 0) {
rsyserr(FERROR, errno, "close failed on %s",
full_fname(fnametmp));
exit_cleanup(RERR_FILEIO);
}
if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
if (partialptr == fname)
partialptr = NULL;
if (!finish_transfer(fname, fnametmp, fnamecmp,
partialptr, file, recv_ok, 1))
recv_ok = -1;
else if (fnamecmp == partialptr) {
do_unlink(partialptr);
handle_partial_dir(partialptr, PDIR_DELETE);
}
} else if (keep_partial && partialptr) {
if (!handle_partial_dir(partialptr, PDIR_CREATE)) {
rprintf(FERROR,
"Unable to create partial-dir for %s -- discarding %s.\n",
local_name ? local_name : f_name(file, NULL),
recv_ok ? "completed file" : "partial file");
do_unlink(fnametmp);
recv_ok = -1;
} else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
file, recv_ok, !partial_dir))
recv_ok = -1;
else if (delay_updates && recv_ok) {
bitbag_set_bit(delayed_bits, ndx);
recv_ok = 2;
} else
partialptr = NULL;
} else
do_unlink(fnametmp);
cleanup_disable();
if (read_batch)
file->flags |= FLAG_FILE_SENT;
switch (recv_ok) {
case 2:
break;
case 1:
if (remove_source_files || inc_recurse
|| (preserve_hard_links && F_IS_HLINKED(file)))
send_msg_int(MSG_SUCCESS, ndx);
break;
case 0: {
enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {
char *errstr, *redostr, *keptstr;
if (!(keep_partial && partialptr) && !inplace)
keptstr = "discarded";
else if (partial_dir)
keptstr = "put into partial-dir";
else
keptstr = "retained";
if (msgtype == FERROR_XFER) {
errstr = "ERROR";
redostr = "";
} else {
errstr = "WARNING";
redostr = read_batch ? " (may try again)"
: " (will try again)";
}
rprintf(msgtype,
"%s: %s failed verification -- update %s%s.\n",
errstr, local_name ? f_name(file, NULL) : fname,
keptstr, redostr);
}
if (!redoing) {
if (read_batch)
flist_ndx_push(&batch_redo_list, ndx);
send_msg_int(MSG_REDO, ndx);
file->flags |= FLAG_FILE_SENT;
} else if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
break;
}
case -1:
if (inc_recurse)
send_msg_int(MSG_NO_SEND, ndx);
break;
}
}
if (make_backups < 0)
make_backups = -make_backups;
if (phase == 2 && delay_updates) /* for protocol_version < 29 */
handle_delayed_updates(local_name);
if (DEBUG_GTE(RECV, 1))
rprintf(FINFO,"recv_files finished\n");
return 0;
}
| 164,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
struct cifs_tcon *tcon, const struct nls_table *cp)
{
struct smb2_tree_connect_req *req;
struct smb2_tree_connect_rsp *rsp = NULL;
struct kvec iov[2];
int rc = 0;
int resp_buftype;
int unc_path_len;
struct TCP_Server_Info *server;
__le16 *unc_path = NULL;
cifs_dbg(FYI, "TCON\n");
if ((ses->server) && tree)
server = ses->server;
else
return -EIO;
if (tcon && tcon->bad_network_name)
return -ENOENT;
unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
if (unc_path == NULL)
return -ENOMEM;
unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
unc_path_len *= 2;
if (unc_path_len < 2) {
kfree(unc_path);
return -EINVAL;
}
rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
if (rc) {
kfree(unc_path);
return rc;
}
if (tcon == NULL) {
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.SessionId = ses->Suid;
/* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
req->PathLength = cpu_to_le16(unc_path_len - 2);
iov[1].iov_base = unc_path;
iov[1].iov_len = unc_path_len;
inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
if (rc != 0) {
if (tcon) {
cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
tcon->need_reconnect = true;
}
goto tcon_error_exit;
}
if (tcon == NULL) {
ses->ipc_tid = rsp->hdr.TreeId;
goto tcon_exit;
}
if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
cifs_dbg(FYI, "connection to disk share\n");
else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
tcon->ipc = true;
cifs_dbg(FYI, "connection to pipe share\n");
} else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
tcon->print = true;
cifs_dbg(FYI, "connection to printer\n");
} else {
cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
rc = -EOPNOTSUPP;
goto tcon_error_exit;
}
tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = rsp->hdr.TreeId;
strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
init_copy_chunk_defaults(tcon);
if (tcon->ses->server->ops->validate_negotiate)
rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
tcon_exit:
free_rsp_buf(resp_buftype, rsp);
kfree(unc_path);
return rc;
tcon_error_exit:
if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
tcon->bad_network_name = true;
}
goto tcon_exit;
}
Commit Message: [CIFS] Possible null ptr deref in SMB2_tcon
As Raphael Geissert pointed out, tcon_error_exit can dereference tcon
and there is one path in which tcon can be null.
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]> # v3.7+
Reported-by: Raphael Geissert <[email protected]>
CWE ID: CWE-399 | SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
struct cifs_tcon *tcon, const struct nls_table *cp)
{
struct smb2_tree_connect_req *req;
struct smb2_tree_connect_rsp *rsp = NULL;
struct kvec iov[2];
int rc = 0;
int resp_buftype;
int unc_path_len;
struct TCP_Server_Info *server;
__le16 *unc_path = NULL;
cifs_dbg(FYI, "TCON\n");
if ((ses->server) && tree)
server = ses->server;
else
return -EIO;
if (tcon && tcon->bad_network_name)
return -ENOENT;
unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
if (unc_path == NULL)
return -ENOMEM;
unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
unc_path_len *= 2;
if (unc_path_len < 2) {
kfree(unc_path);
return -EINVAL;
}
rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
if (rc) {
kfree(unc_path);
return rc;
}
if (tcon == NULL) {
/* since no tcon, smb2_init can not do this, so do here */
req->hdr.SessionId = ses->Suid;
/* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED)
req->hdr.Flags |= SMB2_FLAGS_SIGNED; */
}
iov[0].iov_base = (char *)req;
/* 4 for rfc1002 length field and 1 for pad */
iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
/* Testing shows that buffer offset must be at location of Buffer[0] */
req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
req->PathLength = cpu_to_le16(unc_path_len - 2);
iov[1].iov_base = unc_path;
iov[1].iov_len = unc_path_len;
inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0);
rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base;
if (rc != 0) {
if (tcon) {
cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
tcon->need_reconnect = true;
}
goto tcon_error_exit;
}
if (tcon == NULL) {
ses->ipc_tid = rsp->hdr.TreeId;
goto tcon_exit;
}
if (rsp->ShareType & SMB2_SHARE_TYPE_DISK)
cifs_dbg(FYI, "connection to disk share\n");
else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) {
tcon->ipc = true;
cifs_dbg(FYI, "connection to pipe share\n");
} else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) {
tcon->print = true;
cifs_dbg(FYI, "connection to printer\n");
} else {
cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
rc = -EOPNOTSUPP;
goto tcon_error_exit;
}
tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
tcon->tidStatus = CifsGood;
tcon->need_reconnect = false;
tcon->tid = rsp->hdr.TreeId;
strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
init_copy_chunk_defaults(tcon);
if (tcon->ses->server->ops->validate_negotiate)
rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
tcon_exit:
free_rsp_buf(resp_buftype, rsp);
kfree(unc_path);
return rc;
tcon_error_exit:
if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) {
cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
if (tcon)
tcon->bad_network_name = true;
}
goto tcon_exit;
}
| 166,261 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: zstatus(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
switch (r_type(op)) {
case t_file:
{
stream *s;
make_bool(op, (file_is_valid(s, op) ? 1 : 0));
}
return 0;
case t_string:
{
gs_parsed_file_name_t pname;
struct stat fstat;
int code = parse_file_name(op, &pname,
i_ctx_p->LockFilePermissions, imemory);
if (code < 0) {
if (code == gs_error_undefinedfilename) {
make_bool(op, 0);
code = 0;
}
return code;
}
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = (*pname.iodev->procs.file_status)(pname.iodev,
pname.fname, &fstat);
switch (code) {
case 0:
check_ostack(4);
make_int(op - 4, stat_blocks(&fstat));
make_int(op - 3, fstat.st_size);
/*
* We can't check the value simply by using ==,
* because signed/unsigned == does the wrong thing.
* Instead, since integer assignment only keeps the
* bottom bits, we convert the values to double
* and then test for equality. This handles all
* cases of signed/unsigned or width mismatch.
*/
if ((double)op[-4].value.intval !=
(double)stat_blocks(&fstat) ||
(double)op[-3].value.intval !=
(double)fstat.st_size
)
return_error(gs_error_limitcheck);
make_int(op - 2, fstat.st_mtime);
make_int(op - 1, fstat.st_ctime);
make_bool(op, 1);
break;
case gs_error_undefinedfilename:
make_bool(op, 0);
code = 0;
}
gs_free_file_name(&pname, "status");
return code;
}
default:
return_op_typecheck(op);
}
}
Commit Message:
CWE ID: CWE-200 | zstatus(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
switch (r_type(op)) {
case t_file:
{
stream *s;
make_bool(op, (file_is_valid(s, op) ? 1 : 0));
}
return 0;
case t_string:
{
gs_parsed_file_name_t pname;
struct stat fstat;
int code = parse_file_name(op, &pname,
i_ctx_p->LockFilePermissions, imemory);
if (code < 0) {
if (code == gs_error_undefinedfilename) {
make_bool(op, 0);
code = 0;
}
return code;
}
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
if ((code = check_file_permissions(i_ctx_p, pname.fname, pname.len,
"PermitFileReading")) >= 0) {
code = (*pname.iodev->procs.file_status)(pname.iodev,
pname.fname, &fstat);
}
switch (code) {
case 0:
check_ostack(4);
make_int(op - 4, stat_blocks(&fstat));
make_int(op - 3, fstat.st_size);
/*
* We can't check the value simply by using ==,
* because signed/unsigned == does the wrong thing.
* Instead, since integer assignment only keeps the
* bottom bits, we convert the values to double
* and then test for equality. This handles all
* cases of signed/unsigned or width mismatch.
*/
if ((double)op[-4].value.intval !=
(double)stat_blocks(&fstat) ||
(double)op[-3].value.intval !=
(double)fstat.st_size
)
return_error(gs_error_limitcheck);
make_int(op - 2, fstat.st_mtime);
make_int(op - 1, fstat.st_ctime);
make_bool(op, 1);
break;
case gs_error_undefinedfilename:
make_bool(op, 0);
code = 0;
}
gs_free_file_name(&pname, "status");
return code;
}
default:
return_op_typecheck(op);
}
}
| 164,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: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Disallow Arabic/Hebrew NSMs to come after an unrelated base char.
Arabic NSM(non-spacing mark)s and Hebrew NSMs are allowed to mix with
Latin with the current 'moderately restrictive script mixing policy'.
They're not blocked by BiDi check either because both LTR and RTL labels
can have an NSM.
Block them from coming after an unrelated script (e.g. Latin + Arabic
NSM).
Bug: chromium:729979
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: I5b93fbcf76d17121bf1baaa480ef3624424b3317
Reviewed-on: https://chromium-review.googlesource.com/528348
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#478205}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disallow Arabic non-spacing marks after non-Arabic characters.
// - Disallow Hebrew non-spacing marks after non-Hebrew characters.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,336 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv)
{
#ifdef sgi
char tmpline[80];
#endif
char *p, *bgstr = NULL;
int rc, alen, flen;
int error = 0;
int timing = FALSE;
int have_bg = FALSE;
#ifdef FEATURE_LOOP
int loop = FALSE;
long loop_interval = -1; /* seconds (100,000 max) */
#endif
double LUT_exponent; /* just the lookup table */
double CRT_exponent = 2.2; /* just the monitor */
double default_display_exponent; /* whole display system */
XEvent e;
KeySym k;
/* First initialize a few things, just to be sure--memset takes care of
* default background color (black), booleans (FALSE), pointers (NULL),
* etc. */
displayname = (char *)NULL;
filename = (char *)NULL;
memset(&rpng2_info, 0, sizeof(mainprog_info));
/* Set the default value for our display-system exponent, i.e., the
* product of the CRT exponent and the exponent corresponding to
* the frame-buffer's lookup table (LUT), if any. This is not an
* exhaustive list of LUT values (e.g., OpenStep has a lot of weird
* ones), but it should cover 99% of the current possibilities. */
#if defined(NeXT)
/* third-party utilities can modify the default LUT exponent */
LUT_exponent = 1.0 / 2.2;
/*
if (some_next_function_that_returns_gamma(&next_gamma))
LUT_exponent = 1.0 / next_gamma;
*/
#elif defined(sgi)
LUT_exponent = 1.0 / 1.7;
/* there doesn't seem to be any documented function to
* get the "gamma" value, so we do it the hard way */
infile = fopen("/etc/config/system.glGammaVal", "r");
if (infile) {
double sgi_gamma;
fgets(tmpline, 80, infile);
fclose(infile);
sgi_gamma = atof(tmpline);
if (sgi_gamma > 0.0)
LUT_exponent = 1.0 / sgi_gamma;
}
#elif defined(Macintosh)
LUT_exponent = 1.8 / 2.61;
/*
if (some_mac_function_that_returns_gamma(&mac_gamma))
LUT_exponent = mac_gamma / 2.61;
*/
#else
LUT_exponent = 1.0; /* assume no LUT: most PCs */
#endif
/* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
default_display_exponent = LUT_exponent * CRT_exponent;
/* If the user has set the SCREEN_GAMMA environment variable as suggested
* (somewhat imprecisely) in the libpng documentation, use that; otherwise
* use the default value we just calculated. Either way, the user may
* override this via a command-line option. */
if ((p = getenv("SCREEN_GAMMA")) != NULL)
rpng2_info.display_exponent = atof(p);
else
rpng2_info.display_exponent = default_display_exponent;
/* Now parse the command line for options and the PNG filename. */
while (*++argv && !error) {
if (!strncmp(*argv, "-display", 2)) {
if (!*++argv)
++error;
else
displayname = *argv;
} else if (!strncmp(*argv, "-gamma", 2)) {
if (!*++argv)
++error;
else {
rpng2_info.display_exponent = atof(*argv);
if (rpng2_info.display_exponent <= 0.0)
++error;
}
} else if (!strncmp(*argv, "-bgcolor", 4)) {
if (!*++argv)
++error;
else {
bgstr = *argv;
if (strlen(bgstr) != 7 || bgstr[0] != '#')
++error;
else {
have_bg = TRUE;
bg_image = FALSE;
}
}
} else if (!strncmp(*argv, "-bgpat", 4)) {
if (!*++argv)
++error;
else {
pat = atoi(*argv);
if (pat >= 0 && pat < num_bgpat) {
bg_image = TRUE;
have_bg = FALSE;
} else
++error;
}
} else if (!strncmp(*argv, "-usleep", 2)) {
if (!*++argv)
++error;
else {
usleep_duration = (ulg)atol(*argv);
demo_timing = TRUE;
}
} else if (!strncmp(*argv, "-pause", 2)) {
pause_after_pass = TRUE;
} else if (!strncmp(*argv, "-timing", 2)) {
timing = TRUE;
#ifdef FEATURE_LOOP
} else if (!strncmp(*argv, "-loop", 2)) {
loop = TRUE;
if (!argv[1] || !is_number(argv[1]))
loop_interval = 2;
else {
++argv;
loop_interval = atol(*argv);
if (loop_interval < 0)
loop_interval = 2;
else if (loop_interval > 100000) /* bit more than one day */
loop_interval = 100000;
}
#endif
} else {
if (**argv != '-') {
filename = *argv;
if (argv[1]) /* shouldn't be any more args after filename */
++error;
} else
++error; /* not expecting any other options */
}
}
if (!filename)
++error;
/* print usage screen if any errors up to this point */
if (error) {
fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname);
readpng2_version_info();
fprintf(stderr, "\n"
"Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n"
#ifdef FEATURE_LOOP
" %*s [-usleep dur | -timing] [-pause] [-loop [sec]] file.png\n\n"
#else
" %*s [-usleep dur | -timing] [-pause] file.png\n\n"
#endif
" xdpy\tname of the target X display (e.g., ``hostname:0'')\n"
" exp \ttransfer-function exponent (``gamma'') of the display\n"
"\t\t system in floating-point format (e.g., ``%.1f''); equal\n"
"\t\t to the product of the lookup-table exponent (varies)\n"
"\t\t and the CRT exponent (usually 2.2); must be positive\n"
" bg \tdesired background color in 7-character hex RGB format\n"
"\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n"
"\t\t used with transparent images; overrides -bgpat\n"
" pat \tdesired background pattern number (0-%d); used with\n"
"\t\t transparent images; overrides -bgcolor\n"
#ifdef FEATURE_LOOP
" -loop\tloops through background images after initial display\n"
"\t\t is complete (depends on -bgpat)\n"
" sec \tseconds to display each background image (default = 2)\n"
#endif
" dur \tduration in microseconds to wait after displaying each\n"
"\t\t row (for demo purposes)\n"
" -timing\tenables delay for every block read, to simulate modem\n"
"\t\t download of image (~36 Kbps)\n"
" -pause\tpauses after displaying each pass until mouse clicked\n"
"\nPress Q, Esc or mouse button 1 (within image window, after image\n"
"is displayed) to quit.\n"
"\n", PROGNAME,
(int)strlen(PROGNAME), " ", default_display_exponent, num_bgpat-1);
exit(1);
}
if (!(infile = fopen(filename, "rb"))) {
fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename);
++error;
} else {
incount = fread(inbuf, 1, INBUFSIZE, infile);
if (incount < 8 || !readpng2_check_sig(inbuf, 8)) {
fprintf(stderr, PROGNAME
": [%s] is not a PNG file: incorrect signature\n",
filename);
++error;
} else if ((rc = readpng2_init(&rpng2_info)) != 0) {
switch (rc) {
case 2:
fprintf(stderr, PROGNAME
": [%s] has bad IHDR (libpng longjmp)\n", filename);
break;
case 4:
fprintf(stderr, PROGNAME ": insufficient memory\n");
break;
default:
fprintf(stderr, PROGNAME
": unknown readpng2_init() error\n");
break;
}
++error;
} else {
Trace((stderr, "about to call XOpenDisplay()\n"))
display = XOpenDisplay(displayname);
if (!display) {
readpng2_cleanup(&rpng2_info);
fprintf(stderr, PROGNAME ": can't open X display [%s]\n",
displayname? displayname : "default");
++error;
}
}
if (error)
fclose(infile);
}
if (error) {
fprintf(stderr, PROGNAME ": aborting.\n");
exit(2);
}
/* set the title-bar string, but make sure buffer doesn't overflow */
alen = strlen(appname);
flen = strlen(filename);
if (alen + flen + 3 > 1023)
sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023));
else
sprintf(titlebar, "%s: %s", appname, filename);
/* set some final rpng2_info variables before entering main data loop */
if (have_bg) {
unsigned r, g, b; /* this approach quiets compiler warnings */
sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b);
rpng2_info.bg_red = (uch)r;
rpng2_info.bg_green = (uch)g;
rpng2_info.bg_blue = (uch)b;
} else
rpng2_info.need_bgcolor = TRUE;
rpng2_info.state = kPreInit;
rpng2_info.mainprog_init = rpng2_x_init;
rpng2_info.mainprog_display_row = rpng2_x_display_row;
rpng2_info.mainprog_finish_display = rpng2_x_finish_display;
/* OK, this is the fun part: call readpng2_decode_data() at the start of
* the loop to deal with our first buffer of data (read in above to verify
* that the file is a PNG image), then loop through the file and continue
* calling the same routine to handle each chunk of data. It in turn
* passes the data to libpng, which will invoke one or more of our call-
* backs as decoded data become available. We optionally call sleep() for
* one second per iteration to simulate downloading the image via an analog
* modem. */
for (;;) {
Trace((stderr, "about to call readpng2_decode_data()\n"))
if (readpng2_decode_data(&rpng2_info, inbuf, incount))
++error;
Trace((stderr, "done with readpng2_decode_data()\n"))
if (error || incount != INBUFSIZE || rpng2_info.state == kDone) {
if (rpng2_info.state == kDone) {
Trace((stderr, "done decoding PNG image\n"))
} else if (ferror(infile)) {
fprintf(stderr, PROGNAME
": error while reading PNG image file\n");
exit(3);
} else if (feof(infile)) {
fprintf(stderr, PROGNAME ": end of file reached "
"(unexpectedly) while reading PNG image file\n");
exit(3);
} else /* if (error) */ {
/* will print error message below */
}
break;
}
if (timing)
sleep(1);
incount = fread(inbuf, 1, INBUFSIZE, infile);
}
/* clean up PNG stuff and report any decoding errors */
fclose(infile);
Trace((stderr, "about to call readpng2_cleanup()\n"))
readpng2_cleanup(&rpng2_info);
if (error) {
fprintf(stderr, PROGNAME ": libpng error while decoding PNG image\n");
exit(3);
}
#ifdef FEATURE_LOOP
if (loop && bg_image) {
Trace((stderr, "entering -loop loop (FEATURE_LOOP)\n"))
for (;;) {
int i, use_sleep;
struct timeval now, then;
/* get current time and add loop_interval to get target time */
if (gettimeofday(&then, NULL) == 0) {
then.tv_sec += loop_interval;
use_sleep = FALSE;
} else
use_sleep = TRUE;
/* do quick check for a quit event but don't wait for it */
/* GRR BUG: should also check for Expose events and redraw... */
if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e))
if (QUIT(e,k))
break;
/* generate next background image */
if (++pat >= num_bgpat)
pat = 0;
rpng2_x_reload_bg_image();
/* wait for timeout, using whatever means are available */
if (use_sleep || gettimeofday(&now, NULL) != 0) {
for (i = loop_interval; i > 0; --i) {
sleep(1);
/* GRR BUG: also need to check for Expose (and redraw!) */
if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask,
&e) && QUIT(e,k))
break;
}
} else {
/* Y2038 BUG! */
if (now.tv_sec < then.tv_sec ||
(now.tv_sec == then.tv_sec && now.tv_usec < then.tv_usec))
{
int quit = FALSE;
long seconds_to_go = then.tv_sec - now.tv_sec;
long usleep_usec;
/* basically chew up most of remaining loop-interval with
* calls to sleep(1) interleaved with checks for quit
* events, but also recalc time-to-go periodically; when
* done, clean up any remaining time with usleep() call
* (could also use SIGALRM, but signals are a pain...) */
while (seconds_to_go-- > 1) {
int seconds_done = 0;
for (i = seconds_to_go; i > 0 && !quit; --i) {
sleep(1);
/* GRR BUG: need to check for Expose and redraw */
if (XCheckMaskEvent(display, KeyPressMask |
ButtonPressMask, &e) && QUIT(e,k))
quit = TRUE;
if (++seconds_done > 1000)
break; /* time to redo seconds_to_go meas. */
}
if (quit)
break;
/* OK, more than 1000 seconds since last check:
* correct the time-to-go measurement for drift */
if (gettimeofday(&now, NULL) == 0) {
if (now.tv_sec >= then.tv_sec)
break;
seconds_to_go = then.tv_sec - now.tv_sec;
} else
++seconds_to_go; /* restore what we subtracted */
}
if (quit)
break; /* breaks outer do-loop, skips redisplay */
/* since difference between "now" and "then" is already
* eaten up to within a couple of seconds, don't need to
* worry about overflow--but might have overshot (neg.) */
if (gettimeofday(&now, NULL) == 0) {
usleep_usec = 1000000L*(then.tv_sec - now.tv_sec) +
then.tv_usec - now.tv_usec;
if (usleep_usec > 0)
usleep((ulg)usleep_usec);
}
}
}
/* composite image against new background and display (note that
* we do not take into account the time spent doing this...) */
rpng2_x_redisplay_image (0, 0, rpng2_info.width, rpng2_info.height);
}
} else /* FALL THROUGH and do the normal thing */
#endif /* FEATURE_LOOP */
/* wait for the user to tell us when to quit */
if (rpng2_info.state >= kWindowInit) {
Trace((stderr, "entering final wait-for-quit-event loop\n"))
do {
XNextEvent(display, &e);
if (e.type == Expose) {
XExposeEvent *ex = (XExposeEvent *)&e;
rpng2_x_redisplay_image (ex->x, ex->y, ex->width, ex->height);
}
} while (!QUIT(e,k));
} else {
fprintf(stderr, PROGNAME ": init callback never called: probable "
"libpng error while decoding PNG metadata\n");
exit(4);
}
/* we're done: clean up all image and X resources and go away */
Trace((stderr, "about to call rpng2_x_cleanup()\n"))
rpng2_x_cleanup();
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 main(int argc, char **argv)
{
#ifdef sgi
char tmpline[80];
#endif
char *p, *bgstr = NULL;
int rc, alen, flen;
int error = 0;
int timing = FALSE;
int have_bg = FALSE;
#ifdef FEATURE_LOOP
int loop = FALSE;
long loop_interval = -1; /* seconds (100,000 max) */
#endif
double LUT_exponent; /* just the lookup table */
double CRT_exponent = 2.2; /* just the monitor */
double default_display_exponent; /* whole display system */
XEvent e;
KeySym k;
/* First initialize a few things, just to be sure--memset takes care of
* default background color (black), booleans (FALSE), pointers (NULL),
* etc. */
displayname = (char *)NULL;
filename = (char *)NULL;
memset(&rpng2_info, 0, sizeof(mainprog_info));
/* Set the default value for our display-system exponent, i.e., the
* product of the CRT exponent and the exponent corresponding to
* the frame-buffer's lookup table (LUT), if any. This is not an
* exhaustive list of LUT values (e.g., OpenStep has a lot of weird
* ones), but it should cover 99% of the current possibilities. */
#if defined(NeXT)
/* third-party utilities can modify the default LUT exponent */
LUT_exponent = 1.0 / 2.2;
/*
if (some_next_function_that_returns_gamma(&next_gamma))
LUT_exponent = 1.0 / next_gamma;
*/
#elif defined(sgi)
LUT_exponent = 1.0 / 1.7;
/* there doesn't seem to be any documented function to
* get the "gamma" value, so we do it the hard way */
infile = fopen("/etc/config/system.glGammaVal", "r");
if (infile) {
double sgi_gamma;
fgets(tmpline, 80, infile);
fclose(infile);
sgi_gamma = atof(tmpline);
if (sgi_gamma > 0.0)
LUT_exponent = 1.0 / sgi_gamma;
}
#elif defined(Macintosh)
LUT_exponent = 1.8 / 2.61;
/*
if (some_mac_function_that_returns_gamma(&mac_gamma))
LUT_exponent = mac_gamma / 2.61;
*/
#else
LUT_exponent = 1.0; /* assume no LUT: most PCs */
#endif
/* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
default_display_exponent = LUT_exponent * CRT_exponent;
/* If the user has set the SCREEN_GAMMA environment variable as suggested
* (somewhat imprecisely) in the libpng documentation, use that; otherwise
* use the default value we just calculated. Either way, the user may
* override this via a command-line option. */
if ((p = getenv("SCREEN_GAMMA")) != NULL)
rpng2_info.display_exponent = atof(p);
else
rpng2_info.display_exponent = default_display_exponent;
/* Now parse the command line for options and the PNG filename. */
while (*++argv && !error) {
if (!strncmp(*argv, "-display", 2)) {
if (!*++argv)
++error;
else
displayname = *argv;
} else if (!strncmp(*argv, "-gamma", 2)) {
if (!*++argv)
++error;
else {
rpng2_info.display_exponent = atof(*argv);
if (rpng2_info.display_exponent <= 0.0)
++error;
}
} else if (!strncmp(*argv, "-bgcolor", 4)) {
if (!*++argv)
++error;
else {
bgstr = *argv;
if (strlen(bgstr) != 7 || bgstr[0] != '#')
++error;
else {
have_bg = TRUE;
bg_image = FALSE;
}
}
} else if (!strncmp(*argv, "-bgpat", 4)) {
if (!*++argv)
++error;
else {
pat = atoi(*argv);
if (pat >= 0 && pat < num_bgpat) {
bg_image = TRUE;
have_bg = FALSE;
} else
++error;
}
} else if (!strncmp(*argv, "-usleep", 2)) {
if (!*++argv)
++error;
else {
usleep_duration = (ulg)atol(*argv);
demo_timing = TRUE;
}
} else if (!strncmp(*argv, "-pause", 2)) {
pause_after_pass = TRUE;
} else if (!strncmp(*argv, "-timing", 2)) {
timing = TRUE;
#ifdef FEATURE_LOOP
} else if (!strncmp(*argv, "-loop", 2)) {
loop = TRUE;
if (!argv[1] || !is_number(argv[1]))
loop_interval = 2;
else {
++argv;
loop_interval = atol(*argv);
if (loop_interval < 0)
loop_interval = 2;
else if (loop_interval > 100000) /* bit more than one day */
loop_interval = 100000;
}
#endif
} else {
if (**argv != '-') {
filename = *argv;
if (argv[1]) /* shouldn't be any more args after filename */
++error;
} else
++error; /* not expecting any other options */
}
}
if (!filename)
++error;
/* print usage screen if any errors up to this point */
if (error) {
fprintf(stderr, "\n%s %s: %s\n\n", PROGNAME, VERSION, appname);
readpng2_version_info();
fprintf(stderr, "\n"
"Usage: ");
fprintf(stderr,
"%s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n"
" %*s [-usleep dur | -timing] [-pause]\n",
PROGNAME, (int)strlen(PROGNAME), " ");
fprintf(stderr,
#ifdef FEATURE_LOOP
" [-loop [sec]]"
#endif
" file.png\n\n");
fprintf(stderr,
" xdpy\tname of the target X display (e.g., ``hostname:0'')\n"
" exp \ttransfer-function exponent (``gamma'') of the display\n"
"\t\t system in floating-point format (e.g., ``%.1f''); equal\n"
"\t\t to the product of the lookup-table exponent (varies)\n",
default_display_exponent);
fprintf(stderr,
"\t\t and the CRT exponent (usually 2.2); must be positive\n"
" bg \tdesired background color in 7-character hex RGB format\n"
"\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n"
"\t\t used with transparent images; overrides -bgpat\n"
" pat \tdesired background pattern number (0-%d); used with\n"
"\t\t transparent images; overrides -bgcolor\n",
num_bgpat-1);
#ifdef FEATURE_LOOP
fprintf(stderr,
" -loop\tloops through background images after initial display\n"
"\t\t is complete (depends on -bgpat)\n"
" sec \tseconds to display each background image (default = 2)\n");
#endif
fprintf(stderr,
" dur \tduration in microseconds to wait after displaying each\n"
"\t\t row (for demo purposes)\n"
" -timing\tenables delay for every block read, to simulate modem\n"
"\t\t download of image (~36 Kbps)\n"
" -pause\tpauses after displaying each pass until mouse clicked\n"
"\nPress Q, Esc or mouse button 1 (within image window, after image\n"
"is displayed) to quit.\n");
exit(1);
}
if (!(infile = fopen(filename, "rb"))) {
fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename);
++error;
} else {
incount = fread(inbuf, 1, INBUFSIZE, infile);
if (incount < 8 || !readpng2_check_sig(inbuf, 8)) {
fprintf(stderr, PROGNAME
": [%s] is not a PNG file: incorrect signature\n",
filename);
++error;
} else if ((rc = readpng2_init(&rpng2_info)) != 0) {
switch (rc) {
case 2:
fprintf(stderr, PROGNAME
": [%s] has bad IHDR (libpng longjmp)\n", filename);
break;
case 4:
fprintf(stderr, PROGNAME ": insufficient memory\n");
break;
default:
fprintf(stderr, PROGNAME
": unknown readpng2_init() error\n");
break;
}
++error;
} else {
Trace((stderr, "about to call XOpenDisplay()\n"))
display = XOpenDisplay(displayname);
if (!display) {
readpng2_cleanup(&rpng2_info);
fprintf(stderr, PROGNAME ": can't open X display [%s]\n",
displayname? displayname : "default");
++error;
}
}
if (error)
fclose(infile);
}
if (error) {
fprintf(stderr, PROGNAME ": aborting.\n");
exit(2);
}
/* set the title-bar string, but make sure buffer doesn't overflow */
alen = strlen(appname);
flen = strlen(filename);
if (alen + flen + 3 > 1023)
sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023));
else
sprintf(titlebar, "%s: %s", appname, filename);
/* set some final rpng2_info variables before entering main data loop */
if (have_bg) {
unsigned r, g, b; /* this approach quiets compiler warnings */
sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b);
rpng2_info.bg_red = (uch)r;
rpng2_info.bg_green = (uch)g;
rpng2_info.bg_blue = (uch)b;
} else
rpng2_info.need_bgcolor = TRUE;
rpng2_info.state = kPreInit;
rpng2_info.mainprog_init = rpng2_x_init;
rpng2_info.mainprog_display_row = rpng2_x_display_row;
rpng2_info.mainprog_finish_display = rpng2_x_finish_display;
/* OK, this is the fun part: call readpng2_decode_data() at the start of
* the loop to deal with our first buffer of data (read in above to verify
* that the file is a PNG image), then loop through the file and continue
* calling the same routine to handle each chunk of data. It in turn
* passes the data to libpng, which will invoke one or more of our call-
* backs as decoded data become available. We optionally call sleep() for
* one second per iteration to simulate downloading the image via an analog
* modem. */
for (;;) {
Trace((stderr, "about to call readpng2_decode_data()\n"))
if (readpng2_decode_data(&rpng2_info, inbuf, incount))
++error;
Trace((stderr, "done with readpng2_decode_data()\n"))
if (error || incount != INBUFSIZE || rpng2_info.state == kDone) {
if (rpng2_info.state == kDone) {
Trace((stderr, "done decoding PNG image\n"))
} else if (ferror(infile)) {
fprintf(stderr, PROGNAME
": error while reading PNG image file\n");
exit(3);
} else if (feof(infile)) {
fprintf(stderr, PROGNAME ": end of file reached "
"(unexpectedly) while reading PNG image file\n");
exit(3);
} else /* if (error) */ {
/* will print error message below */
}
break;
}
if (timing)
sleep(1);
incount = fread(inbuf, 1, INBUFSIZE, infile);
}
/* clean up PNG stuff and report any decoding errors */
fclose(infile);
Trace((stderr, "about to call readpng2_cleanup()\n"))
readpng2_cleanup(&rpng2_info);
if (error) {
fprintf(stderr, PROGNAME ": libpng error while decoding PNG image\n");
exit(3);
}
#ifdef FEATURE_LOOP
if (loop && bg_image) {
Trace((stderr, "entering -loop loop (FEATURE_LOOP)\n"))
for (;;) {
int i, use_sleep;
struct timeval now, then;
/* get current time and add loop_interval to get target time */
if (gettimeofday(&then, NULL) == 0) {
then.tv_sec += loop_interval;
use_sleep = FALSE;
} else
use_sleep = TRUE;
/* do quick check for a quit event but don't wait for it */
/* GRR BUG: should also check for Expose events and redraw... */
if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e))
if (QUIT(e,k))
break;
/* generate next background image */
if (++pat >= num_bgpat)
pat = 0;
rpng2_x_reload_bg_image();
/* wait for timeout, using whatever means are available */
if (use_sleep || gettimeofday(&now, NULL) != 0) {
for (i = loop_interval; i > 0; --i) {
sleep(1);
/* GRR BUG: also need to check for Expose (and redraw!) */
if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask,
&e) && QUIT(e,k))
break;
}
} else {
/* Y2038 BUG! */
if (now.tv_sec < then.tv_sec ||
(now.tv_sec == then.tv_sec && now.tv_usec < then.tv_usec))
{
int quit = FALSE;
long seconds_to_go = then.tv_sec - now.tv_sec;
long usleep_usec;
/* basically chew up most of remaining loop-interval with
* calls to sleep(1) interleaved with checks for quit
* events, but also recalc time-to-go periodically; when
* done, clean up any remaining time with usleep() call
* (could also use SIGALRM, but signals are a pain...) */
while (seconds_to_go-- > 1) {
int seconds_done = 0;
for (i = seconds_to_go; i > 0 && !quit; --i) {
sleep(1);
/* GRR BUG: need to check for Expose and redraw */
if (XCheckMaskEvent(display, KeyPressMask |
ButtonPressMask, &e) && QUIT(e,k))
quit = TRUE;
if (++seconds_done > 1000)
break; /* time to redo seconds_to_go meas. */
}
if (quit)
break;
/* OK, more than 1000 seconds since last check:
* correct the time-to-go measurement for drift */
if (gettimeofday(&now, NULL) == 0) {
if (now.tv_sec >= then.tv_sec)
break;
seconds_to_go = then.tv_sec - now.tv_sec;
} else
++seconds_to_go; /* restore what we subtracted */
}
if (quit)
break; /* breaks outer do-loop, skips redisplay */
/* since difference between "now" and "then" is already
* eaten up to within a couple of seconds, don't need to
* worry about overflow--but might have overshot (neg.) */
if (gettimeofday(&now, NULL) == 0) {
usleep_usec = 1000000L*(then.tv_sec - now.tv_sec) +
then.tv_usec - now.tv_usec;
if (usleep_usec > 0)
usleep((ulg)usleep_usec);
}
}
}
/* composite image against new background and display (note that
* we do not take into account the time spent doing this...) */
rpng2_x_redisplay_image (0, 0, rpng2_info.width, rpng2_info.height);
}
} else /* FALL THROUGH and do the normal thing */
#endif /* FEATURE_LOOP */
/* wait for the user to tell us when to quit */
if (rpng2_info.state >= kWindowInit) {
Trace((stderr, "entering final wait-for-quit-event loop\n"))
do {
XNextEvent(display, &e);
if (e.type == Expose) {
XExposeEvent *ex = (XExposeEvent *)&e;
rpng2_x_redisplay_image (ex->x, ex->y, ex->width, ex->height);
}
} while (!QUIT(e,k));
} else {
fprintf(stderr, PROGNAME ": init callback never called: probable "
"libpng error while decoding PNG metadata\n");
exit(4);
}
/* we're done: clean up all image and X resources and go away */
Trace((stderr, "about to call rpng2_x_cleanup()\n"))
rpng2_x_cleanup();
(void)argc; /* Unused */
return 0;
}
| 173,574 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ip6_tunnel_init(void)
{
int err;
if (xfrm6_tunnel_register(&ip4ip6_handler, AF_INET)) {
printk(KERN_ERR "ip6_tunnel init: can't register ip4ip6\n");
err = -EAGAIN;
goto out;
}
if (xfrm6_tunnel_register(&ip6ip6_handler, AF_INET6)) {
printk(KERN_ERR "ip6_tunnel init: can't register ip6ip6\n");
err = -EAGAIN;
goto unreg_ip4ip6;
}
err = register_pernet_device(&ip6_tnl_net_ops);
if (err < 0)
goto err_pernet;
return 0;
err_pernet:
xfrm6_tunnel_deregister(&ip6ip6_handler, AF_INET6);
unreg_ip4ip6:
xfrm6_tunnel_deregister(&ip4ip6_handler, AF_INET);
out:
return err;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int __init ip6_tunnel_init(void)
{
int err;
err = register_pernet_device(&ip6_tnl_net_ops);
if (err < 0)
goto out_pernet;
err = xfrm6_tunnel_register(&ip4ip6_handler, AF_INET);
if (err < 0) {
printk(KERN_ERR "ip6_tunnel init: can't register ip4ip6\n");
goto out_ip4ip6;
}
err = xfrm6_tunnel_register(&ip6ip6_handler, AF_INET6);
if (err < 0) {
printk(KERN_ERR "ip6_tunnel init: can't register ip6ip6\n");
goto out_ip6ip6;
}
return 0;
out_ip6ip6:
xfrm6_tunnel_deregister(&ip4ip6_handler, AF_INET);
out_ip4ip6:
unregister_pernet_device(&ip6_tnl_net_ops);
out_pernet:
return err;
}
| 165,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *escape_pathname(const char *inp)
{
const unsigned char *s;
char *escaped, *d;
if (!inp) {
return NULL;
}
escaped = malloc (4 * strlen(inp) + 1);
if (!escaped) {
perror("malloc");
return NULL;
}
for (d = escaped, s = (const unsigned char *)inp; *s; s++) {
if (needs_escape (*s)) {
snprintf (d, 5, "\\x%02x", *s);
d += strlen (d);
} else {
*d++ = *s;
}
}
*d++ = '\0';
return escaped;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | static char *escape_pathname(const char *inp)
{
const unsigned char *s;
char *escaped, *d;
if (!inp) {
return NULL;
}
escaped = malloc (4 * strlen(inp) + 1);
if (!escaped) {
perror("malloc");
return NULL;
}
for (d = escaped, s = (const unsigned char *)inp; *s; s++) {
if (needs_escape (*s)) {
snprintf (d, 5, "\\x%02x", *s);
d += strlen (d);
} else {
*d++ = *s;
}
}
*d++ = '\0';
return escaped;
}
| 169,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 pipe_advance(struct iov_iter *i, size_t size)
{
struct pipe_inode_info *pipe = i->pipe;
struct pipe_buffer *buf;
int idx = i->idx;
size_t off = i->iov_offset, orig_sz;
if (unlikely(i->count < size))
size = i->count;
orig_sz = size;
if (size) {
if (off) /* make it relative to the beginning of buffer */
size += off - pipe->bufs[idx].offset;
while (1) {
buf = &pipe->bufs[idx];
if (size <= buf->len)
break;
size -= buf->len;
idx = next_idx(idx, pipe);
}
buf->len = size;
i->idx = idx;
off = i->iov_offset = buf->offset + size;
}
if (off)
idx = next_idx(idx, pipe);
if (pipe->nrbufs) {
int unused = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
/* [curbuf,unused) is in use. Free [idx,unused) */
while (idx != unused) {
pipe_buf_release(pipe, &pipe->bufs[idx]);
idx = next_idx(idx, pipe);
pipe->nrbufs--;
}
}
i->count -= orig_sz;
}
Commit Message: fix a fencepost error in pipe_advance()
The logics in pipe_advance() used to release all buffers past the new
position failed in cases when the number of buffers to release was equal
to pipe->buffers. If that happened, none of them had been released,
leaving pipe full. Worse, it was trivial to trigger and we end up with
pipe full of uninitialized pages. IOW, it's an infoleak.
Cc: [email protected] # v4.9
Reported-by: "Alan J. Wylie" <[email protected]>
Tested-by: "Alan J. Wylie" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200 | static void pipe_advance(struct iov_iter *i, size_t size)
{
struct pipe_inode_info *pipe = i->pipe;
if (unlikely(i->count < size))
size = i->count;
if (size) {
struct pipe_buffer *buf;
size_t off = i->iov_offset, left = size;
int idx = i->idx;
if (off) /* make it relative to the beginning of buffer */
left += off - pipe->bufs[idx].offset;
while (1) {
buf = &pipe->bufs[idx];
if (left <= buf->len)
break;
left -= buf->len;
idx = next_idx(idx, pipe);
}
i->idx = idx;
i->iov_offset = buf->offset + left;
}
i->count -= size;
/* ... and discard everything past that point */
pipe_truncate(i);
}
| 168,388 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2)
{
pdf_xref_entry *table;
pdf_xref_entry *table;
int i, n;
if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1)
fz_throw(ctx, FZ_ERROR_GENERIC, "negative xref stream entry index");
table = pdf_xref_find_subsection(ctx, doc, i0, i1);
for (i = i0; i < i0 + i1; i++)
for (i = i0; i < i0 + i1; i++)
{
pdf_xref_entry *entry = &table[i-i0];
int a = 0;
int64_t b = 0;
int c = 0;
if (fz_is_eof(ctx, stm))
fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream");
for (n = 0; n < w0; n++)
a = (a << 8) + fz_read_byte(ctx, stm);
for (n = 0; n < w1; n++)
b = (b << 8) + fz_read_byte(ctx, stm);
for (n = 0; n < w2; n++)
c = (c << 8) + fz_read_byte(ctx, stm);
if (!entry->type)
{
int t = w0 ? a : 1;
entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0;
entry->ofs = w1 ? b : 0;
entry->gen = w2 ? c : 0;
entry->num = i;
}
}
doc->has_xref_streams = 1;
}
Commit Message:
CWE ID: CWE-119 | pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2)
{
pdf_xref_entry *table;
pdf_xref_entry *table;
int i, n;
if (i0 < 0 || i0 > PDF_MAX_OBJECT_NUMBER || i1 < 0 || i1 > PDF_MAX_OBJECT_NUMBER || i0 + i1 - 1 > PDF_MAX_OBJECT_NUMBER)
fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range");
table = pdf_xref_find_subsection(ctx, doc, i0, i1);
for (i = i0; i < i0 + i1; i++)
for (i = i0; i < i0 + i1; i++)
{
pdf_xref_entry *entry = &table[i-i0];
int a = 0;
int64_t b = 0;
int c = 0;
if (fz_is_eof(ctx, stm))
fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream");
for (n = 0; n < w0; n++)
a = (a << 8) + fz_read_byte(ctx, stm);
for (n = 0; n < w1; n++)
b = (b << 8) + fz_read_byte(ctx, stm);
for (n = 0; n < w2; n++)
c = (c << 8) + fz_read_byte(ctx, stm);
if (!entry->type)
{
int t = w0 ? a : 1;
entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0;
entry->ofs = w1 ? b : 0;
entry->gen = w2 ? c : 0;
entry->num = i;
}
}
doc->has_xref_streams = 1;
}
| 165,390 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
unsigned int optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
if (!sctp_is_ep_boundall(sk) && val)
return -EINVAL;
if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
return 0;
if (val == 0 && sp->do_auto_asconf) {
list_del(&sp->auto_asconf_list);
sp->do_auto_asconf = 0;
} else if (val && !sp->do_auto_asconf) {
list_add_tail(&sp->auto_asconf_list,
&sock_net(sk)->sctp.auto_asconf_splist);
sp->do_auto_asconf = 1;
}
return 0;
}
Commit Message: sctp: fix ASCONF list handling
->auto_asconf_splist is per namespace and mangled by functions like
sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization.
Also, the call to inet_sk_copy_descendant() was backuping
->auto_asconf_list through the copy but was not honoring
->do_auto_asconf, which could lead to list corruption if it was
different between both sockets.
This commit thus fixes the list handling by using ->addr_wq_lock
spinlock to protect the list. A special handling is done upon socket
creation and destruction for that. Error handlig on sctp_init_sock()
will never return an error after having initialized asconf, so
sctp_destroy_sock() can be called without addrq_wq_lock. The lock now
will be take on sctp_close_sock(), before locking the socket, so we
don't do it in inverse order compared to sctp_addr_wq_timeout_handler().
Instead of taking the lock on sctp_sock_migrate() for copying and
restoring the list values, it's preferred to avoid rewritting it by
implementing sctp_copy_descendant().
Issue was found with a test application that kept flipping sysctl
default_auto_asconf on and off, but one could trigger it by issuing
simultaneous setsockopt() calls on multiple sockets or by
creating/destroying sockets fast enough. This is only triggerable
locally.
Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).")
Reported-by: Ji Jianwen <[email protected]>
Suggested-by: Neil Horman <[email protected]>
Suggested-by: Hannes Frederic Sowa <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
unsigned int optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
if (!sctp_is_ep_boundall(sk) && val)
return -EINVAL;
if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
return 0;
spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
if (val == 0 && sp->do_auto_asconf) {
list_del(&sp->auto_asconf_list);
sp->do_auto_asconf = 0;
} else if (val && !sp->do_auto_asconf) {
list_add_tail(&sp->auto_asconf_list,
&sock_net(sk)->sctp.auto_asconf_splist);
sp->do_auto_asconf = 1;
}
spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
return 0;
}
| 166,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
/* FIXME: check that the invalid encoding handling is correct */
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
assert ((*s & 0x80));
if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* invalid encoding */
nmore = 5; /* we will reduce the check length anyway */
if (n+nmore > length)
nmore = length - n; /* oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* invalid encoding - stop */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
Commit Message:
CWE ID: CWE-119 | append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
if (!(*s & 0x80))
nmore = 0; /* Not expected here: high bit not set. */
else if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* Invalid encoding */
nmore = 0;
if (!nmore)
{
/* Encoding error: We quote the bad byte. */
snprintf (tmp, sizeof tmp, "\\%02X", *s);
put_stringbuf_mem (sb, tmp, 3);
s++; n++;
}
else
{
if (n+nmore > length)
nmore = length - n; /* Oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* Invalid encoding - let the next cycle detect this. */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
}
| 165,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Do not read the next line to support correct counting with fgetc()
if (!intern->current_line) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
} */
RETURN_LONG(intern->u.file.current_line_num);
} /* }}} */
/* {{{ proto void SplFileObject::next()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Do not read the next line to support correct counting with fgetc()
if (!intern->current_line) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
} */
RETURN_LONG(intern->u.file.current_line_num);
} /* }}} */
/* {{{ proto void SplFileObject::next()
| 167,056 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: fb_mmap(struct file *file, struct vm_area_struct * vma)
{
struct fb_info *info = file_fb_info(file);
struct fb_ops *fb;
unsigned long off;
unsigned long start;
u32 len;
if (!info)
return -ENODEV;
if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))
return -EINVAL;
off = vma->vm_pgoff << PAGE_SHIFT;
fb = info->fbops;
if (!fb)
return -ENODEV;
mutex_lock(&info->mm_lock);
if (fb->fb_mmap) {
int res;
res = fb->fb_mmap(info, vma);
mutex_unlock(&info->mm_lock);
return res;
}
/* frame buffer memory */
start = info->fix.smem_start;
len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len);
if (off >= len) {
/* memory mapped io */
off -= len;
if (info->var.accel_flags) {
mutex_unlock(&info->mm_lock);
return -EINVAL;
}
start = info->fix.mmio_start;
len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.mmio_len);
}
mutex_unlock(&info->mm_lock);
start &= PAGE_MASK;
if ((vma->vm_end - vma->vm_start + off) > len)
return -EINVAL;
off += start;
vma->vm_pgoff = off >> PAGE_SHIFT;
/* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by io_remap_pfn_range()*/
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fb_pgprotect(file, vma, off);
if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start, vma->vm_page_prot))
return -EAGAIN;
return 0;
}
Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper
This is my example conversion of a few existing mmap users. The
fb_mmap() case is a good example because it is a bit more complicated
than some: fb_mmap() mmaps one of two different memory areas depending
on the page offset of the mmap (but happily there is never any mixing of
the two, so the helper function still works).
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | fb_mmap(struct file *file, struct vm_area_struct * vma)
{
struct fb_info *info = file_fb_info(file);
struct fb_ops *fb;
unsigned long mmio_pgoff;
unsigned long start;
u32 len;
if (!info)
return -ENODEV;
fb = info->fbops;
if (!fb)
return -ENODEV;
mutex_lock(&info->mm_lock);
if (fb->fb_mmap) {
int res;
res = fb->fb_mmap(info, vma);
mutex_unlock(&info->mm_lock);
return res;
}
/*
* Ugh. This can be either the frame buffer mapping, or
* if pgoff points past it, the mmio mapping.
*/
start = info->fix.smem_start;
len = info->fix.smem_len;
mmio_pgoff = PAGE_ALIGN((start & ~PAGE_MASK) + len) >> PAGE_SHIFT;
if (vma->vm_pgoff >= mmio_pgoff) {
vma->vm_pgoff -= mmio_pgoff;
start = info->fix.mmio_start;
len = info->fix.mmio_len;
}
mutex_unlock(&info->mm_lock);
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fb_pgprotect(file, vma, start);
return vm_iomap_memory(vma, start, len);
}
| 166,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PGTYPESdate_from_asc(char *str, char **endptr)
{
date dDate;
fsec_t fsec;
struct tm tt,
*tm = &tt;
int dtype;
int nf;
char *field[MAXDATEFIELDS];
int ftype[MAXDATEFIELDS];
char lowstr[MAXDATELEN + 1];
char *realptr;
char **ptr = (endptr != NULL) ? endptr : &realptr;
bool EuroDates = FALSE;
errno = 0;
if (strlen(str) >= sizeof(lowstr))
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 ||
DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, EuroDates) != 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
switch (dtype)
{
case DTK_DATE:
break;
case DTK_EPOCH:
if (GetEpochTime(tm) < 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
break;
default:
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
dDate = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1));
return dDate;
}
Commit Message: Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value. It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer. ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own. In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly. Back-patch to 8.4
(all supported versions).
Reported by Daniel Schüssler, reviewed by Tom Lane.
Security: CVE-2014-0063
CWE ID: CWE-119 | PGTYPESdate_from_asc(char *str, char **endptr)
{
date dDate;
fsec_t fsec;
struct tm tt,
*tm = &tt;
int dtype;
int nf;
char *field[MAXDATEFIELDS];
int ftype[MAXDATEFIELDS];
char lowstr[MAXDATELEN + MAXDATEFIELDS];
char *realptr;
char **ptr = (endptr != NULL) ? endptr : &realptr;
bool EuroDates = FALSE;
errno = 0;
if (strlen(str) > MAXDATELEN)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 ||
DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, EuroDates) != 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
switch (dtype)
{
case DTK_DATE:
break;
case DTK_EPOCH:
if (GetEpochTime(tm) < 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
break;
default:
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
dDate = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1));
return dDate;
}
| 166,463 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
int ret;
assert(ts != NULL);
if (ts->innerstream) {
ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE));
} else {
ret = 0;
}
if (ts->meta) {
zval_ptr_dtor(&ts->meta);
}
efree(ts);
return ret;
}
Commit Message:
CWE ID: CWE-20 | static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
int ret;
assert(ts != NULL);
if (ts->innerstream) {
ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE));
} else {
ret = 0;
}
if (ts->meta) {
zval_ptr_dtor(&ts->meta);
}
efree(ts);
return ret;
}
| 165,479 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
Commit Message:
CWE ID: CWE-682 | XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + rlen;
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
| 164,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!auth_current_ef)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid auth_current_ef");
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
}
| 169,058 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
int32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth);
if (kUseHexDump) {
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
}
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) {
mMoofFound = true;
mMoofOffset = *offset;
}
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (chunk_size < 20 || pssh.datalen > chunk_size - 20) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
if (!timescale) {
ALOGE("timescale should not be ZERO.");
return ERROR_MALFORMED;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0 && mLastTrack->timescale != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
if (max_size > SIZE_MAX - 10 * 2) {
ALOGE("max sample size too big: %zu", max_size);
return ERROR_MALFORMED;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
uint32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) ||
!mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
} else {
if (width > 32768 || height > 32768) {
ALOGE("can't support %u x %u video", width, height);
return ERROR_MALFORMED;
}
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC(0xA9, 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) {
ESDS esds(&buffer[4], chunk_data_size - 4);
uint8_t objectTypeIndication;
if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) {
if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
}
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
bool isParsingMetaKeys = underQTMetaPath(mPath, 2);
if (!isParsingMetaKeys) {
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset = stop_offset;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset = stop_offset;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset = stop_offset;
return OK;
}
*offset += sizeof(buffer);
}
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
mMdatFound = true;
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
break;
}
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
if (mLastTrack != NULL) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
}
break;
}
case FOURCC('k', 'e', 'y', 's'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
parseQTMetaKey(data_offset, chunk_data_size);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
if (mLastTrack == NULL)
return ERROR_MALFORMED;
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) {
return ERROR_MALFORMED;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64,
chunk_data_size, data_offset);
if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) {
return ERROR_MALFORMED;
}
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
if (chunk_data_size <= kSkipBytesOfDataBox) {
return ERROR_MALFORMED;
}
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
if (underQTMetaPath(mPath, 3)) {
parseQTMetaVal(chunk_type, data_offset, chunk_data_size);
}
*offset += chunk_size;
break;
}
}
return OK;
}
Commit Message: Check malloc result to avoid NPD
Bug: 28471206
Change-Id: Id5d055d76893d6f53a2e524ff5f282d1ddca3345
CWE ID: CWE-20 | status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
int32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth);
if (kUseHexDump) {
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
}
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) {
mMoofFound = true;
mMoofOffset = *offset;
}
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (chunk_size < 20 || pssh.datalen > chunk_size - 20) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
if (!timescale) {
ALOGE("timescale should not be ZERO.");
return ERROR_MALFORMED;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0 && mLastTrack->timescale != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
if (max_size > SIZE_MAX - 10 * 2) {
ALOGE("max sample size too big: %zu", max_size);
return ERROR_MALFORMED;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
uint32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) ||
!mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
} else {
if (width > 32768 || height > 32768) {
ALOGE("can't support %u x %u video", width, height);
return ERROR_MALFORMED;
}
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC(0xA9, 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) {
ESDS esds(&buffer[4], chunk_data_size - 4);
uint8_t objectTypeIndication;
if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) {
if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
}
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
bool isParsingMetaKeys = underQTMetaPath(mPath, 2);
if (!isParsingMetaKeys) {
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset = stop_offset;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset = stop_offset;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset = stop_offset;
return OK;
}
*offset += sizeof(buffer);
}
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
mMdatFound = true;
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
break;
}
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
if (mLastTrack != NULL) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
}
break;
}
case FOURCC('k', 'e', 'y', 's'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
parseQTMetaKey(data_offset, chunk_data_size);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
if (mLastTrack == NULL)
return ERROR_MALFORMED;
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) {
return ERROR_MALFORMED;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64,
chunk_data_size, data_offset);
if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) {
return ERROR_MALFORMED;
}
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
if (chunk_data_size <= kSkipBytesOfDataBox) {
return ERROR_MALFORMED;
}
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
if (underQTMetaPath(mPath, 3)) {
parseQTMetaVal(chunk_type, data_offset, chunk_data_size);
}
*offset += chunk_size;
break;
}
}
return OK;
}
| 173,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
Commit Message: Avoid a crash (double-free) when SSH connection fails
CWE ID: CWE-415 | static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
sshu->session = NULL;
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
| 169,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SoftAACEncoder::~SoftAACEncoder() {
delete[] mInputFrame;
mInputFrame = NULL;
if (mEncoderHandle) {
CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
mEncoderHandle = NULL;
}
delete mApiHandle;
mApiHandle = NULL;
delete mMemOperator;
mMemOperator = NULL;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | SoftAACEncoder::~SoftAACEncoder() {
onReset();
if (mEncoderHandle) {
CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
mEncoderHandle = NULL;
}
delete mApiHandle;
mApiHandle = NULL;
delete mMemOperator;
mMemOperator = NULL;
}
| 174,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error)
{
*ret = g_ascii_strup (str, -1);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error)
| 165,126 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection,
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID: | bool Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection.asSelection(),
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
| 172,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: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
if (len > INT_MAX)
len = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
iov.iov_base = buff;
iov.iov_len = len;
msg.msg_name = NULL;
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg, len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom
Cc: [email protected] # v3.19
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
if (len > INT_MAX)
len = INT_MAX;
if (unlikely(!access_ok(VERIFY_READ, buff, len)))
return -EFAULT;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
iov.iov_base = buff;
iov.iov_len = len;
msg.msg_name = NULL;
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg, len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
| 167,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: int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = ctx->cipher->do_cipher(ctx, out, in, inl);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
if (inl <= 0) {
*outl = 0;
return inl == 0;
}
if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
*outl = inl;
return 1;
} else {
*outl = 0;
return 0;
}
}
i = ctx->buf_len;
bl = ctx->cipher->block_size;
OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
if (i != 0) {
if (i + inl < bl) {
memcpy(&(ctx->buf[i]), in, inl);
ctx->buf_len += inl;
*outl = 0;
return 1;
} else {
j = bl - i;
memcpy(&(ctx->buf[i]), in, j);
if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
return 0;
inl -= j;
in += j;
out += bl;
*outl = bl;
}
} else
*outl = 0;
i = inl & (bl - 1);
inl -= i;
if (inl > 0) {
if (!ctx->cipher->do_cipher(ctx, out, in, inl))
return 0;
*outl += inl;
}
if (i != 0)
memcpy(ctx->buf, &(in[inl]), i);
ctx->buf_len = i;
return 1;
}
Commit Message:
CWE ID: CWE-189 | int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = ctx->cipher->do_cipher(ctx, out, in, inl);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
if (inl <= 0) {
*outl = 0;
return inl == 0;
}
if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
*outl = inl;
return 1;
} else {
*outl = 0;
return 0;
}
}
i = ctx->buf_len;
bl = ctx->cipher->block_size;
OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
if (i != 0) {
if (bl - i > inl) {
memcpy(&(ctx->buf[i]), in, inl);
ctx->buf_len += inl;
*outl = 0;
return 1;
} else {
j = bl - i;
memcpy(&(ctx->buf[i]), in, j);
if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
return 0;
inl -= j;
in += j;
out += bl;
*outl = bl;
}
} else
*outl = 0;
i = inl & (bl - 1);
inl -= i;
if (inl > 0) {
if (!ctx->cipher->do_cipher(ctx, out, in, inl))
return 0;
*outl += inl;
}
if (i != 0)
memcpy(ctx->buf, &(in[inl]), i);
ctx->buf_len = i;
return 1;
}
| 165,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
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();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
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: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL(chrome::kSwappedOutURL))
return WebKit::WebNavigationPolicyIgnore;
// Allow chrome::kSwappedOutURL to complete.
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();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
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,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
Commit Message: fix #58 : access to invalid address by reg->dmin value
CWE ID: CWE-125 | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
| 168,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
bool firstexp = true;
bool printHere = false;
int i = 0, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
RList *symbols = r_bin_get_symbols (r->bin);
r_spaces_push (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n");
}
size_t count = 0;
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true);
ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn = {0};
if (exponly && !isAnExport (symbol)) {
free (r_symbol_name);
continue;
}
if (name && strcmp (r_symbol_name, name)) {
free (r_symbol_name);
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
free (r_symbol_name);
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
free (r_symbol_name);
continue;
}
count ++;
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) {
if (is_arm) {
handle_arm_special_symbol (r, symbol, va);
}
} else if (IS_MODE_SET (mode)) {
if (is_arm) {
handle_arm_symbol (r, symbol, info, va);
}
select_flag_space (r, symbol);
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
char *comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *n = sn.demname ? sn.demname : sn.name;
const char *fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
fi->demangled = (bool)(size_t)sn.demname;
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
r_flag_space_pop (r->flags);
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_escape_utf8_for_json (r_symbol_name, -1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
/* Skip special symbols because we do not flag them and
* they shouldn't be printed in the rad format either */
if (is_special_symbol (symbol)) {
goto next;
}
RBinFile *binfile;
RBinPlugin *plugin;
const char *name = sn.demname? sn.demname: r_symbol_name;
if (!name) {
goto next;
}
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i') {
r_cons_printf ("fs imports\n");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
const char *fs = exponly? "exports": "symbols";
r_cons_printf ("fs %s\n", fs);
}
lastfs = 's';
}
if (r->bin->prefix || *name) { // we don't want unnamed symbol flags
char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT);
if (!flagname) {
goto next;
}
r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n",
r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "",
flagname, symbol->size, addr);
free (flagname);
}
binfile = r_bin_cur (r->bin);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (r_str_startswith (plugin->name, "pe")) {
char *module = strdup (r_symbol_name);
char *p = strstr (module, ".dll_");
if (p && strstr (module, "imp.")) {
char *symname = __filterShell (p + 5);
char *m = __filterShell (module);
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("k bin/pe/%s/%d=%s.%s\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("k bin/pe/%s/%d=%s\n",
module, symbol->ordinal, symname);
}
free (symname);
free (m);
}
free (module);
}
}
} else {
const char *bind = symbol->bind? symbol->bind: "NONE";
const char *type = symbol->type? symbol->type: "NONE";
const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name);
r_cons_printf ("%03u", symbol->ordinal);
if (symbol->paddr == UT64_MAX) {
r_cons_printf (" ----------");
} else {
r_cons_printf (" 0x%08"PFMT64x, symbol->paddr);
}
r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n",
addr, bind, type, symbol->size, *name? " ": "", name);
}
next:
snFini (&sn);
i++;
free (r_symbol_name);
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
if (count == 0 && IS_MODE_JSON (mode)) {
r_cons_printf ("{}");
}
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
handle_arm_entry (r, entry, info, va);
}
}
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("]");
}
r_spaces_pop (&r->anal->meta_spaces);
return true;
}
Commit Message: More fixes for the CVE-2019-14745
CWE ID: CWE-78 | static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
bool firstexp = true;
bool printHere = false;
int i = 0, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
RList *symbols = r_bin_get_symbols (r->bin);
r_spaces_push (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n");
}
size_t count = 0;
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true);
ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn = {0};
if (exponly && !isAnExport (symbol)) {
free (r_symbol_name);
continue;
}
if (name && strcmp (r_symbol_name, name)) {
free (r_symbol_name);
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
free (r_symbol_name);
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
free (r_symbol_name);
continue;
}
count ++;
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) {
if (is_arm) {
handle_arm_special_symbol (r, symbol, va);
}
} else if (IS_MODE_SET (mode)) {
if (is_arm) {
handle_arm_symbol (r, symbol, info, va);
}
select_flag_space (r, symbol);
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
char *comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *n = sn.demname ? sn.demname : sn.name;
const char *fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
fi->demangled = (bool)(size_t)sn.demname;
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
r_flag_space_pop (r->flags);
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_escape_utf8_for_json (r_symbol_name, -1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
/* Skip special symbols because we do not flag them and
* they shouldn't be printed in the rad format either */
if (is_special_symbol (symbol)) {
goto next;
}
RBinFile *binfile;
RBinPlugin *plugin;
const char *name = sn.demname? sn.demname: r_symbol_name;
if (!name) {
goto next;
}
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i') {
r_cons_printf ("fs imports\n");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
const char *fs = exponly? "exports": "symbols";
r_cons_printf ("fs %s\n", fs);
}
lastfs = 's';
}
if (r->bin->prefix || *name) { // we don't want unnamed symbol flags
char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT);
if (!flagname) {
goto next;
}
r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n",
r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "",
flagname, symbol->size, addr);
free (flagname);
}
binfile = r_bin_cur (r->bin);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (r_str_startswith (plugin->name, "pe")) {
char *module = strdup (r_symbol_name);
char *p = strstr (module, ".dll_");
if (p && strstr (module, "imp.")) {
char *symname = __filterShell (p + 5);
char *m = __filterShell (module);
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("\"k bin/pe/%s/%d=%s.%s\"\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("\"k bin/pe/%s/%d=%s\"\n",
module, symbol->ordinal, symname);
}
free (symname);
free (m);
}
free (module);
}
}
} else {
const char *bind = symbol->bind? symbol->bind: "NONE";
const char *type = symbol->type? symbol->type: "NONE";
const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name);
r_cons_printf ("%03u", symbol->ordinal);
if (symbol->paddr == UT64_MAX) {
r_cons_printf (" ----------");
} else {
r_cons_printf (" 0x%08"PFMT64x, symbol->paddr);
}
r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n",
addr, bind, type, symbol->size, *name? " ": "", name);
}
next:
snFini (&sn);
i++;
free (r_symbol_name);
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
if (count == 0 && IS_MODE_JSON (mode)) {
r_cons_printf ("{}");
}
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
handle_arm_entry (r, entry, info, va);
}
}
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("]");
}
r_spaces_pop (&r->anal->meta_spaces);
return true;
}
| 170,186 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Tracks::Tracks(
Segment* pSegment,
long long start,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_trackEntries(NULL),
m_trackEntriesEnd(NULL)
{
}
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 | Tracks::Tracks(
| 174,446 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int i, pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
dev_dbg(dev, "Checking memory size\n");
i = 0x12345678;
catc_write_mem(catc, 0x7a80, &i, 4);
i = 0x87654321;
catc_write_mem(catc, 0xfa80, &i, 4);
catc_read_mem(catc, 0x7a80, &i, 4);
switch (i) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
Commit Message: catc: Use heap buffer for memory size test
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
u32 *buf;
int i;
dev_dbg(dev, "Checking memory size\n");
buf = kmalloc(4, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto fail_free;
}
*buf = 0x12345678;
catc_write_mem(catc, 0x7a80, buf, 4);
*buf = 0x87654321;
catc_write_mem(catc, 0xfa80, buf, 4);
catc_read_mem(catc, 0x7a80, buf, 4);
switch (*buf) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
kfree(buf);
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
| 168,213 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_unwrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int *conf_state,
gss_qop_t *qop_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_unwrap_iov(minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_unwrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int *conf_state,
gss_qop_t *qop_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_unwrap_iov(minor_status,
sc->ctx_handle,
conf_state,
qop_state,
iov,
iov_count);
return (ret);
}
| 166,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *jp2_decode(jas_stream_t *in, char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("got box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("warning: component data type mismatch\n");
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(
dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image));
++i) {
if (jas_image_cmptdtype(dec->image, i) !=
JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("warning: component data type mismatch\n");
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
if (!iccprof) {
jas_eprintf("error: failed to parse ICC profile\n");
goto error;
}
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
assert(dec->image->cmprof_);
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
JAS_CAST(uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >=
dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno,
pclrd->numlutents, lutents,
JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#endif
}
}
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the channel number reasonable? */
if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {
jas_eprintf("error: invalid channel number in CDEF box\n");
goto error;
}
jas_image_setcmpttype(dec->image,
dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type,
dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("got box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("warning: component data type mismatch\n");
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(
dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
++i) {
if (jas_image_cmptdtype(dec->image, i) !=
JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("warning: component data type mismatch\n");
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
if (!iccprof) {
jas_eprintf("error: failed to parse ICC profile\n");
goto error;
}
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
assert(dec->image->cmprof_);
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,
jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >=
dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno,
pclrd->numlutents, lutents,
JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#endif
}
}
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the channel number reasonable? */
if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {
jas_eprintf("error: invalid channel number in CDEF box\n");
goto error;
}
jas_image_setcmpttype(dec->image,
dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type,
dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
| 168,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: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
memset(header->pBuffer, 0, header->nAllocLen);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
Commit Message: IOMX: do not clear buffer if it's allocated by component
The component might depends on their buffers to be initialized
in certain ways to work. Don't clear unless we're allocating it.
bug: 31586647
Change-Id: Ia0a125797e414998ef0cd8ce03672f5b1e0bbf7a
(cherry picked from commit ea76573aa276f51950007217a97903c4fe64f685)
CWE ID: CWE-200 | status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
| 174,144 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AutomationProvider::SendFindRequest(
TabContents* tab_contents,
bool with_json,
const string16& search_string,
bool forward,
bool match_case,
bool find_next,
IPC::Message* reply_message) {
int request_id = FindInPageNotificationObserver::kFindInPageRequestId;
FindInPageNotificationObserver* observer =
new FindInPageNotificationObserver(this,
tab_contents,
with_json,
reply_message);
if (!with_json) {
find_in_page_observer_.reset(observer);
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
if (wrapper)
wrapper->GetFindManager()->set_current_find_request_id(request_id);
tab_contents->render_view_host()->StartFinding(
FindInPageNotificationObserver::kFindInPageRequestId,
search_string,
forward,
match_case,
find_next);
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void AutomationProvider::SendFindRequest(
TabContents* tab_contents,
bool with_json,
const string16& search_string,
bool forward,
bool match_case,
bool find_next,
IPC::Message* reply_message) {
int request_id = FindInPageNotificationObserver::kFindInPageRequestId;
FindInPageNotificationObserver* observer =
new FindInPageNotificationObserver(this,
tab_contents,
with_json,
reply_message);
if (!with_json) {
find_in_page_observer_.reset(observer);
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
if (wrapper)
wrapper->find_tab_helper()->set_current_find_request_id(request_id);
tab_contents->render_view_host()->StartFinding(
FindInPageNotificationObserver::kFindInPageRequestId,
search_string,
forward,
match_case,
find_next);
}
| 170,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 re_yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | int re_yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
| 168,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: void RenderFrameImpl::OnSelectPopupMenuItems(
bool canceled,
const std::vector<int>& selected_indices) {
if (!external_popup_menu_)
return;
blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItems(canceled, selected_indices);
external_popup_menu_.reset();
}
Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s)
ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl.
We need to reset external_popup_menu_ before calling it.
Bug: 912211
Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc
Reviewed-on: https://chromium-review.googlesource.com/c/1381325
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618026}
CWE ID: CWE-416 | void RenderFrameImpl::OnSelectPopupMenuItems(
bool canceled,
const std::vector<int>& selected_indices) {
if (!external_popup_menu_)
return;
blink::WebScopedUserGesture gesture(frame_);
// We need to reset |external_popup_menu_| before calling DidSelectItems(),
// which might delete |this|.
// See ExternalPopupMenuRemoveTest.RemoveFrameOnChange
std::unique_ptr<ExternalPopupMenu> popup;
popup.swap(external_popup_menu_);
popup->DidSelectItems(canceled, selected_indices);
}
| 173,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 NavigationRequest::OnStartChecksComplete(
NavigationThrottle::ThrottleCheckResult result) {
DCHECK(result.action() != NavigationThrottle::DEFER);
DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE);
if (on_start_checks_complete_closure_)
on_start_checks_complete_closure_.Run();
if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE ||
result.action() == NavigationThrottle::CANCEL ||
result.action() == NavigationThrottle::BLOCK_REQUEST ||
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
#if DCHECK_IS_ON()
if (result.action() == NavigationThrottle::BLOCK_REQUEST) {
DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT ||
result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR);
}
else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) {
DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED);
}
#endif
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&NavigationRequest::OnRequestFailedInternal,
weak_factory_.GetWeakPtr(), false,
result.net_error_code(), base::nullopt, true,
result.error_page_content()));
return;
}
DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_);
RenderFrameHostImpl* navigating_frame_host =
associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE
? frame_tree_node_->render_manager()->speculative_frame_host()
: frame_tree_node_->current_frame_host();
DCHECK(navigating_frame_host);
navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess());
BrowserContext* browser_context =
frame_tree_node_->navigator()->GetController()->GetBrowserContext();
StoragePartition* partition = BrowserContext::GetStoragePartition(
browser_context, navigating_frame_host->GetSiteInstance());
DCHECK(partition);
bool can_create_service_worker =
(frame_tree_node_->pending_frame_policy().sandbox_flags &
blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin;
request_params_.should_create_service_worker = can_create_service_worker;
if (can_create_service_worker) {
ServiceWorkerContextWrapper* service_worker_context =
static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
navigation_handle_->InitServiceWorkerHandle(service_worker_context);
}
if (IsSchemeSupportedForAppCache(common_params_.url)) {
if (navigating_frame_host->GetRenderViewHost()
->GetWebkitPreferences()
.application_cache_enabled) {
navigation_handle_->InitAppCacheHandle(
static_cast<ChromeAppCacheService*>(partition->GetAppCacheService()));
}
}
request_params_.navigation_timing.fetch_start = base::TimeTicks::Now();
GURL base_url;
#if defined(OS_ANDROID)
NavigationEntry* last_committed_entry =
frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry();
if (last_committed_entry)
base_url = last_committed_entry->GetBaseURLForDataURL();
#endif
const GURL& top_document_url =
!base_url.is_empty()
? base_url
: frame_tree_node_->frame_tree()->root()->current_url();
const GURL& site_for_cookies =
frame_tree_node_->IsMainFrame() ? common_params_.url : top_document_url;
bool parent_is_main_frame = !frame_tree_node_->parent()
? false
: frame_tree_node_->parent()->IsMainFrame();
std::unique_ptr<NavigationUIData> navigation_ui_data;
if (navigation_handle_->GetNavigationUIData())
navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone();
bool is_for_guests_only =
navigation_handle_->GetStartingSiteInstance()->GetSiteURL().
SchemeIs(kGuestScheme);
bool report_raw_headers = false;
RenderFrameDevToolsAgentHost::ApplyOverrides(
frame_tree_node_, begin_params_.get(), &report_raw_headers);
RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this);
loader_ = NavigationURLLoader::Create(
browser_context->GetResourceContext(), partition,
std::make_unique<NavigationRequestInfo>(
common_params_, begin_params_.Clone(), site_for_cookies,
frame_tree_node_->IsMainFrame(), parent_is_main_frame,
IsSecureFrame(frame_tree_node_->parent()),
frame_tree_node_->frame_tree_node_id(), is_for_guests_only,
report_raw_headers,
navigating_frame_host->GetVisibilityState() ==
blink::mojom::PageVisibilityState::kPrerender,
blob_url_loader_factory_ ? blob_url_loader_factory_->Clone()
: nullptr),
std::move(navigation_ui_data),
navigation_handle_->service_worker_handle(),
navigation_handle_->appcache_handle(), this);
}
Commit Message: Check ancestors when setting an <iframe> navigation's "site for cookies".
Currently, we're setting the "site for cookies" only by looking at the
top-level document. We ought to be verifying that the ancestor frames
are same-site before doing so. We do this correctly in Blink (see
`Document::SiteForCookies`), but didn't do so when navigating in the
browser.
This patch addresses the majority of the problem by walking the ancestor
chain when processing a NavigationRequest. If all the ancestors are
same-site, we set the "site for cookies" to the top-level document's URL.
If they aren't all same-site, we set it to an empty URL to ensure that
we don't send SameSite cookies.
Bug: 833847
Change-Id: Icd77f31fa618fa9f8b59fc3b15e1bed6ee05aabd
Reviewed-on: https://chromium-review.googlesource.com/1025772
Reviewed-by: Alex Moshchuk <[email protected]>
Commit-Queue: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553942}
CWE ID: CWE-20 | void NavigationRequest::OnStartChecksComplete(
NavigationThrottle::ThrottleCheckResult result) {
DCHECK(result.action() != NavigationThrottle::DEFER);
DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE);
if (on_start_checks_complete_closure_)
on_start_checks_complete_closure_.Run();
if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE ||
result.action() == NavigationThrottle::CANCEL ||
result.action() == NavigationThrottle::BLOCK_REQUEST ||
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
#if DCHECK_IS_ON()
if (result.action() == NavigationThrottle::BLOCK_REQUEST) {
DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT ||
result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR);
}
else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) {
DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED);
}
#endif
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&NavigationRequest::OnRequestFailedInternal,
weak_factory_.GetWeakPtr(), false,
result.net_error_code(), base::nullopt, true,
result.error_page_content()));
return;
}
DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_);
RenderFrameHostImpl* navigating_frame_host =
associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE
? frame_tree_node_->render_manager()->speculative_frame_host()
: frame_tree_node_->current_frame_host();
DCHECK(navigating_frame_host);
navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess());
BrowserContext* browser_context =
frame_tree_node_->navigator()->GetController()->GetBrowserContext();
StoragePartition* partition = BrowserContext::GetStoragePartition(
browser_context, navigating_frame_host->GetSiteInstance());
DCHECK(partition);
bool can_create_service_worker =
(frame_tree_node_->pending_frame_policy().sandbox_flags &
blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin;
request_params_.should_create_service_worker = can_create_service_worker;
if (can_create_service_worker) {
ServiceWorkerContextWrapper* service_worker_context =
static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
navigation_handle_->InitServiceWorkerHandle(service_worker_context);
}
if (IsSchemeSupportedForAppCache(common_params_.url)) {
if (navigating_frame_host->GetRenderViewHost()
->GetWebkitPreferences()
.application_cache_enabled) {
navigation_handle_->InitAppCacheHandle(
static_cast<ChromeAppCacheService*>(partition->GetAppCacheService()));
}
}
request_params_.navigation_timing.fetch_start = base::TimeTicks::Now();
GURL base_url;
#if defined(OS_ANDROID)
NavigationEntry* last_committed_entry =
frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry();
if (last_committed_entry)
base_url = last_committed_entry->GetBaseURLForDataURL();
#endif
const GURL& top_document_url =
!base_url.is_empty()
? base_url
: frame_tree_node_->frame_tree()->root()->current_url();
// Walk the ancestor chain to determine whether all frames are same-site. If
// not, the |site_for_cookies| is set to an empty URL.
//
// 'Document::SiteForCookies()' in Blink, which special-cases extension
// URLs and a few other sharp edges.
const FrameTreeNode* current = frame_tree_node_->parent();
bool ancestors_are_same_site = true;
while (current && ancestors_are_same_site) {
if (!net::registry_controlled_domains::SameDomainOrHost(
top_document_url, current->current_url(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
ancestors_are_same_site = false;
}
current = current->parent();
}
const GURL& site_for_cookies =
ancestors_are_same_site
? (frame_tree_node_->IsMainFrame() ? common_params_.url
: top_document_url)
: GURL::EmptyGURL();
bool parent_is_main_frame = !frame_tree_node_->parent()
? false
: frame_tree_node_->parent()->IsMainFrame();
std::unique_ptr<NavigationUIData> navigation_ui_data;
if (navigation_handle_->GetNavigationUIData())
navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone();
bool is_for_guests_only =
navigation_handle_->GetStartingSiteInstance()->GetSiteURL().
SchemeIs(kGuestScheme);
bool report_raw_headers = false;
RenderFrameDevToolsAgentHost::ApplyOverrides(
frame_tree_node_, begin_params_.get(), &report_raw_headers);
RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this);
loader_ = NavigationURLLoader::Create(
browser_context->GetResourceContext(), partition,
std::make_unique<NavigationRequestInfo>(
common_params_, begin_params_.Clone(), site_for_cookies,
frame_tree_node_->IsMainFrame(), parent_is_main_frame,
IsSecureFrame(frame_tree_node_->parent()),
frame_tree_node_->frame_tree_node_id(), is_for_guests_only,
report_raw_headers,
navigating_frame_host->GetVisibilityState() ==
blink::mojom::PageVisibilityState::kPrerender,
blob_url_loader_factory_ ? blob_url_loader_factory_->Clone()
: nullptr),
std::move(navigation_ui_data),
navigation_handle_->service_worker_handle(),
navigation_handle_->appcache_handle(), this);
}
| 172,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
return -EPERM;
if (flags && !old_dir->i_op->rename2)
return -EINVAL;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
if (!old_dir->i_op->rename2) {
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry);
} else {
WARN_ON(old_dir->i_op->rename != NULL);
error = old_dir->i_op->rename2(old_dir, old_dentry,
new_dir, new_dentry, flags);
}
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
Commit Message: vfs: rename: check backing inode being equal
If a file is renamed to a hardlink of itself POSIX specifies that rename(2)
should do nothing and return success.
This condition is checked in vfs_rename(). However it won't detect hard
links on overlayfs where these are given separate inodes on the overlayfs
layer.
Overlayfs itself detects this condition and returns success without doing
anything, but then vfs_rename() will proceed as if this was a successful
rename (detach_mounts(), d_move()).
The correct thing to do is to detect this condition before even calling
into overlayfs. This patch does this by calling vfs_select_inode() to get
the underlying inodes.
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v4.2+
CWE ID: CWE-284 | int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
/*
* Check source == target.
* On overlayfs need to look at underlying inodes.
*/
if (vfs_select_inode(old_dentry, 0) == vfs_select_inode(new_dentry, 0))
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
return -EPERM;
if (flags && !old_dir->i_op->rename2)
return -EINVAL;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
if (!old_dir->i_op->rename2) {
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry);
} else {
WARN_ON(old_dir->i_op->rename != NULL);
error = old_dir->i_op->rename2(old_dir, old_dentry,
new_dir, new_dentry, flags);
}
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
| 167,013 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *child_tidptr,
struct pid *pid,
int trace)
{
int retval;
struct task_struct *p;
int cgroup_callbacks_done = 0;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
/*
* Siblings of global init remain as zombies on exit since they are
* not reaped by their parent (swapper). To solve this and to avoid
* multi-rooted process trees, prevent global and container-inits
* from creating siblings.
*/
if ((clone_flags & CLONE_PARENT) &&
current->signal->flags & SIGNAL_UNKILLABLE)
return ERR_PTR(-EINVAL);
retval = security_task_create(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
ftrace_graph_init_task(p);
rt_mutex_init_task(p);
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->real_cred->user->processes) >=
p->signal->rlim[RLIMIT_NPROC].rlim_cur) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->real_cred->user != INIT_USER)
goto bad_fork_free;
}
retval = copy_creds(p, clone_flags);
if (retval < 0)
goto bad_fork_free;
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
retval = -EAGAIN;
if (nr_threads >= max_threads)
goto bad_fork_cleanup_count;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto bad_fork_cleanup_count;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
rcu_copy_process(p);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->gtime = cputime_zero;
p->utimescaled = cputime_zero;
p->stimescaled = cputime_zero;
p->prev_utime = cputime_zero;
p->prev_stime = cputime_zero;
p->default_timer_slack_ns = current->timer_slack_ns;
task_io_accounting_init(&p->ioac);
acct_clear_integrals(p);
posix_cpu_timers_init(p);
p->lock_depth = -1; /* -1 = no lock */
do_posix_clock_monotonic_gettime(&p->start_time);
p->real_start_time = p->start_time;
monotonic_to_bootbased(&p->real_start_time);
p->io_context = NULL;
p->audit_context = NULL;
cgroup_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_dup(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto bad_fork_cleanup_cgroup;
}
mpol_fix_fork_child_flag(p);
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
p->irq_events = 0;
#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p->hardirq_enable_event = 0;
p->hardirq_disable_ip = _THIS_IP_;
p->hardirq_disable_event = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p->softirq_enable_event = 0;
p->softirq_disable_ip = 0;
p->softirq_disable_event = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
p->blocked_on = NULL; /* not blocked yet */
#endif
p->bts = NULL;
p->stack_start = stack_start;
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
retval = perf_event_init_task(p);
if (retval)
goto bad_fork_cleanup_policy;
if ((retval = audit_alloc(p)))
goto bad_fork_cleanup_policy;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto bad_fork_cleanup_audit;
if ((retval = copy_files(clone_flags, p)))
goto bad_fork_cleanup_semundo;
if ((retval = copy_fs(clone_flags, p)))
goto bad_fork_cleanup_files;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto bad_fork_cleanup_sighand;
if ((retval = copy_mm(clone_flags, p)))
goto bad_fork_cleanup_signal;
if ((retval = copy_namespaces(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_io(clone_flags, p)))
goto bad_fork_cleanup_namespaces;
retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto bad_fork_cleanup_io;
if (pid != &init_struct_pid) {
retval = -ENOMEM;
pid = alloc_pid(p->nsproxy->pid_ns);
if (!pid)
goto bad_fork_cleanup_io;
if (clone_flags & CLONE_NEWPID) {
retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);
if (retval < 0)
goto bad_fork_free_pid;
}
}
p->pid = pid_nr(pid);
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if (current->nsproxy != p->nsproxy) {
retval = ns_cgroup_clone(p, pid);
if (retval)
goto bad_fork_free_pid;
}
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
#ifdef CONFIG_FUTEX
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
#endif
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing should be turned off in the child regardless
* of CLONE_PTRACE.
*/
clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
#endif
clear_all_latency_tracing(p);
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
/* Now that the task is set up, run cgroup callbacks if
* necessary. We need to run them before the task is visible
* on the tasklist. */
cgroup_fork_callbacks(p);
cgroup_callbacks_done = 1;
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/*
* The task hasn't been attached yet, so its cpus_allowed mask will
* not be changed, nor will its assigned CPU.
*
* The cpus_allowed mask of the parent may have changed after it was
* copied first time - so re-copy it here, then check the child's CPU
* to ensure it is on a valid CPU (and if not, just force it back to
* parent's CPU). This avoids alot of nasty races.
*/
p->cpus_allowed = current->cpus_allowed;
p->rt.nr_cpus_allowed = current->rt.nr_cpus_allowed;
if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) ||
!cpu_online(task_cpu(p))))
set_task_cpu(p, smp_processor_id());
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
p->real_parent = current->real_parent;
p->parent_exec_id = current->parent_exec_id;
} else {
p->real_parent = current;
p->parent_exec_id = current->self_exec_id;
}
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto bad_fork_free_pid;
}
if (clone_flags & CLONE_THREAD) {
atomic_inc(¤t->signal->count);
atomic_inc(¤t->signal->live);
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
}
if (likely(p->pid)) {
list_add_tail(&p->sibling, &p->real_parent->children);
tracehook_finish_clone(p, clone_flags, trace);
if (thread_group_leader(p)) {
if (clone_flags & CLONE_NEWPID)
p->nsproxy->pid_ns->child_reaper = p;
p->signal->leader_pid = pid;
tty_kref_put(p->signal->tty);
p->signal->tty = tty_kref_get(current->signal->tty);
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
cgroup_post_fork(p);
perf_event_fork(p);
return p;
bad_fork_free_pid:
if (pid != &init_struct_pid)
free_pid(pid);
bad_fork_cleanup_io:
put_io_context(p->io_context);
bad_fork_cleanup_namespaces:
exit_task_namespaces(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
bad_fork_cleanup_signal:
if (!(clone_flags & CLONE_THREAD))
__cleanup_signal(p->signal);
bad_fork_cleanup_sighand:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
bad_fork_cleanup_files:
exit_files(p); /* blocking */
bad_fork_cleanup_semundo:
exit_sem(p);
bad_fork_cleanup_audit:
audit_free(p);
bad_fork_cleanup_policy:
perf_event_free_task(p);
#ifdef CONFIG_NUMA
mpol_put(p->mempolicy);
bad_fork_cleanup_cgroup:
#endif
cgroup_exit(p, cgroup_callbacks_done);
delayacct_tsk_free(p);
module_put(task_thread_info(p)->exec_domain->module);
bad_fork_cleanup_count:
atomic_dec(&p->cred->user->processes);
exit_creds(p);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
Commit Message: block: Fix io_context leak after failure of clone with CLONE_IO
With CLONE_IO, parent's io_context->nr_tasks is incremented, but never
decremented whenever copy_process() fails afterwards, which prevents
exit_io_context() from calling IO schedulers exit functions.
Give a task_struct to exit_io_context(), and call exit_io_context() instead of
put_io_context() in copy_process() cleanup path.
Signed-off-by: Louis Rilling <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-20 | static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *child_tidptr,
struct pid *pid,
int trace)
{
int retval;
struct task_struct *p;
int cgroup_callbacks_done = 0;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
/*
* Siblings of global init remain as zombies on exit since they are
* not reaped by their parent (swapper). To solve this and to avoid
* multi-rooted process trees, prevent global and container-inits
* from creating siblings.
*/
if ((clone_flags & CLONE_PARENT) &&
current->signal->flags & SIGNAL_UNKILLABLE)
return ERR_PTR(-EINVAL);
retval = security_task_create(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
ftrace_graph_init_task(p);
rt_mutex_init_task(p);
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->real_cred->user->processes) >=
p->signal->rlim[RLIMIT_NPROC].rlim_cur) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->real_cred->user != INIT_USER)
goto bad_fork_free;
}
retval = copy_creds(p, clone_flags);
if (retval < 0)
goto bad_fork_free;
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
retval = -EAGAIN;
if (nr_threads >= max_threads)
goto bad_fork_cleanup_count;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto bad_fork_cleanup_count;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
rcu_copy_process(p);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->gtime = cputime_zero;
p->utimescaled = cputime_zero;
p->stimescaled = cputime_zero;
p->prev_utime = cputime_zero;
p->prev_stime = cputime_zero;
p->default_timer_slack_ns = current->timer_slack_ns;
task_io_accounting_init(&p->ioac);
acct_clear_integrals(p);
posix_cpu_timers_init(p);
p->lock_depth = -1; /* -1 = no lock */
do_posix_clock_monotonic_gettime(&p->start_time);
p->real_start_time = p->start_time;
monotonic_to_bootbased(&p->real_start_time);
p->io_context = NULL;
p->audit_context = NULL;
cgroup_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_dup(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto bad_fork_cleanup_cgroup;
}
mpol_fix_fork_child_flag(p);
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
p->irq_events = 0;
#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p->hardirq_enable_event = 0;
p->hardirq_disable_ip = _THIS_IP_;
p->hardirq_disable_event = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p->softirq_enable_event = 0;
p->softirq_disable_ip = 0;
p->softirq_disable_event = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
p->blocked_on = NULL; /* not blocked yet */
#endif
p->bts = NULL;
p->stack_start = stack_start;
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
retval = perf_event_init_task(p);
if (retval)
goto bad_fork_cleanup_policy;
if ((retval = audit_alloc(p)))
goto bad_fork_cleanup_policy;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto bad_fork_cleanup_audit;
if ((retval = copy_files(clone_flags, p)))
goto bad_fork_cleanup_semundo;
if ((retval = copy_fs(clone_flags, p)))
goto bad_fork_cleanup_files;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto bad_fork_cleanup_sighand;
if ((retval = copy_mm(clone_flags, p)))
goto bad_fork_cleanup_signal;
if ((retval = copy_namespaces(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_io(clone_flags, p)))
goto bad_fork_cleanup_namespaces;
retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto bad_fork_cleanup_io;
if (pid != &init_struct_pid) {
retval = -ENOMEM;
pid = alloc_pid(p->nsproxy->pid_ns);
if (!pid)
goto bad_fork_cleanup_io;
if (clone_flags & CLONE_NEWPID) {
retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);
if (retval < 0)
goto bad_fork_free_pid;
}
}
p->pid = pid_nr(pid);
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if (current->nsproxy != p->nsproxy) {
retval = ns_cgroup_clone(p, pid);
if (retval)
goto bad_fork_free_pid;
}
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
#ifdef CONFIG_FUTEX
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
#endif
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing should be turned off in the child regardless
* of CLONE_PTRACE.
*/
clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
#endif
clear_all_latency_tracing(p);
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
/* Now that the task is set up, run cgroup callbacks if
* necessary. We need to run them before the task is visible
* on the tasklist. */
cgroup_fork_callbacks(p);
cgroup_callbacks_done = 1;
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/*
* The task hasn't been attached yet, so its cpus_allowed mask will
* not be changed, nor will its assigned CPU.
*
* The cpus_allowed mask of the parent may have changed after it was
* copied first time - so re-copy it here, then check the child's CPU
* to ensure it is on a valid CPU (and if not, just force it back to
* parent's CPU). This avoids alot of nasty races.
*/
p->cpus_allowed = current->cpus_allowed;
p->rt.nr_cpus_allowed = current->rt.nr_cpus_allowed;
if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) ||
!cpu_online(task_cpu(p))))
set_task_cpu(p, smp_processor_id());
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
p->real_parent = current->real_parent;
p->parent_exec_id = current->parent_exec_id;
} else {
p->real_parent = current;
p->parent_exec_id = current->self_exec_id;
}
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto bad_fork_free_pid;
}
if (clone_flags & CLONE_THREAD) {
atomic_inc(¤t->signal->count);
atomic_inc(¤t->signal->live);
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
}
if (likely(p->pid)) {
list_add_tail(&p->sibling, &p->real_parent->children);
tracehook_finish_clone(p, clone_flags, trace);
if (thread_group_leader(p)) {
if (clone_flags & CLONE_NEWPID)
p->nsproxy->pid_ns->child_reaper = p;
p->signal->leader_pid = pid;
tty_kref_put(p->signal->tty);
p->signal->tty = tty_kref_get(current->signal->tty);
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
cgroup_post_fork(p);
perf_event_fork(p);
return p;
bad_fork_free_pid:
if (pid != &init_struct_pid)
free_pid(pid);
bad_fork_cleanup_io:
if (p->io_context)
exit_io_context(p);
bad_fork_cleanup_namespaces:
exit_task_namespaces(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
bad_fork_cleanup_signal:
if (!(clone_flags & CLONE_THREAD))
__cleanup_signal(p->signal);
bad_fork_cleanup_sighand:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
bad_fork_cleanup_files:
exit_files(p); /* blocking */
bad_fork_cleanup_semundo:
exit_sem(p);
bad_fork_cleanup_audit:
audit_free(p);
bad_fork_cleanup_policy:
perf_event_free_task(p);
#ifdef CONFIG_NUMA
mpol_put(p->mempolicy);
bad_fork_cleanup_cgroup:
#endif
cgroup_exit(p, cgroup_callbacks_done);
delayacct_tsk_free(p);
module_put(task_thread_info(p)->exec_domain->module);
bad_fork_cleanup_count:
atomic_dec(&p->cred->user->processes);
exit_creds(p);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
| 169,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt,
struct nl_info *info)
{
struct rt6_info *iter = NULL;
struct rt6_info **ins;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
ins = &fn->leaf;
for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) {
/*
* Search for duplicates
*/
if (iter->rt6i_metric == rt->rt6i_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
if (replace) {
found++;
break;
}
if (iter->dst.dev == rt->dst.dev &&
iter->rt6i_idev == rt->rt6i_idev &&
ipv6_addr_equal(&iter->rt6i_gateway,
&rt->rt6i_gateway)) {
if (rt->rt6i_nsiblings)
rt->rt6i_nsiblings = 0;
if (!(iter->rt6i_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->rt6i_flags & RTF_EXPIRES))
rt6_clean_expires(iter);
else
rt6_set_expires(iter, rt->dst.expires);
return -EEXIST;
}
/* If we have the same destination and the same metric,
* but not the same gateway, then the route we try to
* add is sibling to this route, increment our counter
* of siblings, and later we will add our route to the
* list.
* Only static routes (which don't have flag
* RTF_EXPIRES) are used for ECMPv6.
*
* To avoid long list, we only had siblings if the
* route have a gateway.
*/
if (rt->rt6i_flags & RTF_GATEWAY &&
!(rt->rt6i_flags & RTF_EXPIRES) &&
!(iter->rt6i_flags & RTF_EXPIRES))
rt->rt6i_nsiblings++;
}
if (iter->rt6i_metric > rt->rt6i_metric)
break;
ins = &iter->dst.rt6_next;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/* Link this route to others same route. */
if (rt->rt6i_nsiblings) {
unsigned int rt6i_nsiblings;
struct rt6_info *sibling, *temp_sibling;
/* Find the first route that have the same metric */
sibling = fn->leaf;
while (sibling) {
if (sibling->rt6i_metric == rt->rt6i_metric) {
list_add_tail(&rt->rt6i_siblings,
&sibling->rt6i_siblings);
break;
}
sibling = sibling->dst.rt6_next;
}
/* For each sibling in the list, increment the counter of
* siblings. BUG() if counters does not match, list of siblings
* is broken!
*/
rt6i_nsiblings = 0;
list_for_each_entry_safe(sibling, temp_sibling,
&rt->rt6i_siblings, rt6i_siblings) {
sibling->rt6i_nsiblings++;
BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings);
rt6i_nsiblings++;
}
BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings);
}
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("NLM_F_CREATE should be set when creating new route\n");
add:
rt->dst.rt6_next = iter;
*ins = rt;
rt->rt6i_node = fn;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
if (!found) {
if (add)
goto add;
pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
*ins = rt;
rt->rt6i_node = fn;
rt->dst.rt6_next = iter->dst.rt6_next;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
rt6_release(iter);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
}
return 0;
}
Commit Message: ipv6: only static routes qualify for equal cost multipathing
Static routes in this case are non-expiring routes which did not get
configured by autoconf or by icmpv6 redirects.
To make sure we actually get an ecmp route while searching for the first
one in this fib6_node's leafs, also make sure it matches the ecmp route
assumptions.
v2:
a) Removed RTF_EXPIRE check in dst.from chain. The check of RTF_ADDRCONF
already ensures that this route, even if added again without
RTF_EXPIRES (in case of a RA announcement with infinite timeout),
does not cause the rt6i_nsiblings logic to go wrong if a later RA
updates the expiration time later.
v3:
a) Allow RTF_EXPIRES routes to enter the ecmp route set. We have to do so,
because an pmtu event could update the RTF_EXPIRES flag and we would
not count this route, if another route joins this set. We now filter
only for RTF_GATEWAY|RTF_ADDRCONF|RTF_DYNAMIC, which are flags that
don't get changed after rt6_info construction.
Cc: Nicolas Dichtel <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt,
struct nl_info *info)
{
struct rt6_info *iter = NULL;
struct rt6_info **ins;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
ins = &fn->leaf;
for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) {
/*
* Search for duplicates
*/
if (iter->rt6i_metric == rt->rt6i_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
if (replace) {
found++;
break;
}
if (iter->dst.dev == rt->dst.dev &&
iter->rt6i_idev == rt->rt6i_idev &&
ipv6_addr_equal(&iter->rt6i_gateway,
&rt->rt6i_gateway)) {
if (rt->rt6i_nsiblings)
rt->rt6i_nsiblings = 0;
if (!(iter->rt6i_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->rt6i_flags & RTF_EXPIRES))
rt6_clean_expires(iter);
else
rt6_set_expires(iter, rt->dst.expires);
return -EEXIST;
}
/* If we have the same destination and the same metric,
* but not the same gateway, then the route we try to
* add is sibling to this route, increment our counter
* of siblings, and later we will add our route to the
* list.
* Only static routes (which don't have flag
* RTF_EXPIRES) are used for ECMPv6.
*
* To avoid long list, we only had siblings if the
* route have a gateway.
*/
if (rt_can_ecmp &&
rt6_qualify_for_ecmp(iter))
rt->rt6i_nsiblings++;
}
if (iter->rt6i_metric > rt->rt6i_metric)
break;
ins = &iter->dst.rt6_next;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/* Link this route to others same route. */
if (rt->rt6i_nsiblings) {
unsigned int rt6i_nsiblings;
struct rt6_info *sibling, *temp_sibling;
/* Find the first route that have the same metric */
sibling = fn->leaf;
while (sibling) {
if (sibling->rt6i_metric == rt->rt6i_metric &&
rt6_qualify_for_ecmp(sibling)) {
list_add_tail(&rt->rt6i_siblings,
&sibling->rt6i_siblings);
break;
}
sibling = sibling->dst.rt6_next;
}
/* For each sibling in the list, increment the counter of
* siblings. BUG() if counters does not match, list of siblings
* is broken!
*/
rt6i_nsiblings = 0;
list_for_each_entry_safe(sibling, temp_sibling,
&rt->rt6i_siblings, rt6i_siblings) {
sibling->rt6i_nsiblings++;
BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings);
rt6i_nsiblings++;
}
BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings);
}
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("NLM_F_CREATE should be set when creating new route\n");
add:
rt->dst.rt6_next = iter;
*ins = rt;
rt->rt6i_node = fn;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
if (!found) {
if (add)
goto add;
pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
*ins = rt;
rt->rt6i_node = fn;
rt->dst.rt6_next = iter->dst.rt6_next;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
rt6_release(iter);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
}
return 0;
}
| 166,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13037/IP: Add bounds checks when printing time stamp options.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
if (ip_printts(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::ContentEncoding()
: compression_entries_(NULL),
compression_entries_end_(NULL),
encryption_entries_(NULL),
encryption_entries_end_(NULL),
encoding_order_(0),
encoding_scope_(1),
encoding_type_(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 | ContentEncoding::ContentEncoding()
: compression_entries_(NULL),
compression_entries_end_(NULL),
encryption_entries_(NULL),
encryption_entries_end_(NULL),
encoding_order_(0),
encoding_scope_(1),
| 174,251 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
buffer_put_cstring(&m, authctxt->user);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
CWE ID: CWE-20 | mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
| 166,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mp_dss_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_dss *mdss = (const struct mp_dss *) opt;
if ((opt_len != mp_dss_len(mdss, 1) &&
opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN)
return 0;
if (mdss->flags & MP_DSS_F)
ND_PRINT((ndo, " fin"));
opt += 4;
if (mdss->flags & MP_DSS_A) {
ND_PRINT((ndo, " ack "));
if (mdss->flags & MP_DSS_a) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
}
if (mdss->flags & MP_DSS_M) {
ND_PRINT((ndo, " seq "));
if (mdss->flags & MP_DSS_m) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
opt += 4;
ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
opt += 2;
if (opt_len == mp_dss_len(mdss, 1))
ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
}
return 1;
}
Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption.
Do the length checking inline; that means we print stuff up to the point
at which we run out of option data.
First check to make sure we have at least 4 bytes of option, so we have
flags to check.
This fixes a buffer over-read discovered by Kim Gwan Yeong.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | mp_dss_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_dss *mdss = (const struct mp_dss *) opt;
/* We need the flags, at a minimum. */
if (opt_len < 4)
return 0;
if (flags & TH_SYN)
return 0;
if (mdss->flags & MP_DSS_F)
ND_PRINT((ndo, " fin"));
opt += 4;
opt_len -= 4;
if (mdss->flags & MP_DSS_A) {
/* Ack present */
ND_PRINT((ndo, " ack "));
/*
* If the a flag is set, we have an 8-byte ack; if it's
* clear, we have a 4-byte ack.
*/
if (mdss->flags & MP_DSS_a) {
if (opt_len < 8)
return 0;
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
opt_len -= 8;
} else {
if (opt_len < 4)
return 0;
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
}
}
if (mdss->flags & MP_DSS_M) {
/*
* Data Sequence Number (DSN), Subflow Sequence Number (SSN),
* Data-Level Length present, and Checksum possibly present.
*/
ND_PRINT((ndo, " seq "));
/*
* If the m flag is set, we have an 8-byte NDS; if it's clear,
* we have a 4-byte DSN.
*/
if (mdss->flags & MP_DSS_m) {
if (opt_len < 8)
return 0;
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
opt_len -= 8;
} else {
if (opt_len < 4)
return 0;
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
}
if (opt_len < 4)
return 0;
ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
opt += 4;
opt_len -= 4;
if (opt_len < 2)
return 0;
ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
opt += 2;
opt_len -= 2;
/*
* The Checksum is present only if negotiated.
* If there are at least 2 bytes left, process the next 2
* bytes as the Checksum.
*/
if (opt_len >= 2) {
ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
opt_len -= 2;
}
}
if (opt_len != 0)
return 0;
return 1;
}
| 167,837 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT("
<< GLES2Util::GetStringQueryTarget(target) << ", " << id
<< ")");
switch (target) {
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_COMPLETED_CHROMIUM:
if (!capabilities_.sync_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for commands completed queries");
return;
}
break;
case GL_SAMPLES_PASSED_ARB:
if (!capabilities_.occlusion_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for occlusion queries");
return;
}
break;
case GL_ANY_SAMPLES_PASSED:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
if (!capabilities_.occlusion_query_boolean) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for boolean occlusion queries");
return;
}
break;
case GL_TIME_ELAPSED_EXT:
if (!capabilities_.timer_queries) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for timing queries");
return;
}
break;
case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
if (capabilities_.major_version >= 3)
break;
FALLTHROUGH;
default:
SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target");
return;
}
if (query_tracker_->GetCurrentQuery(target)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"query already in progress");
return;
}
if (id == 0) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0");
return;
}
if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id");
return;
}
switch (target) {
case GL_TIME_ELAPSED_EXT:
if (!query_tracker_->SetDisjointSync(this)) {
SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT",
"buffer allocation failed");
return;
}
break;
default:
break;
}
if (query_tracker_->BeginQuery(id, target, this))
CheckGLError();
if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) {
AllocateShadowCopiesForReadback();
}
}
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 GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT("
<< GLES2Util::GetStringQueryTarget(target) << ", " << id
<< ")");
switch (target) {
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_COMPLETED_CHROMIUM:
if (!capabilities_.sync_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for commands completed queries");
return;
}
break;
case GL_SAMPLES_PASSED_ARB:
if (!capabilities_.occlusion_query) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for occlusion queries");
return;
}
break;
case GL_ANY_SAMPLES_PASSED:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
if (!capabilities_.occlusion_query_boolean) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for boolean occlusion queries");
return;
}
break;
case GL_TIME_ELAPSED_EXT:
if (!capabilities_.timer_queries) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"not enabled for timing queries");
return;
}
break;
case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
if (capabilities_.major_version >= 3)
break;
FALLTHROUGH;
default:
SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target");
return;
}
if (query_tracker_->GetCurrentQuery(target)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT",
"query already in progress");
return;
}
if (id == 0) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0");
return;
}
if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id");
return;
}
switch (target) {
case GL_TIME_ELAPSED_EXT:
if (!query_tracker_->SetDisjointSync(this)) {
SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT",
"buffer allocation failed");
return;
}
break;
default:
break;
}
if (query_tracker_->BeginQuery(id, target, this))
CheckGLError();
if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) {
AllocateShadowCopiesForReadback();
}
}
| 172,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
avpriv_request_sample(track->par, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
} else {
if (hdr->substreamid != 0) {
avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
Commit Message: avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample
Fixes: out of array read
Fixes: ffmpeg_crash_8.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
avpriv_request_sample(mov->fc, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
} else {
if (hdr->substreamid != 0) {
avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
| 169,162 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
pipe_.Close();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
| 171,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: EAS_RESULT DLSParser (EAS_HW_DATA_HANDLE hwInstData, EAS_FILE_HANDLE fileHandle, EAS_I32 offset, EAS_DLSLIB_HANDLE *ppDLS)
{
EAS_RESULT result;
SDLS_SYNTHESIZER_DATA dls;
EAS_U32 temp;
EAS_I32 pos;
EAS_I32 chunkPos;
EAS_I32 size;
EAS_I32 instSize;
EAS_I32 rgnPoolSize;
EAS_I32 artPoolSize;
EAS_I32 waveLenSize;
EAS_I32 endDLS;
EAS_I32 wvplPos;
EAS_I32 wvplSize;
EAS_I32 linsPos;
EAS_I32 linsSize;
EAS_I32 ptblPos;
EAS_I32 ptblSize;
void *p;
/* zero counts and pointers */
EAS_HWMemSet(&dls, 0, sizeof(dls));
/* save file handle and hwInstData to save copying pointers around */
dls.hwInstData = hwInstData;
dls.fileHandle = fileHandle;
/* NULL return value in case of error */
*ppDLS = NULL;
/* seek to start of DLS and read in RIFF tag and set processor endian flag */
if ((result = EAS_HWFileSeek(dls.hwInstData, dls.fileHandle, offset)) != EAS_SUCCESS)
return result;
if ((result = EAS_HWReadFile(dls.hwInstData, dls.fileHandle, &temp, sizeof(temp), &size)) != EAS_SUCCESS)
return result;
/* check for processor endian-ness */
dls.bigEndian = (temp == CHUNK_RIFF);
/* first chunk should be DLS */
pos = offset;
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
if (temp != CHUNK_DLS)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Expected DLS chunk, got %08lx\n", temp); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* no instrument or wavepool chunks */
linsSize = wvplSize = ptblSize = linsPos = wvplPos = ptblPos = 0;
/* scan the chunks in the DLS list */
endDLS = offset + size;
pos = offset + 12;
while (pos < endDLS)
{
chunkPos = pos;
/* get the next chunk type */
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_CDL:
if ((result = Parse_cdl(&dls, size, &temp)) != EAS_SUCCESS)
return result;
if (!temp)
return EAS_ERROR_UNRECOGNIZED_FORMAT;
break;
case CHUNK_LINS:
linsPos = chunkPos + 12;
linsSize = size - 4;
break;
case CHUNK_WVPL:
wvplPos = chunkPos + 12;
wvplSize = size - 4;
break;
case CHUNK_PTBL:
ptblPos = chunkPos + 8;
ptblSize = size - 4;
break;
default:
break;
}
}
/* must have a lins chunk */
if (linsSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No lins chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a wvpl chunk */
if (wvplSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No wvpl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a ptbl chunk */
if ((ptblSize == 0) || (ptblSize > DLS_MAX_WAVE_COUNT * sizeof(POOLCUE) + sizeof(POOLTABLE)))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No ptbl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* pre-parse the wave pool chunk */
if ((result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize)) != EAS_SUCCESS)
return result;
/* limit check */
if ((dls.waveCount == 0) || (dls.waveCount > DLS_MAX_WAVE_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #waves [%u]\n", dls.waveCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* allocate memory for wsmp data */
dls.wsmpData = EAS_HWMalloc(dls.hwInstData, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
if (dls.wsmpData == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc for wsmp data failed\n"); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.wsmpData, 0, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
/* pre-parse the lins chunk */
result = Parse_lins(&dls, linsPos, linsSize);
if (result == EAS_SUCCESS)
{
/* limit check */
if ((dls.regionCount == 0) || (dls.regionCount > DLS_MAX_REGION_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #regions [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.artCount == 0) || (dls.artCount > DLS_MAX_ART_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #articulations [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.instCount == 0) || (dls.instCount > DLS_MAX_INST_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #instruments [%u]\n", dls.instCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* Allocate memory for the converted DLS data */
/* calculate size of instrument data */
instSize = (EAS_I32) (sizeof(S_PROGRAM) * dls.instCount);
/* calculate size of region pool */
rgnPoolSize = (EAS_I32) (sizeof(S_DLS_REGION) * dls.regionCount);
/* calculate size of articulation pool, add one for default articulation */
dls.artCount++;
artPoolSize = (EAS_I32) (sizeof(S_DLS_ARTICULATION) * dls.artCount);
/* calculate size of wave length and offset arrays */
waveLenSize = (EAS_I32) (dls.waveCount * sizeof(EAS_U32));
/* calculate final memory size */
size = (EAS_I32) sizeof(S_EAS) + instSize + rgnPoolSize + artPoolSize + (2 * waveLenSize) + (EAS_I32) dls.wavePoolSize;
if (size <= 0) {
return EAS_ERROR_FILE_FORMAT;
}
/* allocate the main EAS chunk */
dls.pDLS = EAS_HWMalloc(dls.hwInstData, size);
if (dls.pDLS == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc failed for DLS memory allocation size %ld\n", size); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.pDLS, 0, size);
dls.pDLS->refCount = 1;
p = PtrOfs(dls.pDLS, sizeof(S_EAS));
/* setup pointer to programs */
dls.pDLS->numDLSPrograms = (EAS_U16) dls.instCount;
dls.pDLS->pDLSPrograms = p;
p = PtrOfs(p, instSize);
/* setup pointer to regions */
dls.pDLS->pDLSRegions = p;
dls.pDLS->numDLSRegions = (EAS_U16) dls.regionCount;
p = PtrOfs(p, rgnPoolSize);
/* setup pointer to articulations */
dls.pDLS->numDLSArticulations = (EAS_U16) dls.artCount;
dls.pDLS->pDLSArticulations = p;
p = PtrOfs(p, artPoolSize);
/* setup pointer to wave length table */
dls.pDLS->numDLSSamples = (EAS_U16) dls.waveCount;
dls.pDLS->pDLSSampleLen = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave offsets table */
dls.pDLS->pDLSSampleOffsets = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave pool */
dls.pDLS->pDLSSamples = p;
/* clear filter flag */
dls.filterUsed = EAS_FALSE;
/* parse the wave pool and load samples */
result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize);
}
/* create the default articulation */
Convert_art(&dls, &defaultArt, 0);
dls.artCount = 1;
/* parse the lins chunk and load instruments */
dls.regionCount = dls.instCount = 0;
if (result == EAS_SUCCESS)
result = Parse_lins(&dls, linsPos, linsSize);
/* clean up any temporary objects that were allocated */
if (dls.wsmpData)
EAS_HWFree(dls.hwInstData, dls.wsmpData);
/* if successful, return a pointer to the EAS collection */
if (result == EAS_SUCCESS)
{
*ppDLS = dls.pDLS;
#ifdef _DEBUG_DLS
DumpDLS(dls.pDLS);
#endif
}
/* something went wrong, deallocate the EAS collection */
else
DLSCleanup(dls.hwInstData, dls.pDLS);
return result;
}
Commit Message: Fix NULL pointer dereference
Bug: 29770686
Bug: 23304983
Change-Id: I1648aab90bc281702a00744bf884ae8bb8009412
CWE ID: CWE-284 | EAS_RESULT DLSParser (EAS_HW_DATA_HANDLE hwInstData, EAS_FILE_HANDLE fileHandle, EAS_I32 offset, EAS_DLSLIB_HANDLE *ppDLS)
{
EAS_RESULT result;
SDLS_SYNTHESIZER_DATA dls;
EAS_U32 temp;
EAS_I32 pos;
EAS_I32 chunkPos;
EAS_I32 size;
EAS_I32 instSize;
EAS_I32 rgnPoolSize;
EAS_I32 artPoolSize;
EAS_I32 waveLenSize;
EAS_I32 endDLS;
EAS_I32 wvplPos;
EAS_I32 wvplSize;
EAS_I32 linsPos;
EAS_I32 linsSize;
EAS_I32 ptblPos;
EAS_I32 ptblSize;
void *p;
/* zero counts and pointers */
EAS_HWMemSet(&dls, 0, sizeof(dls));
/* save file handle and hwInstData to save copying pointers around */
dls.hwInstData = hwInstData;
dls.fileHandle = fileHandle;
/* NULL return value in case of error */
*ppDLS = NULL;
/* seek to start of DLS and read in RIFF tag and set processor endian flag */
if ((result = EAS_HWFileSeek(dls.hwInstData, dls.fileHandle, offset)) != EAS_SUCCESS)
return result;
if ((result = EAS_HWReadFile(dls.hwInstData, dls.fileHandle, &temp, sizeof(temp), &size)) != EAS_SUCCESS)
return result;
/* check for processor endian-ness */
dls.bigEndian = (temp == CHUNK_RIFF);
/* first chunk should be DLS */
pos = offset;
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
if (temp != CHUNK_DLS)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Expected DLS chunk, got %08lx\n", temp); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* no instrument or wavepool chunks */
linsSize = wvplSize = ptblSize = linsPos = wvplPos = ptblPos = 0;
/* scan the chunks in the DLS list */
endDLS = offset + size;
pos = offset + 12;
while (pos < endDLS)
{
chunkPos = pos;
/* get the next chunk type */
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_CDL:
if ((result = Parse_cdl(&dls, size, &temp)) != EAS_SUCCESS)
return result;
if (!temp)
return EAS_ERROR_UNRECOGNIZED_FORMAT;
break;
case CHUNK_LINS:
linsPos = chunkPos + 12;
linsSize = size - 4;
break;
case CHUNK_WVPL:
wvplPos = chunkPos + 12;
wvplSize = size - 4;
break;
case CHUNK_PTBL:
ptblPos = chunkPos + 8;
ptblSize = size - 4;
break;
default:
break;
}
}
/* must have a lins chunk */
if (linsSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No lins chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a wvpl chunk */
if (wvplSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No wvpl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a ptbl chunk */
if ((ptblSize == 0) || (ptblSize > DLS_MAX_WAVE_COUNT * sizeof(POOLCUE) + sizeof(POOLTABLE)))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No ptbl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* pre-parse the wave pool chunk */
if ((result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize)) != EAS_SUCCESS)
return result;
/* limit check */
if ((dls.waveCount == 0) || (dls.waveCount > DLS_MAX_WAVE_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #waves [%u]\n", dls.waveCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* allocate memory for wsmp data */
dls.wsmpData = EAS_HWMalloc(dls.hwInstData, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
if (dls.wsmpData == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc for wsmp data failed\n"); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.wsmpData, 0, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
/* pre-parse the lins chunk */
result = Parse_lins(&dls, linsPos, linsSize);
if (result == EAS_SUCCESS)
{
/* limit check */
if ((dls.regionCount == 0) || (dls.regionCount > DLS_MAX_REGION_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #regions [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.artCount == 0) || (dls.artCount > DLS_MAX_ART_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #articulations [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.instCount == 0) || (dls.instCount > DLS_MAX_INST_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #instruments [%u]\n", dls.instCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* Allocate memory for the converted DLS data */
/* calculate size of instrument data */
instSize = (EAS_I32) (sizeof(S_PROGRAM) * dls.instCount);
/* calculate size of region pool */
rgnPoolSize = (EAS_I32) (sizeof(S_DLS_REGION) * dls.regionCount);
/* calculate size of articulation pool, add one for default articulation */
dls.artCount++;
artPoolSize = (EAS_I32) (sizeof(S_DLS_ARTICULATION) * dls.artCount);
/* calculate size of wave length and offset arrays */
waveLenSize = (EAS_I32) (dls.waveCount * sizeof(EAS_U32));
/* calculate final memory size */
size = (EAS_I32) sizeof(S_EAS) + instSize + rgnPoolSize + artPoolSize + (2 * waveLenSize) + (EAS_I32) dls.wavePoolSize;
if (size <= 0) {
return EAS_ERROR_FILE_FORMAT;
}
/* allocate the main EAS chunk */
dls.pDLS = EAS_HWMalloc(dls.hwInstData, size);
if (dls.pDLS == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc failed for DLS memory allocation size %ld\n", size); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.pDLS, 0, size);
dls.pDLS->refCount = 1;
p = PtrOfs(dls.pDLS, sizeof(S_EAS));
/* setup pointer to programs */
dls.pDLS->numDLSPrograms = (EAS_U16) dls.instCount;
dls.pDLS->pDLSPrograms = p;
p = PtrOfs(p, instSize);
/* setup pointer to regions */
dls.pDLS->pDLSRegions = p;
dls.pDLS->numDLSRegions = (EAS_U16) dls.regionCount;
p = PtrOfs(p, rgnPoolSize);
/* setup pointer to articulations */
dls.pDLS->numDLSArticulations = (EAS_U16) dls.artCount;
dls.pDLS->pDLSArticulations = p;
p = PtrOfs(p, artPoolSize);
/* setup pointer to wave length table */
dls.pDLS->numDLSSamples = (EAS_U16) dls.waveCount;
dls.pDLS->pDLSSampleLen = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave offsets table */
dls.pDLS->pDLSSampleOffsets = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave pool */
dls.pDLS->pDLSSamples = p;
/* clear filter flag */
dls.filterUsed = EAS_FALSE;
/* parse the wave pool and load samples */
result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize);
}
/* create the default articulation */
if (dls.pDLS) {
Convert_art(&dls, &defaultArt, 0);
dls.artCount = 1;
}
/* parse the lins chunk and load instruments */
dls.regionCount = dls.instCount = 0;
if (result == EAS_SUCCESS)
result = Parse_lins(&dls, linsPos, linsSize);
/* clean up any temporary objects that were allocated */
if (dls.wsmpData)
EAS_HWFree(dls.hwInstData, dls.wsmpData);
/* if successful, return a pointer to the EAS collection */
if (result == EAS_SUCCESS)
{
*ppDLS = dls.pDLS;
#ifdef _DEBUG_DLS
DumpDLS(dls.pDLS);
#endif
}
/* something went wrong, deallocate the EAS collection */
else
DLSCleanup(dls.hwInstData, dls.pDLS);
return result;
}
| 173,412 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Block::GetDiscardPadding() const
{
return m_discard_padding;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Block::GetDiscardPadding() const
| 174,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(CachedResourceType(cached_resource));
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(ToResourceType(cached_resource.GetType()));
}
| 172,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_recv_plaintext(int sock)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = 512;
buf = calloc(1, chunk_size);
while (1) {
errno = 0;
rc = read(sock, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
if (errno == EINTR || errno == EAGAIN) {
crm_trace("Retry: %d", (int)rc);
if (rc > 0) {
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
}
} else if (rc < 0) {
crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_recv_plaintext(int sock)
/*!
* \internal
* \brief Read bytes off non blocking socket.
*
* \param session - tls session to read
* \param max_size - max bytes allowed to read for buffer. 0 assumes no limit
*
* \note only use with NON-Blocking sockets. Should only be used after polling socket.
* This function will return once max_size is met, the socket read buffer
* is empty, or an error is encountered.
*
* \retval '\0' terminated buffer on success
*/
static char *
crm_recv_plaintext(int sock, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (sock <= 0) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
errno = 0;
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = read(sock, buf + len, chunk_size);
if (rc > 0) {
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
if (rc > 0) {
continue;
} else if (rc == 0) {
if (disconnected) {
*disconnected = 1;
}
crm_trace("EOF encoutered during read");
goto done;
}
/* process errors */
if (errno == EINTR) {
crm_trace("EINTER encoutered, retry socket read.");
} else if (errno == EAGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (errno <= 0) {
if (disconnected) {
*disconnected = 1;
}
crm_debug("Error receiving message: %d", (int)rc);
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), FALSE, __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
| 170,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
&delegate_,
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399 | PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
delegate_.AsWeakPtr(),
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
| 171,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: void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId);
outHeader->nTimeStamp = header->nTimeStamp;
outHeader->nFlags = header->nFlags;
outHeader->nFilledLen = mWidth * mHeight * 3 / 2;
uint8_t *dst = outHeader->pBuffer + outHeader->nOffset;
const uint8_t *srcY = data;
const uint8_t *srcU = srcY + mWidth * mHeight;
const uint8_t *srcV = srcU + mWidth * mHeight / 4;
size_t srcYStride = mWidth;
size_t srcUStride = mWidth / 2;
size_t srcVStride = srcUStride;
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
mPicToHeaderMap.removeItem(picId);
delete header;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) {
bool SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
OMX_U32 frameSize = mWidth * mHeight * 3 / 2;
if (outHeader->nAllocLen - outHeader->nOffset < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
return false;
}
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId);
outHeader->nTimeStamp = header->nTimeStamp;
outHeader->nFlags = header->nFlags;
outHeader->nFilledLen = frameSize;
uint8_t *dst = outHeader->pBuffer + outHeader->nOffset;
const uint8_t *srcY = data;
const uint8_t *srcU = srcY + mWidth * mHeight;
const uint8_t *srcV = srcU + mWidth * mHeight / 4;
size_t srcYStride = mWidth;
size_t srcUStride = mWidth / 2;
size_t srcVStride = srcUStride;
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
mPicToHeaderMap.removeItem(picId);
delete header;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return true;
}
| 174,177 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
swapl(&stuff->numSpecs);
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
Commit Message:
CWE ID: CWE-20 | SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
swapl(&stuff->numSpecs);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
| 165,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel,
int gpu_host_id) {
surface_route_id_ = params_in_pixel.route_id;
if (params_in_pixel.protection_state_id &&
params_in_pixel.protection_state_id != protection_state_id_) {
DCHECK(!current_surface_);
if (!params_in_pixel.skip_ack)
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL);
return;
}
if (ShouldFastACK(params_in_pixel.surface_handle)) {
if (!params_in_pixel.skip_ack)
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL);
return;
}
current_surface_ = params_in_pixel.surface_handle;
if (!params_in_pixel.skip_ack)
released_front_lock_ = NULL;
UpdateExternalTexture();
ui::Compositor* compositor = GetCompositor();
if (!compositor) {
if (!params_in_pixel.skip_ack)
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL);
} else {
DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) !=
image_transport_clients_.end());
gfx::Size surface_size_in_pixel =
image_transport_clients_[params_in_pixel.surface_handle]->size();
gfx::Size surface_size = ConvertSizeToDIP(this, surface_size_in_pixel);
window_->SchedulePaintInRect(gfx::Rect(surface_size));
if (!params_in_pixel.skip_ack) {
can_lock_compositor_ = NO_PENDING_COMMIT;
on_compositing_did_commit_callbacks_.push_back(
base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK,
params_in_pixel.route_id,
gpu_host_id,
true));
if (!compositor->HasObserver(this))
compositor->AddObserver(this);
}
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped(
bool RenderWidgetHostViewAura::SwapBuffersPrepare(
const gfx::Rect& surface_rect,
const gfx::Rect& damage_rect,
BufferPresentedParams* params) {
DCHECK(params->surface_handle);
DCHECK(!params->texture_to_produce);
if (last_swapped_surface_size_ != surface_rect.size()) {
// The surface could have shrunk since we skipped an update, in which
// case we can expect a full update.
DLOG_IF(ERROR, damage_rect != surface_rect) << "Expected full damage rect";
skipped_damage_.setEmpty();
last_swapped_surface_size_ = surface_rect.size();
}
if (ShouldSkipFrame(surface_rect.size())) {
skipped_damage_.op(RectToSkIRect(damage_rect), SkRegion::kUnion_Op);
InsertSyncPointAndACK(*params);
return false;
}
DCHECK(!current_surface_ || image_transport_clients_.find(current_surface_) !=
image_transport_clients_.end());
if (current_surface_)
params->texture_to_produce = image_transport_clients_[current_surface_];
std::swap(current_surface_, params->surface_handle);
DCHECK(image_transport_clients_.find(current_surface_) !=
image_transport_clients_.end());
image_transport_clients_[current_surface_]->Consume(surface_rect.size());
released_front_lock_ = NULL;
UpdateExternalTexture();
return true;
}
void RenderWidgetHostViewAura::SwapBuffersCompleted(
const BufferPresentedParams& params) {
ui::Compositor* compositor = GetCompositor();
if (!compositor) {
InsertSyncPointAndACK(params);
} else {
// Add sending an ACK to the list of things to do OnCompositingDidCommit
can_lock_compositor_ = NO_PENDING_COMMIT;
on_compositing_did_commit_callbacks_.push_back(
base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params));
if (!compositor->HasObserver(this))
compositor->AddObserver(this);
}
}
void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel,
int gpu_host_id) {
const gfx::Rect surface_rect = gfx::Rect(gfx::Point(), params_in_pixel.size);
BufferPresentedParams ack_params(
params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle);
if (!SwapBuffersPrepare(surface_rect, surface_rect, &ack_params))
return;
previous_damage_.setRect(RectToSkIRect(surface_rect));
skipped_damage_.setEmpty();
ui::Compositor* compositor = GetCompositor();
if (compositor) {
gfx::Size surface_size = ConvertSizeToDIP(this, params_in_pixel.size);
window_->SchedulePaintInRect(gfx::Rect(surface_size));
}
SwapBuffersCompleted(ack_params);
}
| 171,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 const char *parse_object( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '{' ) {
/* Not an object! */
ep = value;
return 0;
}
item->type = cJSON_Object;
value =skip( value + 1 );
if ( *value == '}' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0;
if ( ! ( value = skip( parse_string( child, skip( value ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_string( child, skip( value + 1 ) ) ) ) )
return 0;
child->string = child->valuestring;
child->valuestring = 0;
if ( *value != ':' ) {
/* Fail! */
ep = value;
return 0;
}
if ( ! ( value = skip( parse_value( child, skip( value + 1 ) ) ) ) )
return 0;
}
if ( *value == '}' )
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static const char *parse_object( cJSON *item, const char *value )
static const char *parse_object(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='{') {*ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
}
| 167,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
int ret;
ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0,
indx, data, size, 1000);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
return ret;
}
Commit Message: pegasus: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
References: https://bugs.debian.org/852556
Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
u8 *buf;
int ret;
buf = kmalloc(size, GFP_NOIO);
if (!buf)
return -ENOMEM;
ret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0,
indx, buf, size, 1000);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
else if (ret <= size)
memcpy(data, buf, ret);
kfree(buf);
return ret;
}
| 168,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
int tmp;
if (copy_from_user(buf, buffer, count))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
Commit Message: uml: check length in exitcode_proc_write()
We don't cap the size of buffer from the user so we could write past the
end of the array here. Only root can write to this file.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
size_t size;
int tmp;
size = min(count, sizeof(buf));
if (copy_from_user(buf, buffer, size))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
| 165,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
Commit Message: fixed out of bounds access of ASN.1 Bitstring
Credit to OSS-Fuzz
CWE ID: CWE-119 | static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int i, count = 0;
int zero_bits;
size_t octets_left;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
zero_bits = *in & 0x07;
octets_left = inlen - 1;
in++;
memset(outbuf, 0, outlen);
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
| 169,515 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const AXObject* AXObject::disabledAncestor() const {
const AtomicString& disabled = getAttribute(aria_disabledAttr);
if (equalIgnoringCase(disabled, "true"))
return this;
if (equalIgnoringCase(disabled, "false"))
return 0;
if (AXObject* parent = parentObject())
return parent->disabledAncestor();
return 0;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | const AXObject* AXObject::disabledAncestor() const {
const AtomicString& disabled = getAttribute(aria_disabledAttr);
if (equalIgnoringASCIICase(disabled, "true"))
return this;
if (equalIgnoringASCIICase(disabled, "false"))
return 0;
if (AXObject* parent = parentObject())
return parent->disabledAncestor();
return 0;
}
| 171,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,
MagickMax(Ar_image->columns,Cr_image->columns),1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,
MagickMax(Ai_image->columns,Ci_image->columns),1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,
MagickMax(Br_image->columns,Cr_image->columns),1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,
MagickMax(Bi_image->columns,Ci_image->columns),1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595
CWE ID: CWE-119 | MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
| 170,199 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool tailmatch(const char *little, const char *bigone)
{
size_t littlelen = strlen(little);
size_t biglen = strlen(bigone);
if(littlelen > biglen)
return FALSE;
return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE;
}
Commit Message: cookie: fix tailmatching to prevent cross-domain leakage
Cookies set for 'example.com' could accidentaly also be sent by libcurl
to the 'bexample.com' (ie with a prefix to the first domain name).
This is a security vulnerabilty, CVE-2013-1944.
Bug: http://curl.haxx.se/docs/adv_20130412.html
CWE ID: CWE-200 | static bool tailmatch(const char *little, const char *bigone)
static bool tailmatch(const char *cooke_domain, const char *hostname)
{
size_t cookie_domain_len = strlen(cooke_domain);
size_t hostname_len = strlen(hostname);
if(hostname_len < cookie_domain_len)
return FALSE;
if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len))
return FALSE;
/* A lead char of cookie_domain is not '.'.
RFC6265 4.1.2.3. The Domain Attribute says:
For example, if the value of the Domain attribute is
"example.com", the user agent will include the cookie in the Cookie
header when making HTTP requests to example.com, www.example.com, and
www.corp.example.com.
*/
if(hostname_len == cookie_domain_len)
return TRUE;
if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
return TRUE;
return FALSE;
}
| 166,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int command_read(struct pci_dev *dev, int offset, u16 *value, void *data)
{
int i;
int ret;
ret = xen_pcibk_read_config_word(dev, offset, value, data);
if (!pci_is_enabled(dev))
return ret;
for (i = 0; i < PCI_ROM_RESOURCE; i++) {
if (dev->resource[i].flags & IORESOURCE_IO)
*value |= PCI_COMMAND_IO;
if (dev->resource[i].flags & IORESOURCE_MEM)
*value |= PCI_COMMAND_MEMORY;
}
return ret;
}
Commit Message: xen-pciback: limit guest control of command register
Otherwise the guest can abuse that control to cause e.g. PCIe
Unsupported Request responses by disabling memory and/or I/O decoding
and subsequently causing (CPU side) accesses to the respective address
ranges, which (depending on system configuration) may be fatal to the
host.
Note that to alter any of the bits collected together as
PCI_COMMAND_GUEST permissive mode is now required to be enabled
globally or on the specific device.
This is CVE-2015-2150 / XSA-120.
Signed-off-by: Jan Beulich <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Cc: <[email protected]>
Signed-off-by: David Vrabel <[email protected]>
CWE ID: CWE-264 | static int command_read(struct pci_dev *dev, int offset, u16 *value, void *data)
/* Bits guests are allowed to control in permissive mode. */
#define PCI_COMMAND_GUEST (PCI_COMMAND_MASTER|PCI_COMMAND_SPECIAL| \
PCI_COMMAND_INVALIDATE|PCI_COMMAND_VGA_PALETTE| \
PCI_COMMAND_WAIT|PCI_COMMAND_FAST_BACK)
static void *command_init(struct pci_dev *dev, int offset)
{
struct pci_cmd_info *cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
int err;
if (!cmd)
return ERR_PTR(-ENOMEM);
err = pci_read_config_word(dev, PCI_COMMAND, &cmd->val);
if (err) {
kfree(cmd);
return ERR_PTR(err);
}
return cmd;
}
static int command_read(struct pci_dev *dev, int offset, u16 *value, void *data)
{
int ret = pci_read_config_word(dev, offset, value);
const struct pci_cmd_info *cmd = data;
*value &= PCI_COMMAND_GUEST;
*value |= cmd->val & ~PCI_COMMAND_GUEST;
return ret;
}
| 166,682 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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 | void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 4x4 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn,
unsigned long size)
{
gfn_t end_gfn;
pfn_t pfn;
pfn = gfn_to_pfn_memslot(slot, gfn);
end_gfn = gfn + (size >> PAGE_SHIFT);
gfn += 1;
if (is_error_noslot_pfn(pfn))
return pfn;
while (gfn < end_gfn)
gfn_to_pfn_memslot(slot, gfn++);
return pfn;
}
Commit Message: kvm: fix excessive pages un-pinning in kvm_iommu_map error path.
The third parameter of kvm_unpin_pages() when called from
kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin
and not the page size.
This error was facilitated with an inconsistent API: kvm_pin_pages() takes
a size, but kvn_unpin_pages() takes a number of pages, so fix the problem
by matching the two.
This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter
of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of
un-pinning for pages intended to be un-pinned (i.e. memory leak) but
unfortunately potentially aggravated the number of pages we un-pin that
should have stayed pinned. As far as I understand though, the same
practical mitigations apply.
This issue was found during review of Red Hat 6.6 patches to prepare
Ksplice rebootless updates.
Thanks to Vegard for his time on a late Friday evening to help me in
understanding this code.
Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)")
Cc: [email protected]
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Signed-off-by: Jamie Iles <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189 | static pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn,
unsigned long npages)
{
gfn_t end_gfn;
pfn_t pfn;
pfn = gfn_to_pfn_memslot(slot, gfn);
end_gfn = gfn + npages;
gfn += 1;
if (is_error_noslot_pfn(pfn))
return pfn;
while (gfn < end_gfn)
gfn_to_pfn_memslot(slot, gfn++);
return pfn;
}
| 166,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: int sandbox(void* sandbox_arg) {
(void)sandbox_arg;
pid_t child_pid = getpid();
if (arg_debug)
printf("Initializing child process\n");
close(parent_to_child_fds[1]);
close(child_to_parent_fds[0]);
wait_for_other(parent_to_child_fds[0]);
if (arg_debug && child_pid == 1)
printf("PID namespace installed\n");
if (cfg.hostname) {
if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0)
errExit("sethostname");
}
if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
chk_chroot();
}
preproc_mount_mnt_dir();
if (mount(LIBDIR "/firejail", RUN_FIREJAIL_LIB_DIR, "none", MS_BIND, NULL) < 0)
errExit("mounting " RUN_FIREJAIL_LIB_DIR);
if (cfg.name)
fs_logger2("sandbox name:", cfg.name);
fs_logger2int("sandbox pid:", (int) sandbox_pid);
if (cfg.chrootdir)
fs_logger("sandbox filesystem: chroot");
else if (arg_overlay)
fs_logger("sandbox filesystem: overlay");
else
fs_logger("sandbox filesystem: local");
fs_logger("install mount namespace");
if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter
netfilter(arg_netfilter_file);
}
if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter
netfilter6(arg_netfilter6_file);
}
int gw_cfg_failed = 0; // default gw configuration flag
if (arg_nonetwork) {
net_if_up("lo");
if (arg_debug)
printf("Network namespace enabled, only loopback interface available\n");
}
else if (arg_netns) {
netns(arg_netns);
if (arg_debug)
printf("Network namespace '%s' activated\n", arg_netns);
}
else if (any_bridge_configured() || any_interface_configured()) {
net_if_up("lo");
if (mac_not_zero(cfg.bridge0.macsandbox))
net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox);
sandbox_if_up(&cfg.bridge0);
if (mac_not_zero(cfg.bridge1.macsandbox))
net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox);
sandbox_if_up(&cfg.bridge1);
if (mac_not_zero(cfg.bridge2.macsandbox))
net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox);
sandbox_if_up(&cfg.bridge2);
if (mac_not_zero(cfg.bridge3.macsandbox))
net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox);
sandbox_if_up(&cfg.bridge3);
if (cfg.interface0.configured && cfg.interface0.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev);
net_config_interface(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu);
}
if (cfg.interface1.configured && cfg.interface1.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev);
net_config_interface(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu);
}
if (cfg.interface2.configured && cfg.interface2.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev);
net_config_interface(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu);
}
if (cfg.interface3.configured && cfg.interface3.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev);
net_config_interface(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu);
}
if (cfg.defaultgw) {
if (net_add_route(0, 0, cfg.defaultgw)) {
fwarning("cannot configure default route\n");
gw_cfg_failed = 1;
}
}
if (arg_debug)
printf("Network namespace enabled\n");
}
if (!arg_quiet) {
if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) {
fmessage("\n");
if (any_bridge_configured() || any_interface_configured()) {
if (arg_scan)
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 3, PATH_FNET, "printif", "scan");
else
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 2, PATH_FNET, "printif");
}
if (cfg.defaultgw != 0) {
if (gw_cfg_failed)
fmessage("Default gateway configuration failed\n");
else
fmessage("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw));
}
if (cfg.dns1 != NULL)
fmessage("DNS server %s\n", cfg.dns1);
if (cfg.dns2 != NULL)
fmessage("DNS server %s\n", cfg.dns2);
if (cfg.dns3 != NULL)
fmessage("DNS server %s\n", cfg.dns3);
if (cfg.dns4 != NULL)
fmessage("DNS server %s\n", cfg.dns4);
fmessage("\n");
}
}
if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) {
}
else {
EUID_USER();
env_ibus_load();
EUID_ROOT();
}
#ifdef HAVE_SECCOMP
if (cfg.protocol) {
if (arg_debug)
printf("Build protocol filter: %s\n", cfg.protocol);
int rv = sbox_run(SBOX_USER | SBOX_CAPS_NONE | SBOX_SECCOMP, 5,
PATH_FSECCOMP, "protocol", "build", cfg.protocol, RUN_SECCOMP_PROTOCOL);
if (rv)
exit(rv);
}
if (arg_seccomp && (cfg.seccomp_list || cfg.seccomp_list_drop || cfg.seccomp_list_keep))
arg_seccomp_postexec = 1;
#endif
bool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec;
if (getuid() != 0 && (arg_appimage || cfg.chrootdir || arg_overlay)) {
enforce_filters();
need_preload = arg_trace || arg_tracelog;
}
if (need_preload)
fs_trace_preload();
if (cfg.hosts_file)
fs_store_hosts_file();
#ifdef HAVE_CHROOT
if (cfg.chrootdir) {
fs_chroot(cfg.chrootdir);
if (need_preload)
fs_trace_preload();
}
else
#endif
#ifdef HAVE_OVERLAYFS
if (arg_overlay)
fs_overlayfs();
else
#endif
fs_basic_fs();
if (arg_private) {
if (cfg.home_private) { // --private=
if (cfg.chrootdir)
fwarning("private=directory feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private=directory feature is disabled in overlay\n");
else
fs_private_homedir();
}
else if (cfg.home_private_keep) { // --private-home=
if (cfg.chrootdir)
fwarning("private-home= feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-home= feature is disabled in overlay\n");
else
fs_private_home_list();
}
else // --private
fs_private();
}
if (arg_private_dev)
fs_private_dev();
if (arg_private_etc) {
if (cfg.chrootdir)
fwarning("private-etc feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-etc feature is disabled in overlay\n");
else {
fs_private_dir_list("/etc", RUN_ETC_DIR, cfg.etc_private_keep);
if (need_preload)
fs_trace_preload();
}
}
if (arg_private_opt) {
if (cfg.chrootdir)
fwarning("private-opt feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-opt feature is disabled in overlay\n");
else {
fs_private_dir_list("/opt", RUN_OPT_DIR, cfg.opt_private_keep);
}
}
if (arg_private_srv) {
if (cfg.chrootdir)
fwarning("private-srv feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-srv feature is disabled in overlay\n");
else {
fs_private_dir_list("/srv", RUN_SRV_DIR, cfg.srv_private_keep);
}
}
if (arg_private_bin && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-bin feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-bin feature is disabled in overlay\n");
else {
if (arg_x11_xorg) {
EUID_USER();
char *tmp;
if (asprintf(&tmp, "%s,xauth", cfg.bin_private_keep) == -1)
errExit("asprintf");
cfg.bin_private_keep = tmp;
EUID_ROOT();
}
fs_private_bin_list();
}
}
if (arg_private_lib && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-lib feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-lib feature is disabled in overlay\n");
else {
fs_private_lib();
}
}
if (arg_private_cache) {
if (cfg.chrootdir)
fwarning("private-cache feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-cache feature is disabled in overlay\n");
else
fs_private_cache();
}
if (arg_private_tmp) {
EUID_USER();
fs_private_tmp();
EUID_ROOT();
}
if (arg_nodbus)
dbus_session_disable();
if (cfg.hostname)
fs_hostname(cfg.hostname);
if (cfg.hosts_file)
fs_mount_hosts_file();
if (arg_netns)
netns_mounts(arg_netns);
fs_proc_sys_dev_boot();
if (checkcfg(CFG_DISABLE_MNT))
fs_mnt(1);
else if (arg_disable_mnt)
fs_mnt(0);
fs_whitelist();
fs_blacklist(); // mkdir and mkfile are processed all over again
if (arg_nosound) {
pulseaudio_disable();
fs_dev_disable_sound();
}
else if (!arg_noautopulse)
pulseaudio_init();
if (arg_no3d)
fs_dev_disable_3d();
if (arg_notv)
fs_dev_disable_tv();
if (arg_nodvd)
fs_dev_disable_dvd();
if (arg_nou2f)
fs_dev_disable_u2f();
if (arg_novideo)
fs_dev_disable_video();
if (need_preload)
fs_trace();
fs_resolvconf();
fs_logger_print();
fs_logger_change_owner();
EUID_USER();
int cwd = 0;
if (cfg.cwd) {
if (chdir(cfg.cwd) == 0)
cwd = 1;
}
if (!cwd) {
if (chdir("/") < 0)
errExit("chdir");
if (cfg.homedir) {
struct stat s;
if (stat(cfg.homedir, &s) == 0) {
/* coverity[toctou] */
if (chdir(cfg.homedir) < 0)
errExit("chdir");
}
}
}
if (arg_debug) {
char *cpath = get_current_dir_name();
if (cpath) {
printf("Current directory: %s\n", cpath);
free(cpath);
}
}
EUID_ROOT();
fs_x11();
if (arg_x11_xorg)
x11_xorg();
save_umask();
save_nonewprivs();
set_caps();
save_cpu();
save_cgroup();
#ifdef HAVE_SECCOMP
#ifdef SYS_socket
if (cfg.protocol) {
if (arg_debug)
printf("Install protocol filter: %s\n", cfg.protocol);
seccomp_load(RUN_SECCOMP_PROTOCOL); // install filter
protocol_filter_save(); // save filter in RUN_PROTOCOL_CFG
}
else {
int rv = unlink(RUN_SECCOMP_PROTOCOL);
(void) rv;
}
#endif
if (arg_seccomp == 1) {
if (cfg.seccomp_list_keep)
seccomp_filter_keep();
else
seccomp_filter_drop();
}
else { // clean seccomp files under /run/firejail/mnt
int rv = unlink(RUN_SECCOMP_CFG);
rv |= unlink(RUN_SECCOMP_32);
(void) rv;
}
if (arg_memory_deny_write_execute) {
if (arg_debug)
printf("Install memory write&execute filter\n");
seccomp_load(RUN_SECCOMP_MDWX); // install filter
}
else {
int rv = unlink(RUN_SECCOMP_MDWX);
(void) rv;
}
#endif
FILE *rj = create_ready_for_join_file();
save_nogroups();
if (arg_noroot) {
int rv = unshare(CLONE_NEWUSER);
if (rv == -1) {
fwarning("cannot create a new user namespace, going forward without it...\n");
arg_noroot = 0;
}
}
notify_other(child_to_parent_fds[1]);
close(child_to_parent_fds[1]);
wait_for_other(parent_to_child_fds[0]);
close(parent_to_child_fds[0]);
if (arg_noroot) {
if (arg_debug)
printf("noroot user namespace installed\n");
set_caps();
}
if (arg_nonewprivs) {
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) {
fwarning("cannot set NO_NEW_PRIVS, it requires a Linux kernel version 3.5 or newer.\n");
if (force_nonewprivs) {
fprintf(stderr, "Error: NO_NEW_PRIVS required for this sandbox, exiting ...\n");
exit(1);
}
}
else if (arg_debug)
printf("NO_NEW_PRIVS set\n");
}
drop_privs(arg_nogroups);
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
if (cfg.cpus)
set_cpu_affinity();
pid_t app_pid = fork();
if (app_pid == -1)
errExit("fork");
if (app_pid == 0) {
#ifdef HAVE_APPARMOR
if (checkcfg(CFG_APPARMOR) && arg_apparmor) {
errno = 0;
if (aa_change_onexec("firejail-default")) {
fwarning("Cannot confine the application using AppArmor.\n"
"Maybe firejail-default AppArmor profile is not loaded into the kernel.\n"
"As root, run \"aa-enforce firejail-default\" to load it.\n");
}
else if (arg_debug)
printf("AppArmor enabled\n");
}
#endif
if (arg_nice)
set_nice(cfg.nice);
set_rlimits();
start_application(0, rj);
}
fclose(rj);
int status = monitor_application(app_pid); // monitor application
flush_stdin();
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
} else {
return -1;
}
}
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more
CWE ID: CWE-284 | int sandbox(void* sandbox_arg) {
(void)sandbox_arg;
pid_t child_pid = getpid();
if (arg_debug)
printf("Initializing child process\n");
close(parent_to_child_fds[1]);
close(child_to_parent_fds[0]);
wait_for_other(parent_to_child_fds[0]);
if (arg_debug && child_pid == 1)
printf("PID namespace installed\n");
if (cfg.hostname) {
if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0)
errExit("sethostname");
}
if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
chk_chroot();
}
preproc_mount_mnt_dir();
if (mount(LIBDIR "/firejail", RUN_FIREJAIL_LIB_DIR, "none", MS_BIND, NULL) < 0)
errExit("mounting " RUN_FIREJAIL_LIB_DIR);
if (cfg.name)
fs_logger2("sandbox name:", cfg.name);
fs_logger2int("sandbox pid:", (int) sandbox_pid);
if (cfg.chrootdir)
fs_logger("sandbox filesystem: chroot");
else if (arg_overlay)
fs_logger("sandbox filesystem: overlay");
else
fs_logger("sandbox filesystem: local");
fs_logger("install mount namespace");
if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter
netfilter(arg_netfilter_file);
}
if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter
netfilter6(arg_netfilter6_file);
}
int gw_cfg_failed = 0; // default gw configuration flag
if (arg_nonetwork) {
net_if_up("lo");
if (arg_debug)
printf("Network namespace enabled, only loopback interface available\n");
}
else if (arg_netns) {
netns(arg_netns);
if (arg_debug)
printf("Network namespace '%s' activated\n", arg_netns);
}
else if (any_bridge_configured() || any_interface_configured()) {
net_if_up("lo");
if (mac_not_zero(cfg.bridge0.macsandbox))
net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox);
sandbox_if_up(&cfg.bridge0);
if (mac_not_zero(cfg.bridge1.macsandbox))
net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox);
sandbox_if_up(&cfg.bridge1);
if (mac_not_zero(cfg.bridge2.macsandbox))
net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox);
sandbox_if_up(&cfg.bridge2);
if (mac_not_zero(cfg.bridge3.macsandbox))
net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox);
sandbox_if_up(&cfg.bridge3);
if (cfg.interface0.configured && cfg.interface0.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev);
net_config_interface(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu);
}
if (cfg.interface1.configured && cfg.interface1.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev);
net_config_interface(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu);
}
if (cfg.interface2.configured && cfg.interface2.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev);
net_config_interface(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu);
}
if (cfg.interface3.configured && cfg.interface3.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev);
net_config_interface(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu);
}
if (cfg.defaultgw) {
if (net_add_route(0, 0, cfg.defaultgw)) {
fwarning("cannot configure default route\n");
gw_cfg_failed = 1;
}
}
if (arg_debug)
printf("Network namespace enabled\n");
}
if (!arg_quiet) {
if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) {
fmessage("\n");
if (any_bridge_configured() || any_interface_configured()) {
if (arg_scan)
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 3, PATH_FNET, "printif", "scan");
else
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 2, PATH_FNET, "printif");
}
if (cfg.defaultgw != 0) {
if (gw_cfg_failed)
fmessage("Default gateway configuration failed\n");
else
fmessage("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw));
}
if (cfg.dns1 != NULL)
fmessage("DNS server %s\n", cfg.dns1);
if (cfg.dns2 != NULL)
fmessage("DNS server %s\n", cfg.dns2);
if (cfg.dns3 != NULL)
fmessage("DNS server %s\n", cfg.dns3);
if (cfg.dns4 != NULL)
fmessage("DNS server %s\n", cfg.dns4);
fmessage("\n");
}
}
if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) {
}
else {
EUID_USER();
env_ibus_load();
EUID_ROOT();
}
#ifdef HAVE_SECCOMP
if (cfg.protocol) {
if (arg_debug)
printf("Build protocol filter: %s\n", cfg.protocol);
int rv = sbox_run(SBOX_USER | SBOX_CAPS_NONE | SBOX_SECCOMP, 5,
PATH_FSECCOMP, "protocol", "build", cfg.protocol, RUN_SECCOMP_PROTOCOL);
if (rv)
exit(rv);
}
if (arg_seccomp && (cfg.seccomp_list || cfg.seccomp_list_drop || cfg.seccomp_list_keep))
arg_seccomp_postexec = 1;
#endif
bool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec;
if (getuid() != 0 && (arg_appimage || cfg.chrootdir || arg_overlay)) {
enforce_filters();
need_preload = arg_trace || arg_tracelog;
}
if (need_preload)
fs_trace_preload();
if (cfg.hosts_file)
fs_store_hosts_file();
#ifdef HAVE_CHROOT
if (cfg.chrootdir) {
fs_chroot(cfg.chrootdir);
if (need_preload)
fs_trace_preload();
}
else
#endif
#ifdef HAVE_OVERLAYFS
if (arg_overlay)
fs_overlayfs();
else
#endif
fs_basic_fs();
if (arg_private) {
if (cfg.home_private) { // --private=
if (cfg.chrootdir)
fwarning("private=directory feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private=directory feature is disabled in overlay\n");
else
fs_private_homedir();
}
else if (cfg.home_private_keep) { // --private-home=
if (cfg.chrootdir)
fwarning("private-home= feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-home= feature is disabled in overlay\n");
else
fs_private_home_list();
}
else // --private
fs_private();
}
if (arg_private_dev)
fs_private_dev();
if (arg_private_etc) {
if (cfg.chrootdir)
fwarning("private-etc feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-etc feature is disabled in overlay\n");
else {
fs_private_dir_list("/etc", RUN_ETC_DIR, cfg.etc_private_keep);
if (need_preload)
fs_trace_preload();
}
}
if (arg_private_opt) {
if (cfg.chrootdir)
fwarning("private-opt feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-opt feature is disabled in overlay\n");
else {
fs_private_dir_list("/opt", RUN_OPT_DIR, cfg.opt_private_keep);
}
}
if (arg_private_srv) {
if (cfg.chrootdir)
fwarning("private-srv feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-srv feature is disabled in overlay\n");
else {
fs_private_dir_list("/srv", RUN_SRV_DIR, cfg.srv_private_keep);
}
}
if (arg_private_bin && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-bin feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-bin feature is disabled in overlay\n");
else {
if (arg_x11_xorg) {
EUID_USER();
char *tmp;
if (asprintf(&tmp, "%s,xauth", cfg.bin_private_keep) == -1)
errExit("asprintf");
cfg.bin_private_keep = tmp;
EUID_ROOT();
}
fs_private_bin_list();
}
}
if (arg_private_lib && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-lib feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-lib feature is disabled in overlay\n");
else {
fs_private_lib();
}
}
if (arg_private_cache) {
if (cfg.chrootdir)
fwarning("private-cache feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-cache feature is disabled in overlay\n");
else
fs_private_cache();
}
if (arg_private_tmp) {
EUID_USER();
fs_private_tmp();
EUID_ROOT();
}
if (arg_nodbus)
dbus_session_disable();
if (cfg.hostname)
fs_hostname(cfg.hostname);
if (cfg.hosts_file)
fs_mount_hosts_file();
if (arg_netns)
netns_mounts(arg_netns);
fs_proc_sys_dev_boot();
if (checkcfg(CFG_DISABLE_MNT))
fs_mnt(1);
else if (arg_disable_mnt)
fs_mnt(0);
fs_whitelist();
fs_blacklist(); // mkdir and mkfile are processed all over again
if (arg_nosound) {
pulseaudio_disable();
fs_dev_disable_sound();
}
else if (!arg_noautopulse)
pulseaudio_init();
if (arg_no3d)
fs_dev_disable_3d();
if (arg_notv)
fs_dev_disable_tv();
if (arg_nodvd)
fs_dev_disable_dvd();
if (arg_nou2f)
fs_dev_disable_u2f();
if (arg_novideo)
fs_dev_disable_video();
if (need_preload)
fs_trace();
fs_resolvconf();
fs_logger_print();
fs_logger_change_owner();
EUID_USER();
int cwd = 0;
if (cfg.cwd) {
if (chdir(cfg.cwd) == 0)
cwd = 1;
}
if (!cwd) {
if (chdir("/") < 0)
errExit("chdir");
if (cfg.homedir) {
struct stat s;
if (stat(cfg.homedir, &s) == 0) {
/* coverity[toctou] */
if (chdir(cfg.homedir) < 0)
errExit("chdir");
}
}
}
if (arg_debug) {
char *cpath = get_current_dir_name();
if (cpath) {
printf("Current directory: %s\n", cpath);
free(cpath);
}
}
EUID_ROOT();
fs_x11();
if (arg_x11_xorg)
x11_xorg();
save_umask();
save_nonewprivs();
save_cpu();
save_cgroup();
#ifdef HAVE_SECCOMP
#ifdef SYS_socket
if (cfg.protocol) {
if (arg_debug)
printf("Install protocol filter: %s\n", cfg.protocol);
seccomp_load(RUN_SECCOMP_PROTOCOL); // install filter
protocol_filter_save(); // save filter in RUN_PROTOCOL_CFG
}
else {
int rv = unlink(RUN_SECCOMP_PROTOCOL);
(void) rv;
}
#endif
if (arg_seccomp == 1) {
if (cfg.seccomp_list_keep)
seccomp_filter_keep();
else
seccomp_filter_drop();
}
else { // clean seccomp files under /run/firejail/mnt
int rv = unlink(RUN_SECCOMP_CFG);
rv |= unlink(RUN_SECCOMP_32);
(void) rv;
}
if (arg_memory_deny_write_execute) {
if (arg_debug)
printf("Install memory write&execute filter\n");
seccomp_load(RUN_SECCOMP_MDWX); // install filter
}
else {
int rv = unlink(RUN_SECCOMP_MDWX);
(void) rv;
}
// make seccomp filters read-only
fs_rdonly(RUN_SECCOMP_DIR);
#endif
// set capabilities
set_caps();
FILE *rj = create_ready_for_join_file();
save_nogroups();
if (arg_noroot) {
int rv = unshare(CLONE_NEWUSER);
if (rv == -1) {
fwarning("cannot create a new user namespace, going forward without it...\n");
arg_noroot = 0;
}
}
notify_other(child_to_parent_fds[1]);
close(child_to_parent_fds[1]);
wait_for_other(parent_to_child_fds[0]);
close(parent_to_child_fds[0]);
if (arg_noroot) {
if (arg_debug)
printf("noroot user namespace installed\n");
set_caps();
}
if (arg_nonewprivs) {
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) {
fwarning("cannot set NO_NEW_PRIVS, it requires a Linux kernel version 3.5 or newer.\n");
if (force_nonewprivs) {
fprintf(stderr, "Error: NO_NEW_PRIVS required for this sandbox, exiting ...\n");
exit(1);
}
}
else if (arg_debug)
printf("NO_NEW_PRIVS set\n");
}
drop_privs(arg_nogroups);
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
if (cfg.cpus)
set_cpu_affinity();
pid_t app_pid = fork();
if (app_pid == -1)
errExit("fork");
if (app_pid == 0) {
#ifdef HAVE_APPARMOR
if (checkcfg(CFG_APPARMOR) && arg_apparmor) {
errno = 0;
if (aa_change_onexec("firejail-default")) {
fwarning("Cannot confine the application using AppArmor.\n"
"Maybe firejail-default AppArmor profile is not loaded into the kernel.\n"
"As root, run \"aa-enforce firejail-default\" to load it.\n");
}
else if (arg_debug)
printf("AppArmor enabled\n");
}
#endif
if (arg_nice)
set_nice(cfg.nice);
set_rlimits();
start_application(0, rj);
}
fclose(rj);
int status = monitor_application(app_pid); // monitor application
flush_stdin();
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
} else {
return -1;
}
}
| 169,659 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 se_portal_group *tcm_loop_make_naa_tpg(
struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct tcm_loop_hba *tl_hba = container_of(wwn,
struct tcm_loop_hba, tl_hba_wwn);
struct tcm_loop_tpg *tl_tpg;
char *tpgt_str, *end_ptr;
int ret;
unsigned short int tpgt;
tpgt_str = strstr(name, "tpgt_");
if (!tpgt_str) {
printk(KERN_ERR "Unable to locate \"tpgt_#\" directory"
" group\n");
return ERR_PTR(-EINVAL);
}
tpgt_str += 5; /* Skip ahead of "tpgt_" */
tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0);
if (tpgt > TL_TPGS_PER_HBA) {
printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"
" %u\n", tpgt, TL_TPGS_PER_HBA);
return ERR_PTR(-EINVAL);
}
tl_tpg = &tl_hba->tl_hba_tpgs[tpgt];
tl_tpg->tl_hba = tl_hba;
tl_tpg->tl_tpgt = tpgt;
/*
* Register the tl_tpg as a emulated SAS TCM Target Endpoint
*/
ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops,
wwn, &tl_tpg->tl_se_tpg, tl_tpg,
TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0)
return ERR_PTR(-ENOMEM);
printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s"
" Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba),
config_item_name(&wwn->wwn_group.cg_item), tpgt);
return &tl_tpg->tl_se_tpg;
}
Commit Message: loopback: off by one in tcm_loop_make_naa_tpg()
This is an off by one 'tgpt' check in tcm_loop_make_naa_tpg() that could result
in memory corruption.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas A. Bellinger <[email protected]>
CWE ID: CWE-119 | struct se_portal_group *tcm_loop_make_naa_tpg(
struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct tcm_loop_hba *tl_hba = container_of(wwn,
struct tcm_loop_hba, tl_hba_wwn);
struct tcm_loop_tpg *tl_tpg;
char *tpgt_str, *end_ptr;
int ret;
unsigned short int tpgt;
tpgt_str = strstr(name, "tpgt_");
if (!tpgt_str) {
printk(KERN_ERR "Unable to locate \"tpgt_#\" directory"
" group\n");
return ERR_PTR(-EINVAL);
}
tpgt_str += 5; /* Skip ahead of "tpgt_" */
tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0);
if (tpgt >= TL_TPGS_PER_HBA) {
printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"
" %u\n", tpgt, TL_TPGS_PER_HBA);
return ERR_PTR(-EINVAL);
}
tl_tpg = &tl_hba->tl_hba_tpgs[tpgt];
tl_tpg->tl_hba = tl_hba;
tl_tpg->tl_tpgt = tpgt;
/*
* Register the tl_tpg as a emulated SAS TCM Target Endpoint
*/
ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops,
wwn, &tl_tpg->tl_se_tpg, tl_tpg,
TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0)
return ERR_PTR(-ENOMEM);
printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s"
" Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba),
config_item_name(&wwn->wwn_group.cg_item), tpgt);
return &tl_tpg->tl_se_tpg;
}
| 169,870 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc)
{
struct scsi_device *SDev;
struct scsi_sense_hdr sshdr;
int result, err = 0, retries = 0;
SDev = cd->device;
retry:
if (!scsi_block_when_processing_errors(SDev)) {
err = -ENODEV;
goto out;
}
result = scsi_execute(SDev, cgc->cmd, cgc->data_direction,
cgc->buffer, cgc->buflen,
(unsigned char *)cgc->sense, &sshdr,
cgc->timeout, IOCTL_RETRIES, 0, 0, NULL);
/* Minimal error checking. Ignore cases we know about, and report the rest. */
if (driver_byte(result) != 0) {
switch (sshdr.sense_key) {
case UNIT_ATTENTION:
SDev->changed = 1;
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"disc change detected.\n");
if (retries++ < 10)
goto retry;
err = -ENOMEDIUM;
break;
case NOT_READY: /* This happens if there is no disc in drive */
if (sshdr.asc == 0x04 &&
sshdr.ascq == 0x01) {
/* sense: Logical unit is in process of becoming ready */
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready yet.\n");
if (retries++ < 10) {
/* sleep 2 sec and try again */
ssleep(2);
goto retry;
} else {
/* 20 secs are enough? */
err = -ENOMEDIUM;
break;
}
}
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready. Make sure there "
"is a disc in the drive.\n");
err = -ENOMEDIUM;
break;
case ILLEGAL_REQUEST:
err = -EIO;
if (sshdr.asc == 0x20 &&
sshdr.ascq == 0x00)
/* sense: Invalid command operation code */
err = -EDRIVE_CANT_DO_THIS;
break;
default:
err = -EIO;
}
}
/* Wake up a process waiting for device */
out:
cgc->stat = err;
return err;
}
Commit Message: sr: pass down correctly sized SCSI sense buffer
We're casting the CDROM layer request_sense to the SCSI sense
buffer, but the former is 64 bytes and the latter is 96 bytes.
As we generally allocate these on the stack, we end up blowing
up the stack.
Fix this by wrapping the scsi_execute() call with a properly
sized sense buffer, and copying back the bits for the CDROM
layer.
Cc: [email protected]
Reported-by: Piotr Gabriel Kosinski <[email protected]>
Reported-by: Daniel Shapira <[email protected]>
Tested-by: Kees Cook <[email protected]>
Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request")
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-119 | int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc)
{
struct scsi_device *SDev;
struct scsi_sense_hdr sshdr;
int result, err = 0, retries = 0;
unsigned char sense_buffer[SCSI_SENSE_BUFFERSIZE], *senseptr = NULL;
SDev = cd->device;
if (cgc->sense)
senseptr = sense_buffer;
retry:
if (!scsi_block_when_processing_errors(SDev)) {
err = -ENODEV;
goto out;
}
result = scsi_execute(SDev, cgc->cmd, cgc->data_direction,
cgc->buffer, cgc->buflen, senseptr, &sshdr,
cgc->timeout, IOCTL_RETRIES, 0, 0, NULL);
if (cgc->sense)
memcpy(cgc->sense, sense_buffer, sizeof(*cgc->sense));
/* Minimal error checking. Ignore cases we know about, and report the rest. */
if (driver_byte(result) != 0) {
switch (sshdr.sense_key) {
case UNIT_ATTENTION:
SDev->changed = 1;
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"disc change detected.\n");
if (retries++ < 10)
goto retry;
err = -ENOMEDIUM;
break;
case NOT_READY: /* This happens if there is no disc in drive */
if (sshdr.asc == 0x04 &&
sshdr.ascq == 0x01) {
/* sense: Logical unit is in process of becoming ready */
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready yet.\n");
if (retries++ < 10) {
/* sleep 2 sec and try again */
ssleep(2);
goto retry;
} else {
/* 20 secs are enough? */
err = -ENOMEDIUM;
break;
}
}
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready. Make sure there "
"is a disc in the drive.\n");
err = -ENOMEDIUM;
break;
case ILLEGAL_REQUEST:
err = -EIO;
if (sshdr.asc == 0x20 &&
sshdr.ascq == 0x00)
/* sense: Invalid command operation code */
err = -EDRIVE_CANT_DO_THIS;
break;
default:
err = -EIO;
}
}
/* Wake up a process waiting for device */
out:
cgc->stat = err;
return err;
}
| 169,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.