instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserContextDestroyer::FinishDestroyContext() {
DCHECK_EQ(pending_hosts_, 0U);
delete context_;
context_ = nullptr;
delete this;
}
Commit Message:
CWE ID: CWE-20 | void BrowserContextDestroyer::FinishDestroyContext() {
DCHECK(finish_destroy_scheduled_);
CHECK_EQ(GetHostsForContext(context_.get()).size(), 0U)
<< "One or more RenderProcessHosts exist whilst its BrowserContext is "
<< "being deleted!";
g_contexts_pending_deletion.Get().remove(this);
if (context_->IsOffTheRecord()) {
// If this is an OTR context and its owner BrowserContext has been scheduled
// for deletion, update the owner's BrowserContextDestroyer
BrowserContextDestroyer* orig_destroyer =
GetForContext(context_->GetOriginalContext());
if (orig_destroyer) {
DCHECK_GT(orig_destroyer->otr_contexts_pending_deletion_, 0U);
DCHECK(!orig_destroyer->finish_destroy_scheduled_);
--orig_destroyer->otr_contexts_pending_deletion_;
orig_destroyer->MaybeScheduleFinishDestroyContext();
}
}
delete this;
}
| 165,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftAVC::drainAllOutputBuffers(bool eos) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
H264SwDecPicture decodedPicture;
if (mHeadersDecoded) {
while (!outQueue.empty()
&& H264SWDEC_PIC_RDY == H264SwDecNextPicture(
mHandle, &decodedPicture, eos /* flush */)) {
int32_t picId = decodedPicture.picId;
uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture;
drainOneOutputBuffer(picId, data);
}
}
if (!eos) {
return;
}
while (!outQueue.empty()) {
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftAVC::drainAllOutputBuffers(bool eos) {
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
H264SwDecPicture decodedPicture;
if (mHeadersDecoded) {
while (!outQueue.empty()
&& H264SWDEC_PIC_RDY == H264SwDecNextPicture(
mHandle, &decodedPicture, eos /* flush */)) {
int32_t picId = decodedPicture.picId;
uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture;
if (!drainOneOutputBuffer(picId, data)) {
ALOGE("Drain failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
}
}
if (!eos) {
return;
}
while (!outQueue.empty()) {
BufferInfo *outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
}
| 174,176 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
Commit Message: Fix bug #72860: wddx_deserialize use-after-free
CWE ID: CWE-416 | static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data
&& ((st_entry *)stack->elements[i])->type != ST_FIELD) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
| 166,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher,
base::WaitableEvent* shutdown_event,
bool forbid_other_requests) {
dispatcher->AddShutdown("/shutdown", shutdown_event);
dispatcher->AddStatus("/healthz");
dispatcher->Add<CreateSession>("/session");
dispatcher->Add<FindOneElementCommand>( "/session/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements");
dispatcher->Add<ActiveElementCommand>( "/session/*/element/active");
dispatcher->Add<FindOneElementCommand>( "/session/*/element/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements/*/elements");
dispatcher->Add<ElementAttributeCommand>("/session/*/element/*/attribute/*");
dispatcher->Add<ElementCssCommand>( "/session/*/element/*/css/*");
dispatcher->Add<ElementClearCommand>( "/session/*/element/*/clear");
dispatcher->Add<ElementDisplayedCommand>("/session/*/element/*/displayed");
dispatcher->Add<ElementEnabledCommand>( "/session/*/element/*/enabled");
dispatcher->Add<ElementEqualsCommand>( "/session/*/element/*/equals/*");
dispatcher->Add<ElementLocationCommand>( "/session/*/element/*/location");
dispatcher->Add<ElementLocationInViewCommand>(
"/session/*/element/*/location_in_view");
dispatcher->Add<ElementNameCommand>( "/session/*/element/*/name");
dispatcher->Add<ElementSelectedCommand>("/session/*/element/*/selected");
dispatcher->Add<ElementSizeCommand>( "/session/*/element/*/size");
dispatcher->Add<ElementSubmitCommand>( "/session/*/element/*/submit");
dispatcher->Add<ElementTextCommand>( "/session/*/element/*/text");
dispatcher->Add<ElementToggleCommand>( "/session/*/element/*/toggle");
dispatcher->Add<ElementValueCommand>( "/session/*/element/*/value");
dispatcher->Add<ScreenshotCommand>("/session/*/screenshot");
dispatcher->Add<MoveAndClickCommand>("/session/*/element/*/click");
dispatcher->Add<DragCommand>( "/session/*/element/*/drag");
dispatcher->Add<HoverCommand>( "/session/*/element/*/hover");
dispatcher->Add<MoveToCommand>( "/session/*/moveto");
dispatcher->Add<ClickCommand>( "/session/*/click");
dispatcher->Add<ButtonDownCommand>( "/session/*/buttondown");
dispatcher->Add<ButtonUpCommand>( "/session/*/buttonup");
dispatcher->Add<DoubleClickCommand>("/session/*/doubleclick");
dispatcher->Add<AcceptAlertCommand>( "/session/*/accept_alert");
dispatcher->Add<AlertTextCommand>( "/session/*/alert_text");
dispatcher->Add<BackCommand>( "/session/*/back");
dispatcher->Add<DismissAlertCommand>( "/session/*/dismiss_alert");
dispatcher->Add<ExecuteCommand>( "/session/*/execute");
dispatcher->Add<ExecuteAsyncScriptCommand>(
"/session/*/execute_async");
dispatcher->Add<ForwardCommand>( "/session/*/forward");
dispatcher->Add<SwitchFrameCommand>( "/session/*/frame");
dispatcher->Add<RefreshCommand>( "/session/*/refresh");
dispatcher->Add<SourceCommand>( "/session/*/source");
dispatcher->Add<TitleCommand>( "/session/*/title");
dispatcher->Add<URLCommand>( "/session/*/url");
dispatcher->Add<WindowCommand>( "/session/*/window");
dispatcher->Add<WindowHandleCommand>( "/session/*/window_handle");
dispatcher->Add<WindowHandlesCommand>("/session/*/window_handles");
dispatcher->Add<SetAsyncScriptTimeoutCommand>(
"/session/*/timeouts/async_script");
dispatcher->Add<ImplicitWaitCommand>( "/session/*/timeouts/implicit_wait");
dispatcher->Add<CookieCommand>( "/session/*/cookie");
dispatcher->Add<NamedCookieCommand>("/session/*/cookie/*");
dispatcher->Add<SessionWithID>("/session/*");
if (forbid_other_requests)
dispatcher->ForbidAllOtherRequests();
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher,
base::WaitableEvent* shutdown_event,
bool forbid_other_requests) {
dispatcher->AddShutdown("/shutdown", shutdown_event);
dispatcher->AddHealthz("/healthz");
dispatcher->AddLog("/log");
dispatcher->Add<CreateSession>("/session");
dispatcher->Add<FindOneElementCommand>( "/session/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements");
dispatcher->Add<ActiveElementCommand>( "/session/*/element/active");
dispatcher->Add<FindOneElementCommand>( "/session/*/element/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements/*/elements");
dispatcher->Add<ElementAttributeCommand>("/session/*/element/*/attribute/*");
dispatcher->Add<ElementCssCommand>( "/session/*/element/*/css/*");
dispatcher->Add<ElementClearCommand>( "/session/*/element/*/clear");
dispatcher->Add<ElementDisplayedCommand>("/session/*/element/*/displayed");
dispatcher->Add<ElementEnabledCommand>( "/session/*/element/*/enabled");
dispatcher->Add<ElementEqualsCommand>( "/session/*/element/*/equals/*");
dispatcher->Add<ElementLocationCommand>( "/session/*/element/*/location");
dispatcher->Add<ElementLocationInViewCommand>(
"/session/*/element/*/location_in_view");
dispatcher->Add<ElementNameCommand>( "/session/*/element/*/name");
dispatcher->Add<ElementSelectedCommand>("/session/*/element/*/selected");
dispatcher->Add<ElementSizeCommand>( "/session/*/element/*/size");
dispatcher->Add<ElementSubmitCommand>( "/session/*/element/*/submit");
dispatcher->Add<ElementTextCommand>( "/session/*/element/*/text");
dispatcher->Add<ElementToggleCommand>( "/session/*/element/*/toggle");
dispatcher->Add<ElementValueCommand>( "/session/*/element/*/value");
dispatcher->Add<ScreenshotCommand>("/session/*/screenshot");
dispatcher->Add<MoveAndClickCommand>("/session/*/element/*/click");
dispatcher->Add<DragCommand>( "/session/*/element/*/drag");
dispatcher->Add<HoverCommand>( "/session/*/element/*/hover");
dispatcher->Add<MoveToCommand>( "/session/*/moveto");
dispatcher->Add<ClickCommand>( "/session/*/click");
dispatcher->Add<ButtonDownCommand>( "/session/*/buttondown");
dispatcher->Add<ButtonUpCommand>( "/session/*/buttonup");
dispatcher->Add<DoubleClickCommand>("/session/*/doubleclick");
dispatcher->Add<AcceptAlertCommand>( "/session/*/accept_alert");
dispatcher->Add<AlertTextCommand>( "/session/*/alert_text");
dispatcher->Add<BackCommand>( "/session/*/back");
dispatcher->Add<DismissAlertCommand>( "/session/*/dismiss_alert");
dispatcher->Add<ExecuteCommand>( "/session/*/execute");
dispatcher->Add<ExecuteAsyncScriptCommand>(
"/session/*/execute_async");
dispatcher->Add<ForwardCommand>( "/session/*/forward");
dispatcher->Add<SwitchFrameCommand>( "/session/*/frame");
dispatcher->Add<RefreshCommand>( "/session/*/refresh");
dispatcher->Add<SourceCommand>( "/session/*/source");
dispatcher->Add<TitleCommand>( "/session/*/title");
dispatcher->Add<URLCommand>( "/session/*/url");
dispatcher->Add<WindowCommand>( "/session/*/window");
dispatcher->Add<WindowHandleCommand>( "/session/*/window_handle");
dispatcher->Add<WindowHandlesCommand>("/session/*/window_handles");
dispatcher->Add<SetAsyncScriptTimeoutCommand>(
"/session/*/timeouts/async_script");
dispatcher->Add<ImplicitWaitCommand>( "/session/*/timeouts/implicit_wait");
dispatcher->Add<CookieCommand>( "/session/*/cookie");
dispatcher->Add<NamedCookieCommand>("/session/*/cookie/*");
dispatcher->Add<SessionWithID>("/session/*");
if (forbid_other_requests)
dispatcher->ForbidAllOtherRequests();
}
| 170,460 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
BrowserContext* browser_context,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
return map->FindProcess(site);
}
Commit Message: Check for appropriate bindings in process-per-site mode.
BUG=174059
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12188025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
BrowserContext* browser_context,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
// See if we have an existing process with appropriate bindings for this site.
// If not, the caller should create a new process and register it.
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
RenderProcessHost* host = map->FindProcess(site);
if (host && !IsSuitableHost(host, browser_context, url)) {
// The registered process does not have an appropriate set of bindings for
// the url. Remove it from the map so we can register a better one.
RecordAction(UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
map->RemoveProcess(host);
host = NULL;
}
return host;
}
| 171,467 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_image_new(Jbig2Ctx *ctx, int width, int height)
{
Jbig2Image *image;
int stride;
int64_t check;
image = jbig2_new(ctx, Jbig2Image, 1);
if (image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image structure in jbig2_image_new");
return NULL;
}
stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */
/* check for integer multiplication overflow */
check = ((int64_t) stride) * ((int64_t) height);
if (check != (int)check) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow from stride(%d)*height(%d)", stride, height);
jbig2_free(ctx->allocator, image);
return NULL;
}
/* Add 1 to accept runs that exceed image width and clamped to width+1 */
image->data = jbig2_new(ctx, uint8_t, (int)check + 1);
if (image->data == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image data buffer! [stride(%d)*height(%d) bytes]", stride, height);
jbig2_free(ctx->allocator, image);
return NULL;
}
image->width = width;
image->height = height;
image->stride = stride;
image->refcount = 1;
return image;
}
Commit Message:
CWE ID: CWE-119 | jbig2_image_new(Jbig2Ctx *ctx, int width, int height)
jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height)
{
Jbig2Image *image;
uint32_t stride;
int64_t check;
image = jbig2_new(ctx, Jbig2Image, 1);
if (image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image structure in jbig2_image_new");
return NULL;
}
stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */
/* check for integer multiplication overflow */
check = ((int64_t) stride) * ((int64_t) height);
if (check != (int)check) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow from stride(%d)*height(%d)", stride, height);
jbig2_free(ctx->allocator, image);
return NULL;
}
/* Add 1 to accept runs that exceed image width and clamped to width+1 */
image->data = jbig2_new(ctx, uint8_t, (int)check + 1);
if (image->data == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image data buffer! [stride(%d)*height(%d) bytes]", stride, height);
jbig2_free(ctx->allocator, image);
return NULL;
}
image->width = width;
image->height = height;
image->stride = stride;
image->refcount = 1;
return image;
}
| 165,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
bool profiling, const std::string& filename_prefix) {
#if !defined(OS_WIN)
if (profiling)
HeapProfilerStart(filename_prefix.c_str());
else
HeapProfilerStop();
#endif
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
| 170,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t bat_socket_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct socket_client *socket_client = file->private_data;
struct socket_packet *socket_packet;
size_t packet_len;
int error;
if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0))
return -EAGAIN;
if ((!buf) || (count < sizeof(struct icmp_packet)))
return -EINVAL;
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
error = wait_event_interruptible(socket_client->queue_wait,
socket_client->queue_len);
if (error)
return error;
spin_lock_bh(&socket_client->lock);
socket_packet = list_first_entry(&socket_client->queue_list,
struct socket_packet, list);
list_del(&socket_packet->list);
socket_client->queue_len--;
spin_unlock_bh(&socket_client->lock);
error = copy_to_user(buf, &socket_packet->icmp_packet,
socket_packet->icmp_len);
packet_len = socket_packet->icmp_len;
kfree(socket_packet);
if (error)
return -EFAULT;
return packet_len;
}
Commit Message: batman-adv: Only write requested number of byte to user buffer
Don't write more than the requested number of bytes of an batman-adv icmp
packet to the userspace buffer. Otherwise unrelated userspace memory might get
overridden by the kernel.
Signed-off-by: Sven Eckelmann <[email protected]>
Signed-off-by: Marek Lindner <[email protected]>
CWE ID: CWE-119 | static ssize_t bat_socket_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct socket_client *socket_client = file->private_data;
struct socket_packet *socket_packet;
size_t packet_len;
int error;
if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0))
return -EAGAIN;
if ((!buf) || (count < sizeof(struct icmp_packet)))
return -EINVAL;
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
error = wait_event_interruptible(socket_client->queue_wait,
socket_client->queue_len);
if (error)
return error;
spin_lock_bh(&socket_client->lock);
socket_packet = list_first_entry(&socket_client->queue_list,
struct socket_packet, list);
list_del(&socket_packet->list);
socket_client->queue_len--;
spin_unlock_bh(&socket_client->lock);
packet_len = min(count, socket_packet->icmp_len);
error = copy_to_user(buf, &socket_packet->icmp_packet, packet_len);
kfree(socket_packet);
if (error)
return -EFAULT;
return packet_len;
}
| 166,207 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20 | BackendImpl::BackendImpl(
const base::FilePath& path,
uint32_t mask,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
consider_evicting_at_op_end_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
| 172,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromePluginServiceFilter::IsPluginEnabled(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (!use)
return false;
*plugin = details->overridden_plugins[i].plugin;
break;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | bool ChromePluginServiceFilter::IsPluginEnabled(
bool ChromePluginServiceFilter::IsPluginAvailable(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (use)
*plugin = details->overridden_plugins[i].plugin;
return use;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
| 171,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetUpCacheWithVariousFiles() {
CreateFile(persistent_directory_.AppendASCII("id_foo.md5foo"));
CreateFile(persistent_directory_.AppendASCII("id_bar.local"));
CreateFile(persistent_directory_.AppendASCII("id_baz.local"));
CreateFile(persistent_directory_.AppendASCII("id_bad.md5bad"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
persistent_directory_.AppendASCII("id_symlink"));
CreateFile(tmp_directory_.AppendASCII("id_qux.md5qux"));
CreateFile(tmp_directory_.AppendASCII("id_quux.local"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
tmp_directory_.AppendASCII("id_symlink_tmp"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
pinned_directory_.AppendASCII("id_foo"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
pinned_directory_.AppendASCII("id_corge"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_dangling.md5foo"),
pinned_directory_.AppendASCII("id_dangling"));
CreateSymbolicLink(tmp_directory_.AppendASCII("id_qux.md5qux"),
pinned_directory_.AppendASCII("id_outside"));
CreateFile(pinned_directory_.AppendASCII("id_not_symlink"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_bar.local"),
outgoing_directory_.AppendASCII("id_bar"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
outgoing_directory_.AppendASCII("id_foo"));
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void SetUpCacheWithVariousFiles() {
std::vector<FilePath> empty_cache_paths;
metadata_->Initialize(empty_cache_paths);
}
| 170,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 173,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EncoderTest::RunLoop(VideoSource *video) {
vpx_codec_dec_cfg_t dec_cfg = {0};
stats_.Reset();
ASSERT_TRUE(passes_ == 1 || passes_ == 2);
for (unsigned int pass = 0; pass < passes_; pass++) {
last_pts_ = 0;
if (passes_ == 1)
cfg_.g_pass = VPX_RC_ONE_PASS;
else if (pass == 0)
cfg_.g_pass = VPX_RC_FIRST_PASS;
else
cfg_.g_pass = VPX_RC_LAST_PASS;
BeginPassHook(pass);
Encoder* const encoder = codec_->CreateEncoder(cfg_, deadline_, init_flags_,
&stats_);
ASSERT_TRUE(encoder != NULL);
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0);
bool again;
for (again = true, video->Begin(); again; video->Next()) {
again = (video->img() != NULL);
PreEncodeFrameHook(video);
PreEncodeFrameHook(video, encoder);
encoder->EncodeFrame(video, frame_flags_);
CxDataIterator iter = encoder->GetCxData();
bool has_cxdata = false;
bool has_dxdata = false;
while (const vpx_codec_cx_pkt_t *pkt = iter.Next()) {
pkt = MutateEncoderOutputHook(pkt);
again = true;
switch (pkt->kind) {
case VPX_CODEC_CX_FRAME_PKT:
has_cxdata = true;
if (decoder && DoDecode()) {
vpx_codec_err_t res_dec = decoder->DecodeFrame(
(const uint8_t*)pkt->data.frame.buf, pkt->data.frame.sz);
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
has_dxdata = true;
}
ASSERT_GE(pkt->data.frame.pts, last_pts_);
last_pts_ = pkt->data.frame.pts;
FramePktHook(pkt);
break;
case VPX_CODEC_PSNR_PKT:
PSNRPktHook(pkt);
break;
default:
break;
}
}
if (has_dxdata && has_cxdata) {
const vpx_image_t *img_enc = encoder->GetPreviewFrame();
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img_dec = dec_iter.Next();
if (img_enc && img_dec) {
const bool res = compare_img(img_enc, img_dec);
if (!res) { // Mismatch
MismatchHook(img_enc, img_dec);
}
}
if (img_dec)
DecompressedFrameHook(*img_dec, video->pts());
}
if (!Continue())
break;
}
EndPassHook();
if (decoder)
delete decoder;
delete encoder;
if (!Continue())
break;
}
}
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 EncoderTest::RunLoop(VideoSource *video) {
vpx_codec_dec_cfg_t dec_cfg = vpx_codec_dec_cfg_t();
stats_.Reset();
ASSERT_TRUE(passes_ == 1 || passes_ == 2);
for (unsigned int pass = 0; pass < passes_; pass++) {
last_pts_ = 0;
if (passes_ == 1)
cfg_.g_pass = VPX_RC_ONE_PASS;
else if (pass == 0)
cfg_.g_pass = VPX_RC_FIRST_PASS;
else
cfg_.g_pass = VPX_RC_LAST_PASS;
BeginPassHook(pass);
Encoder* const encoder = codec_->CreateEncoder(cfg_, deadline_, init_flags_,
&stats_);
ASSERT_TRUE(encoder != NULL);
video->Begin();
encoder->InitEncoder(video);
unsigned long dec_init_flags = 0; // NOLINT
// Use fragment decoder if encoder outputs partitions.
// NOTE: fragment decoder and partition encoder are only supported by VP8.
if (init_flags_ & VPX_CODEC_USE_OUTPUT_PARTITION)
dec_init_flags |= VPX_CODEC_USE_INPUT_FRAGMENTS;
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, dec_init_flags, 0);
bool again;
for (again = true; again; video->Next()) {
again = (video->img() != NULL);
PreEncodeFrameHook(video);
PreEncodeFrameHook(video, encoder);
encoder->EncodeFrame(video, frame_flags_);
CxDataIterator iter = encoder->GetCxData();
bool has_cxdata = false;
bool has_dxdata = false;
while (const vpx_codec_cx_pkt_t *pkt = iter.Next()) {
pkt = MutateEncoderOutputHook(pkt);
again = true;
switch (pkt->kind) {
case VPX_CODEC_CX_FRAME_PKT:
has_cxdata = true;
if (decoder && DoDecode()) {
vpx_codec_err_t res_dec = decoder->DecodeFrame(
(const uint8_t*)pkt->data.frame.buf, pkt->data.frame.sz);
if (!HandleDecodeResult(res_dec, *video, decoder))
break;
has_dxdata = true;
}
ASSERT_GE(pkt->data.frame.pts, last_pts_);
last_pts_ = pkt->data.frame.pts;
FramePktHook(pkt);
break;
case VPX_CODEC_PSNR_PKT:
PSNRPktHook(pkt);
break;
default:
break;
}
}
// Flush the decoder when there are no more fragments.
if ((init_flags_ & VPX_CODEC_USE_OUTPUT_PARTITION) && has_dxdata) {
const vpx_codec_err_t res_dec = decoder->DecodeFrame(NULL, 0);
if (!HandleDecodeResult(res_dec, *video, decoder))
break;
}
if (has_dxdata && has_cxdata) {
const vpx_image_t *img_enc = encoder->GetPreviewFrame();
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img_dec = dec_iter.Next();
if (img_enc && img_dec) {
const bool res = compare_img(img_enc, img_dec);
if (!res) { // Mismatch
MismatchHook(img_enc, img_dec);
}
}
if (img_dec)
DecompressedFrameHook(*img_dec, video->pts());
}
if (!Continue())
break;
}
EndPassHook();
if (decoder)
delete decoder;
delete encoder;
if (!Continue())
break;
}
}
| 174,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
Commit Message:
CWE ID: CWE-189 | void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
| 164,614 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int get_rock_ridge_filename(struct iso_directory_record *de,
char *retname, struct inode *inode)
{
struct rock_state rs;
struct rock_ridge *rr;
int sig;
int retnamlen = 0;
int truncate = 0;
int ret = 0;
if (!ISOFS_SB(inode->i_sb)->s_rock)
return 0;
*retname = 0;
init_rock_state(&rs, inode);
setup_rock_ridge(de, inode, &rs);
repeat:
while (rs.len > 2) { /* There may be one byte for padding somewhere */
rr = (struct rock_ridge *)rs.chr;
/*
* Ignore rock ridge info if rr->len is out of range, but
* don't return -EIO because that would make the file
* invisible.
*/
if (rr->len < 3)
goto out; /* Something got screwed up here */
sig = isonum_721(rs.chr);
if (rock_check_overflow(&rs, sig))
goto eio;
rs.chr += rr->len;
rs.len -= rr->len;
/*
* As above, just ignore the rock ridge info if rr->len
* is bogus.
*/
if (rs.len < 0)
goto out; /* Something got screwed up here */
switch (sig) {
case SIG('R', 'R'):
if ((rr->u.RR.flags[0] & RR_NM) == 0)
goto out;
break;
case SIG('S', 'P'):
if (check_sp(rr, inode))
goto out;
break;
case SIG('C', 'E'):
rs.cont_extent = isonum_733(rr->u.CE.extent);
rs.cont_offset = isonum_733(rr->u.CE.offset);
rs.cont_size = isonum_733(rr->u.CE.size);
break;
case SIG('N', 'M'):
if (truncate)
break;
if (rr->len < 5)
break;
/*
* If the flags are 2 or 4, this indicates '.' or '..'.
* We don't want to do anything with this, because it
* screws up the code that calls us. We don't really
* care anyways, since we can just use the non-RR
* name.
*/
if (rr->u.NM.flags & 6)
break;
if (rr->u.NM.flags & ~1) {
printk("Unsupported NM flag settings (%d)\n",
rr->u.NM.flags);
break;
}
if ((strlen(retname) + rr->len - 5) >= 254) {
truncate = 1;
break;
}
strncat(retname, rr->u.NM.name, rr->len - 5);
retnamlen += rr->len - 5;
break;
case SIG('R', 'E'):
kfree(rs.buffer);
return -1;
default:
break;
}
}
ret = rock_continue(&rs);
if (ret == 0)
goto repeat;
if (ret == 1)
return retnamlen; /* If 0, this file did not have a NM field */
out:
kfree(rs.buffer);
return ret;
eio:
ret = -EIO;
goto out;
}
Commit Message: get_rock_ridge_filename(): handle malformed NM entries
Payloads of NM entries are not supposed to contain NUL. When we run
into such, only the part prior to the first NUL goes into the
concatenation (i.e. the directory entry name being encoded by a bunch
of NM entries). We do stop when the amount collected so far + the
claimed amount in the current NM entry exceed 254. So far, so good,
but what we return as the total length is the sum of *claimed*
sizes, not the actual amount collected. And that can grow pretty
large - not unlimited, since you'd need to put CE entries in
between to be able to get more than the maximum that could be
contained in one isofs directory entry / continuation chunk and
we are stop once we'd encountered 32 CEs, but you can get about 8Kb
easily. And that's what will be passed to readdir callback as the
name length. 8Kb __copy_to_user() from a buffer allocated by
__get_free_page()
Cc: [email protected] # 0.98pl6+ (yes, really)
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200 | int get_rock_ridge_filename(struct iso_directory_record *de,
char *retname, struct inode *inode)
{
struct rock_state rs;
struct rock_ridge *rr;
int sig;
int retnamlen = 0;
int truncate = 0;
int ret = 0;
char *p;
int len;
if (!ISOFS_SB(inode->i_sb)->s_rock)
return 0;
*retname = 0;
init_rock_state(&rs, inode);
setup_rock_ridge(de, inode, &rs);
repeat:
while (rs.len > 2) { /* There may be one byte for padding somewhere */
rr = (struct rock_ridge *)rs.chr;
/*
* Ignore rock ridge info if rr->len is out of range, but
* don't return -EIO because that would make the file
* invisible.
*/
if (rr->len < 3)
goto out; /* Something got screwed up here */
sig = isonum_721(rs.chr);
if (rock_check_overflow(&rs, sig))
goto eio;
rs.chr += rr->len;
rs.len -= rr->len;
/*
* As above, just ignore the rock ridge info if rr->len
* is bogus.
*/
if (rs.len < 0)
goto out; /* Something got screwed up here */
switch (sig) {
case SIG('R', 'R'):
if ((rr->u.RR.flags[0] & RR_NM) == 0)
goto out;
break;
case SIG('S', 'P'):
if (check_sp(rr, inode))
goto out;
break;
case SIG('C', 'E'):
rs.cont_extent = isonum_733(rr->u.CE.extent);
rs.cont_offset = isonum_733(rr->u.CE.offset);
rs.cont_size = isonum_733(rr->u.CE.size);
break;
case SIG('N', 'M'):
if (truncate)
break;
if (rr->len < 5)
break;
/*
* If the flags are 2 or 4, this indicates '.' or '..'.
* We don't want to do anything with this, because it
* screws up the code that calls us. We don't really
* care anyways, since we can just use the non-RR
* name.
*/
if (rr->u.NM.flags & 6)
break;
if (rr->u.NM.flags & ~1) {
printk("Unsupported NM flag settings (%d)\n",
rr->u.NM.flags);
break;
}
len = rr->len - 5;
if (retnamlen + len >= 254) {
truncate = 1;
break;
}
p = memchr(rr->u.NM.name, '\0', len);
if (unlikely(p))
len = p - rr->u.NM.name;
memcpy(retname + retnamlen, rr->u.NM.name, len);
retnamlen += len;
retname[retnamlen] = '\0';
break;
case SIG('R', 'E'):
kfree(rs.buffer);
return -1;
default:
break;
}
}
ret = rock_continue(&rs);
if (ret == 0)
goto repeat;
if (ret == 1)
return retnamlen; /* If 0, this file did not have a NM field */
out:
kfree(rs.buffer);
return ret;
eio:
ret = -EIO;
goto out;
}
| 167,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WriteFakeData(uint8* audio_data, size_t length) {
Type* output = reinterpret_cast<Type*>(audio_data);
for (size_t i = 0; i < length; i++) {
output[i] = i % 5 + 10;
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void WriteFakeData(uint8* audio_data, size_t length) {
| 171,537 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pud_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pud_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
| 170,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
{
struct tun_struct *tun;
struct tun_file *tfile = file->private_data;
struct net_device *dev;
int err;
if (tfile->detached)
return -EINVAL;
dev = __dev_get_by_name(net, ifr->ifr_name);
if (dev) {
if (ifr->ifr_flags & IFF_TUN_EXCL)
return -EBUSY;
if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
tun = netdev_priv(dev);
else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
tun = netdev_priv(dev);
else
return -EINVAL;
if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
!!(tun->flags & IFF_MULTI_QUEUE))
return -EINVAL;
if (tun_not_capable(tun))
return -EPERM;
err = security_tun_dev_open(tun->security);
if (err < 0)
return err;
err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
if (err < 0)
return err;
if (tun->flags & IFF_MULTI_QUEUE &&
(tun->numqueues + tun->numdisabled > 1)) {
/* One or more queue has already been attached, no need
* to initialize the device again.
*/
return 0;
}
}
else {
char *name;
unsigned long flags = 0;
int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
MAX_TAP_QUEUES : 1;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = security_tun_dev_create();
if (err < 0)
return err;
/* Set dev type */
if (ifr->ifr_flags & IFF_TUN) {
/* TUN device */
flags |= IFF_TUN;
name = "tun%d";
} else if (ifr->ifr_flags & IFF_TAP) {
/* TAP device */
flags |= IFF_TAP;
name = "tap%d";
} else
return -EINVAL;
if (*ifr->ifr_name)
name = ifr->ifr_name;
dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
NET_NAME_UNKNOWN, tun_setup, queues,
queues);
if (!dev)
return -ENOMEM;
err = dev_get_valid_name(net, dev, name);
if (err)
goto err_free_dev;
dev_net_set(dev, net);
dev->rtnl_link_ops = &tun_link_ops;
dev->ifindex = tfile->ifindex;
dev->sysfs_groups[0] = &tun_attr_group;
tun = netdev_priv(dev);
tun->dev = dev;
tun->flags = flags;
tun->txflt.count = 0;
tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
tun->align = NET_SKB_PAD;
tun->filter_attached = false;
tun->sndbuf = tfile->socket.sk->sk_sndbuf;
tun->rx_batched = 0;
tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
if (!tun->pcpu_stats) {
err = -ENOMEM;
goto err_free_dev;
}
spin_lock_init(&tun->lock);
err = security_tun_dev_alloc_security(&tun->security);
if (err < 0)
goto err_free_stat;
tun_net_init(dev);
tun_flow_init(tun);
dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX;
dev->features = dev->hw_features | NETIF_F_LLTX;
dev->vlan_features = dev->features &
~(NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX);
INIT_LIST_HEAD(&tun->disabled);
err = tun_attach(tun, file, false);
if (err < 0)
goto err_free_flow;
err = register_netdevice(tun->dev);
if (err < 0)
goto err_detach;
}
netif_carrier_on(tun->dev);
tun_debug(KERN_INFO, tun, "tun_set_iff\n");
tun->flags = (tun->flags & ~TUN_FEATURES) |
(ifr->ifr_flags & TUN_FEATURES);
/* Make sure persistent devices do not get stuck in
* xoff state.
*/
if (netif_running(tun->dev))
netif_tx_wake_all_queues(tun->dev);
strcpy(ifr->ifr_name, tun->dev->name);
return 0;
err_detach:
tun_detach_all(dev);
/* register_netdevice() already called tun_free_netdev() */
goto err_free_dev;
err_free_flow:
tun_flow_uninit(tun);
security_tun_dev_free_security(tun->security);
err_free_stat:
free_percpu(tun->pcpu_stats);
err_free_dev:
free_netdev(dev);
return err;
}
Commit Message: tun: allow positive return values on dev_get_valid_name() call
If the name argument of dev_get_valid_name() contains "%d", it will try
to assign it a unit number in __dev__alloc_name() and return either the
unit number (>= 0) or an error code (< 0).
Considering positive values as error values prevent tun device creations
relying this mechanism, therefor we should only consider negative values
as errors here.
Signed-off-by: Julien Gomes <[email protected]>
Acked-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
{
struct tun_struct *tun;
struct tun_file *tfile = file->private_data;
struct net_device *dev;
int err;
if (tfile->detached)
return -EINVAL;
dev = __dev_get_by_name(net, ifr->ifr_name);
if (dev) {
if (ifr->ifr_flags & IFF_TUN_EXCL)
return -EBUSY;
if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
tun = netdev_priv(dev);
else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
tun = netdev_priv(dev);
else
return -EINVAL;
if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
!!(tun->flags & IFF_MULTI_QUEUE))
return -EINVAL;
if (tun_not_capable(tun))
return -EPERM;
err = security_tun_dev_open(tun->security);
if (err < 0)
return err;
err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
if (err < 0)
return err;
if (tun->flags & IFF_MULTI_QUEUE &&
(tun->numqueues + tun->numdisabled > 1)) {
/* One or more queue has already been attached, no need
* to initialize the device again.
*/
return 0;
}
}
else {
char *name;
unsigned long flags = 0;
int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
MAX_TAP_QUEUES : 1;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = security_tun_dev_create();
if (err < 0)
return err;
/* Set dev type */
if (ifr->ifr_flags & IFF_TUN) {
/* TUN device */
flags |= IFF_TUN;
name = "tun%d";
} else if (ifr->ifr_flags & IFF_TAP) {
/* TAP device */
flags |= IFF_TAP;
name = "tap%d";
} else
return -EINVAL;
if (*ifr->ifr_name)
name = ifr->ifr_name;
dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
NET_NAME_UNKNOWN, tun_setup, queues,
queues);
if (!dev)
return -ENOMEM;
err = dev_get_valid_name(net, dev, name);
if (err < 0)
goto err_free_dev;
dev_net_set(dev, net);
dev->rtnl_link_ops = &tun_link_ops;
dev->ifindex = tfile->ifindex;
dev->sysfs_groups[0] = &tun_attr_group;
tun = netdev_priv(dev);
tun->dev = dev;
tun->flags = flags;
tun->txflt.count = 0;
tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
tun->align = NET_SKB_PAD;
tun->filter_attached = false;
tun->sndbuf = tfile->socket.sk->sk_sndbuf;
tun->rx_batched = 0;
tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
if (!tun->pcpu_stats) {
err = -ENOMEM;
goto err_free_dev;
}
spin_lock_init(&tun->lock);
err = security_tun_dev_alloc_security(&tun->security);
if (err < 0)
goto err_free_stat;
tun_net_init(dev);
tun_flow_init(tun);
dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX;
dev->features = dev->hw_features | NETIF_F_LLTX;
dev->vlan_features = dev->features &
~(NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX);
INIT_LIST_HEAD(&tun->disabled);
err = tun_attach(tun, file, false);
if (err < 0)
goto err_free_flow;
err = register_netdevice(tun->dev);
if (err < 0)
goto err_detach;
}
netif_carrier_on(tun->dev);
tun_debug(KERN_INFO, tun, "tun_set_iff\n");
tun->flags = (tun->flags & ~TUN_FEATURES) |
(ifr->ifr_flags & TUN_FEATURES);
/* Make sure persistent devices do not get stuck in
* xoff state.
*/
if (netif_running(tun->dev))
netif_tx_wake_all_queues(tun->dev);
strcpy(ifr->ifr_name, tun->dev->name);
return 0;
err_detach:
tun_detach_all(dev);
/* register_netdevice() already called tun_free_netdev() */
goto err_free_dev;
err_free_flow:
tun_flow_uninit(tun);
security_tun_dev_free_security(tun->security);
err_free_stat:
free_percpu(tun->pcpu_stats);
err_free_dev:
free_netdev(dev);
return err;
}
| 170,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool XmlReader::LoadFile(const std::string& file_path) {
const int kParseOptions = XML_PARSE_RECOVER | // recover on errors
XML_PARSE_NONET | // forbid network access
XML_PARSE_NOXXE; // no external entities
reader_ = xmlReaderForFile(file_path.c_str(), NULL, kParseOptions);
return reader_ != NULL;
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787 | bool XmlReader::LoadFile(const std::string& file_path) {
const int kParseOptions = XML_PARSE_RECOVER | // recover on errors
XML_PARSE_NONET; // forbid network access
reader_ = xmlReaderForFile(file_path.c_str(), NULL, kParseOptions);
return reader_ != NULL;
}
| 172,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void receive_tcppacket(connection_t *c, const char *buffer, int len) {
vpn_packet_t outpkt;
outpkt.len = len;
if(c->options & OPTION_TCPONLY)
outpkt.priority = 0;
else
outpkt.priority = -1;
memcpy(outpkt.data, buffer, len);
receive_packet(c->node, &outpkt);
}
Commit Message: Drop packets forwarded via TCP if they are too big (CVE-2013-1428).
Normally all requests sent via the meta connections are checked so that they
cannot be larger than the input buffer. However, when packets are forwarded via
meta connections, they are copied into a packet buffer without checking whether
it fits into it. Since the packet buffer is allocated on the stack, this in
effect allows an authenticated remote node to cause a stack overflow.
This issue was found by Martin Schobert.
CWE ID: CWE-119 | void receive_tcppacket(connection_t *c, const char *buffer, int len) {
vpn_packet_t outpkt;
if(len > sizeof outpkt.data)
return;
outpkt.len = len;
if(c->options & OPTION_TCPONLY)
outpkt.priority = 0;
else
outpkt.priority = -1;
memcpy(outpkt.data, buffer, len);
receive_packet(c->node, &outpkt);
}
| 166,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index++;
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
if (intern->file_name) {
efree(intern->file_name);
intern->file_name = NULL;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index++;
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
if (intern->file_name) {
efree(intern->file_name);
intern->file_name = NULL;
}
}
| 167,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
#if defined(OS_WIN)
base::SharedMemory shared_memory(transfer_buffer,
false,
channel_->renderer_process());
#else
#endif
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 170,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index, ret;
s->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE);
return AVERROR(EINVAL);
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
switch (s->vqa_version) {
case 1:
case 2:
break;
case 3:
avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version);
return AVERROR_PATCHWELCOME;
default:
avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version);
return AVERROR_PATCHWELCOME;
}
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if ((ret = av_image_check_size(s->width, s->height, 0, avctx)) < 0) {
s->width= s->height= 0;
return ret;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return AVERROR_INVALIDDATA;
}
if (s->width % s->vector_width || s->height % s->vector_height) {
av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
return AVERROR_INVALIDDATA;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
if (!s->codebook)
goto fail;
s->next_codebook_buffer = av_malloc(s->codebook_size);
if (!s->next_codebook_buffer)
goto fail;
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_mallocz(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
Commit Message: avcodec/vqavideo: Set video size
Fixes: out of array access
Fixes: 15919/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_VQA_fuzzer-5657368257363968
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: | static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index, ret;
s->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE);
return AVERROR(EINVAL);
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
switch (s->vqa_version) {
case 1:
case 2:
break;
case 3:
avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version);
return AVERROR_PATCHWELCOME;
default:
avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version);
return AVERROR_PATCHWELCOME;
}
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if ((ret = ff_set_dimensions(avctx, s->width, s->height)) < 0) {
s->width= s->height= 0;
return ret;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return AVERROR_INVALIDDATA;
}
if (s->width % s->vector_width || s->height % s->vector_height) {
av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
return AVERROR_INVALIDDATA;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
if (!s->codebook)
goto fail;
s->next_codebook_buffer = av_malloc(s->codebook_size);
if (!s->next_codebook_buffer)
goto fail;
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_mallocz(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
| 169,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: e1000e_write_packet_to_guest(E1000ECore *core, struct NetRxPkt *pkt,
const E1000E_RxRing *rxr,
const E1000E_RSSInfo *rss_info)
{
PCIDevice *d = core->owner;
dma_addr_t base;
uint8_t desc[E1000_MAX_RX_DESC_LEN];
size_t desc_size;
size_t desc_offset = 0;
size_t iov_ofs = 0;
struct iovec *iov = net_rx_pkt_get_iovec(pkt);
size_t size = net_rx_pkt_get_total_len(pkt);
size_t total_size = size + e1000x_fcs_len(core->mac);
const E1000E_RingInfo *rxi;
size_t ps_hdr_len = 0;
bool do_ps = e1000e_do_ps(core, pkt, &ps_hdr_len);
bool is_first = true;
rxi = rxr->i;
do {
hwaddr ba[MAX_PS_BUFFERS];
e1000e_ba_state bastate = { { 0 } };
bool is_last = false;
desc_size = total_size - desc_offset;
if (desc_size > core->rx_desc_buf_size) {
desc_size = core->rx_desc_buf_size;
desc_size = core->rx_desc_buf_size;
}
base = e1000e_ring_head_descr(core, rxi);
pci_dma_read(d, base, &desc, core->rx_desc_len);
if (ba[0]) {
if (desc_offset < size) {
static const uint32_t fcs_pad;
size_t iov_copy;
size_t copy_size = size - desc_offset;
if (copy_size > core->rx_desc_buf_size) {
copy_size = core->rx_desc_buf_size;
}
/* For PS mode copy the packet header first */
if (do_ps) {
if (is_first) {
size_t ps_hdr_copied = 0;
do {
iov_copy = MIN(ps_hdr_len - ps_hdr_copied,
iov->iov_len - iov_ofs);
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
iov->iov_base, iov_copy);
copy_size -= iov_copy;
ps_hdr_copied += iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
} while (ps_hdr_copied < ps_hdr_len);
is_first = false;
} else {
/* Leave buffer 0 of each descriptor except first */
/* empty as per spec 7.1.5.1 */
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
NULL, 0);
}
}
/* Copy packet payload */
while (copy_size) {
iov_copy = MIN(copy_size, iov->iov_len - iov_ofs);
e1000e_write_to_rx_buffers(core, &ba, &bastate,
iov->iov_base + iov_ofs, iov_copy);
copy_size -= iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
}
if (desc_offset + desc_size >= total_size) {
/* Simulate FCS checksum presence in the last descriptor */
e1000e_write_to_rx_buffers(core, &ba, &bastate,
(const char *) &fcs_pad, e1000x_fcs_len(core->mac));
}
}
desc_offset += desc_size;
if (desc_offset >= total_size) {
is_last = true;
}
} else { /* as per intel docs; skip descriptors with null buf addr */
trace_e1000e_rx_null_descriptor();
}
e1000e_write_rx_descr(core, desc, is_last ? core->rx_pkt : NULL,
rss_info, do_ps ? ps_hdr_len : 0, &bastate.written);
pci_dma_write(d, base, &desc, core->rx_desc_len);
e1000e_ring_advance(core, rxi,
core->rx_desc_len / E1000_MIN_RX_DESC_LEN);
} while (desc_offset < total_size);
e1000e_update_rx_stats(core, size, total_size);
}
Commit Message:
CWE ID: CWE-835 | e1000e_write_packet_to_guest(E1000ECore *core, struct NetRxPkt *pkt,
const E1000E_RxRing *rxr,
const E1000E_RSSInfo *rss_info)
{
PCIDevice *d = core->owner;
dma_addr_t base;
uint8_t desc[E1000_MAX_RX_DESC_LEN];
size_t desc_size;
size_t desc_offset = 0;
size_t iov_ofs = 0;
struct iovec *iov = net_rx_pkt_get_iovec(pkt);
size_t size = net_rx_pkt_get_total_len(pkt);
size_t total_size = size + e1000x_fcs_len(core->mac);
const E1000E_RingInfo *rxi;
size_t ps_hdr_len = 0;
bool do_ps = e1000e_do_ps(core, pkt, &ps_hdr_len);
bool is_first = true;
rxi = rxr->i;
do {
hwaddr ba[MAX_PS_BUFFERS];
e1000e_ba_state bastate = { { 0 } };
bool is_last = false;
desc_size = total_size - desc_offset;
if (desc_size > core->rx_desc_buf_size) {
desc_size = core->rx_desc_buf_size;
desc_size = core->rx_desc_buf_size;
}
if (e1000e_ring_empty(core, rxi)) {
return;
}
base = e1000e_ring_head_descr(core, rxi);
pci_dma_read(d, base, &desc, core->rx_desc_len);
if (ba[0]) {
if (desc_offset < size) {
static const uint32_t fcs_pad;
size_t iov_copy;
size_t copy_size = size - desc_offset;
if (copy_size > core->rx_desc_buf_size) {
copy_size = core->rx_desc_buf_size;
}
/* For PS mode copy the packet header first */
if (do_ps) {
if (is_first) {
size_t ps_hdr_copied = 0;
do {
iov_copy = MIN(ps_hdr_len - ps_hdr_copied,
iov->iov_len - iov_ofs);
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
iov->iov_base, iov_copy);
copy_size -= iov_copy;
ps_hdr_copied += iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
} while (ps_hdr_copied < ps_hdr_len);
is_first = false;
} else {
/* Leave buffer 0 of each descriptor except first */
/* empty as per spec 7.1.5.1 */
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
NULL, 0);
}
}
/* Copy packet payload */
while (copy_size) {
iov_copy = MIN(copy_size, iov->iov_len - iov_ofs);
e1000e_write_to_rx_buffers(core, &ba, &bastate,
iov->iov_base + iov_ofs, iov_copy);
copy_size -= iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
}
if (desc_offset + desc_size >= total_size) {
/* Simulate FCS checksum presence in the last descriptor */
e1000e_write_to_rx_buffers(core, &ba, &bastate,
(const char *) &fcs_pad, e1000x_fcs_len(core->mac));
}
}
desc_offset += desc_size;
if (desc_offset >= total_size) {
is_last = true;
}
} else { /* as per intel docs; skip descriptors with null buf addr */
trace_e1000e_rx_null_descriptor();
}
e1000e_write_rx_descr(core, desc, is_last ? core->rx_pkt : NULL,
rss_info, do_ps ? ps_hdr_len : 0, &bastate.written);
pci_dma_write(d, base, &desc, core->rx_desc_len);
e1000e_ring_advance(core, rxi,
core->rx_desc_len / E1000_MIN_RX_DESC_LEN);
} while (desc_offset < total_size);
e1000e_update_rx_stats(core, size, total_size);
}
| 164,800 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
vsep = memchr(var->ptr, '&', var->end - var->ptr);
if (!vsep) {
if (!eof) {
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
return 1;
}
Commit Message: Fix bug #73807
CWE ID: CWE-400 | static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *start, *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
start = var->ptr + var->already_scanned;
vsep = memchr(start, '&', var->end - start);
if (!vsep) {
if (!eof) {
var->already_scanned = var->end - var->ptr;
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
var->already_scanned = 0;
return 1;
}
| 168,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NetworkHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
host_ = frame_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::SetRenderer(RenderProcessHost* process_host,
void NetworkHandler::SetRenderer(int render_process_host_id,
RenderFrameHostImpl* frame_host) {
RenderProcessHost* process_host =
RenderProcessHost::FromID(render_process_host_id);
if (process_host) {
storage_partition_ = process_host->GetStoragePartition();
browser_context_ = process_host->GetBrowserContext();
} else {
storage_partition_ = nullptr;
browser_context_ = nullptr;
}
host_ = frame_host;
}
| 172,763 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return compression_entries_[idx];
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
const ptrdiff_t count = compression_entries_end_ - compression_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return compression_entries_[idx];
}
| 173,815 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key)
{
unsigned long modulus_bitlen, modulus_bytelen, x;
int err;
unsigned char *tmpbuf;
LTC_ARGCHK(hash != NULL);
LTC_ARGCHK(sig != NULL);
LTC_ARGCHK(stat != NULL);
LTC_ARGCHK(key != NULL);
/* default to invalid */
*stat = 0;
/* valid padding? */
if ((padding != LTC_PKCS_1_V1_5) &&
(padding != LTC_PKCS_1_PSS)) {
return CRYPT_PK_INVALID_PADDING;
}
if (padding == LTC_PKCS_1_PSS) {
/* valid hash ? */
if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
return err;
}
}
/* get modulus len in bits */
modulus_bitlen = mp_count_bits( (key->N));
/* outlen must be at least the size of the modulus */
modulus_bytelen = mp_unsigned_bin_size( (key->N));
if (modulus_bytelen != siglen) {
return CRYPT_INVALID_PACKET;
}
/* allocate temp buffer for decoded sig */
tmpbuf = XMALLOC(siglen);
if (tmpbuf == NULL) {
return CRYPT_MEM;
}
/* RSA decode it */
x = siglen;
if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
XFREE(tmpbuf);
return err;
}
/* make sure the output is the right size */
if (x != siglen) {
XFREE(tmpbuf);
return CRYPT_INVALID_PACKET;
}
if (padding == LTC_PKCS_1_PSS) {
/* PSS decode and verify it */
if(modulus_bitlen%8 == 1){
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf+1, x-1, saltlen, hash_idx, modulus_bitlen, stat);
}
else{
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf, x, saltlen, hash_idx, modulus_bitlen, stat);
}
} else {
/* PKCS #1 v1.5 decode it */
unsigned char *out;
unsigned long outlen, loid[16];
int decoded;
ltc_asn1_list digestinfo[2], siginfo[2];
/* not all hashes have OIDs... so sad */
if (hash_descriptor[hash_idx].OIDlen == 0) {
err = CRYPT_INVALID_ARG;
goto bail_2;
}
/* allocate temp buffer for decoded hash */
outlen = ((modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0)) - 3;
out = XMALLOC(outlen);
if (out == NULL) {
err = CRYPT_MEM;
goto bail_2;
}
if ((err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_PKCS_1_EMSA, modulus_bitlen, out, &outlen, &decoded)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* now we must decode out[0...outlen-1] using ASN.1, test the OID and then test the hash */
/* construct the SEQUENCE
SEQUENCE {
SEQUENCE {hashoid OID
blah NULL
}
hash OCTET STRING
}
*/
LTC_SET_ASN1(digestinfo, 0, LTC_ASN1_OBJECT_IDENTIFIER, loid, sizeof(loid)/sizeof(loid[0]));
LTC_SET_ASN1(digestinfo, 1, LTC_ASN1_NULL, NULL, 0);
LTC_SET_ASN1(siginfo, 0, LTC_ASN1_SEQUENCE, digestinfo, 2);
LTC_SET_ASN1(siginfo, 1, LTC_ASN1_OCTET_STRING, tmpbuf, siglen);
if ((err = der_decode_sequence(out, outlen, siginfo, 2)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* test OID */
if ((digestinfo[0].size == hash_descriptor[hash_idx].OIDlen) &&
(XMEMCMP(digestinfo[0].data, hash_descriptor[hash_idx].OID, sizeof(unsigned long) * hash_descriptor[hash_idx].OIDlen) == 0) &&
(siginfo[1].size == hashlen) &&
(XMEMCMP(siginfo[1].data, hash, hashlen) == 0)) {
*stat = 1;
}
#ifdef LTC_CLEAN_STACK
zeromem(out, outlen);
#endif
XFREE(out);
}
bail_2:
#ifdef LTC_CLEAN_STACK
zeromem(tmpbuf, siglen);
#endif
XFREE(tmpbuf);
return err;
}
Commit Message: rsa_verify_hash: fix possible bleichenbacher signature attack
CWE ID: CWE-20 | int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key)
{
unsigned long modulus_bitlen, modulus_bytelen, x;
int err;
unsigned char *tmpbuf;
LTC_ARGCHK(hash != NULL);
LTC_ARGCHK(sig != NULL);
LTC_ARGCHK(stat != NULL);
LTC_ARGCHK(key != NULL);
/* default to invalid */
*stat = 0;
/* valid padding? */
if ((padding != LTC_PKCS_1_V1_5) &&
(padding != LTC_PKCS_1_PSS)) {
return CRYPT_PK_INVALID_PADDING;
}
if (padding == LTC_PKCS_1_PSS) {
/* valid hash ? */
if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
return err;
}
}
/* get modulus len in bits */
modulus_bitlen = mp_count_bits( (key->N));
/* outlen must be at least the size of the modulus */
modulus_bytelen = mp_unsigned_bin_size( (key->N));
if (modulus_bytelen != siglen) {
return CRYPT_INVALID_PACKET;
}
/* allocate temp buffer for decoded sig */
tmpbuf = XMALLOC(siglen);
if (tmpbuf == NULL) {
return CRYPT_MEM;
}
/* RSA decode it */
x = siglen;
if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
XFREE(tmpbuf);
return err;
}
/* make sure the output is the right size */
if (x != siglen) {
XFREE(tmpbuf);
return CRYPT_INVALID_PACKET;
}
if (padding == LTC_PKCS_1_PSS) {
/* PSS decode and verify it */
if(modulus_bitlen%8 == 1){
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf+1, x-1, saltlen, hash_idx, modulus_bitlen, stat);
}
else{
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf, x, saltlen, hash_idx, modulus_bitlen, stat);
}
} else {
/* PKCS #1 v1.5 decode it */
unsigned char *out;
unsigned long outlen, loid[16], reallen;
int decoded;
ltc_asn1_list digestinfo[2], siginfo[2];
/* not all hashes have OIDs... so sad */
if (hash_descriptor[hash_idx].OIDlen == 0) {
err = CRYPT_INVALID_ARG;
goto bail_2;
}
/* allocate temp buffer for decoded hash */
outlen = ((modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0)) - 3;
out = XMALLOC(outlen);
if (out == NULL) {
err = CRYPT_MEM;
goto bail_2;
}
if ((err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_PKCS_1_EMSA, modulus_bitlen, out, &outlen, &decoded)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* now we must decode out[0...outlen-1] using ASN.1, test the OID and then test the hash */
/* construct the SEQUENCE
SEQUENCE {
SEQUENCE {hashoid OID
blah NULL
}
hash OCTET STRING
}
*/
LTC_SET_ASN1(digestinfo, 0, LTC_ASN1_OBJECT_IDENTIFIER, loid, sizeof(loid)/sizeof(loid[0]));
LTC_SET_ASN1(digestinfo, 1, LTC_ASN1_NULL, NULL, 0);
LTC_SET_ASN1(siginfo, 0, LTC_ASN1_SEQUENCE, digestinfo, 2);
LTC_SET_ASN1(siginfo, 1, LTC_ASN1_OCTET_STRING, tmpbuf, siglen);
if ((err = der_decode_sequence(out, outlen, siginfo, 2)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
if ((err = der_length_sequence(siginfo, 2, &reallen)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* test OID */
if ((reallen == outlen) &&
(digestinfo[0].size == hash_descriptor[hash_idx].OIDlen) &&
(XMEMCMP(digestinfo[0].data, hash_descriptor[hash_idx].OID, sizeof(unsigned long) * hash_descriptor[hash_idx].OIDlen) == 0) &&
(siginfo[1].size == hashlen) &&
(XMEMCMP(siginfo[1].data, hash, hashlen) == 0)) {
*stat = 1;
}
#ifdef LTC_CLEAN_STACK
zeromem(out, outlen);
#endif
XFREE(out);
}
bail_2:
#ifdef LTC_CLEAN_STACK
zeromem(tmpbuf, siglen);
#endif
XFREE(tmpbuf);
return err;
}
| 168,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::unique_ptr<WebContents> CreateWebContents() {
std::unique_ptr<WebContents> web_contents = CreateTestWebContents();
content::WebContentsTester::For(web_contents.get())
->NavigateAndCommit(GURL("https://www.example.com"));
return web_contents;
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | std::unique_ptr<WebContents> CreateWebContents() {
std::unique_ptr<WebContents> web_contents = CreateTestWebContents();
ResourceCoordinatorTabHelper::CreateForWebContents(web_contents.get());
content::WebContentsTester::For(web_contents.get())
->NavigateAndCommit(GURL("https://www.example.com"));
base::RepeatingClosure run_loop_cb = base::BindRepeating(
&base::TestMockTimeTaskRunner::RunUntilIdle, task_runner_);
testing::WaitForLocalDBEntryToBeInitialized(web_contents.get(),
run_loop_cb);
testing::ExpireLocalDBObservationWindows(web_contents.get());
return web_contents;
}
| 172,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
/* Undo the ref. */
g_object_unref (subdir);
dir = GSF_INFILE_TAR (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
}
Commit Message: tar: fix crash on broken tar file.
CWE ID: CWE-476 | tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
dir = GSF_IS_INFILE_TAR (subdir)
? GSF_INFILE_TAR (subdir)
: dir;
/* Undo the ref. */
g_object_unref (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
}
| 166,843 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b)
{
return b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24);
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b)
{
return (unsigned int)b[0] | ((unsigned int)b[1]<<8) |
((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24);
}
| 168,200 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginEnabled(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginAvailable(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
| 171,476 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothOptionsHandler::DisplayPasskey(
chromeos::BluetoothDevice* device,
int passkey,
int entered) {
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void BluetoothOptionsHandler::DisplayPasskey(
chromeos::BluetoothDevice* device,
int passkey,
int entered) {
DictionaryValue params;
params.SetString("pairing", "bluetoothRemotePasskey");
params.SetInteger("passkey", passkey);
params.SetInteger("entered", entered);
SendDeviceNotification(device, ¶ms);
}
| 170,967 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
Commit Message: fix deinterlacing for small pictures
fixes #12
CWE ID: CWE-119 | static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {
u16 tocopy;
struct ngiflib_gif * p = i->parent;
while(n > 0) {
tocopy = (context->Xtogo < n) ? context->Xtogo : n;
if(!i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);
pixels += tocopy;
context->frbuff_p.p8 += tocopy;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
int j;
for(j = (int)tocopy; j > 0; j--) {
*(context->frbuff_p.p32++) =
GifIndexToTrueColor(i->palette, *pixels++);
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
int j;
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;
pixels++;
context->frbuff_p.p8++;
}
#ifndef NGIFLIB_INDEXED_ONLY
} else {
for(j = (int)tocopy; j > 0; j--) {
if(*pixels != i->gce.transparent_color) {
*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);
}
pixels++;
context->frbuff_p.p32++;
}
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
context->Xtogo -= tocopy;
if(context->Xtogo == 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
while(context->pass > 0 && context->pass < 4 &&
context->curY >= p->height) {
switch(++context->pass) {
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY = i->posY + 4;
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY = i->posY + 2;
break;
case 4: /* 4th pass : every odd row */
context->curY = i->posY + 1;
break;
}
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
n -= tocopy;
}
}
| 169,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
Commit Message: KVM: x86: Fix potential divide by 0 in lapic (CVE-2013-6367)
Under guest controllable circumstances apic_get_tmcct will execute a
divide by zero and cause a crash. If the guest cpuid support
tsc deadline timers and performs the following sequence of requests
the host will crash.
- Set the mode to periodic
- Set the TMICT to 0
- Set the mode bits to 11 (neither periodic, nor one shot, nor tsc deadline)
- Set the TMICT to non-zero.
Then the lapic_timer.period will be 0, but the TMICT will not be. If the
guest then reads from the TMCCT then the host will perform a divide by 0.
This patch ensures that if the lapic_timer.period is 0, then the division
does not occur.
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189 | static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0 ||
apic->lapic_timer.period == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
| 165,951 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaStreamDispatcherHost::CancelRequest(int page_request_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->CancelRequest(render_process_id_, render_frame_id_,
page_request_id);
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamDispatcherHost::CancelRequest(int page_request_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->CancelRequest(render_process_id_, render_frame_id_,
requester_id_, page_request_id);
}
| 173,093 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125 | METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
int cmaplen = source->cmap_length;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
| 169,836 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ixheaacd_cmplx_anal_fft != NULL)
(*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787 | WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ptr_hbe_txposer->ixheaacd_cmplx_anal_fft != NULL)
(*(ptr_hbe_txposer->ixheaacd_cmplx_anal_fft))(u_in, u_out,
anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
| 174,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mct_u232_port_probe(struct usb_serial_port *port)
{
struct mct_u232_private *priv;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* Use second interrupt-in endpoint for reading. */
priv->read_urb = port->serial->port[1]->interrupt_in_urb;
priv->read_urb->context = port;
spin_lock_init(&priv->lock);
usb_set_serial_port_data(port, priv);
return 0;
}
Commit Message: USB: mct_u232: add sanity checking in probe
An attack using the lack of sanity checking in probe is known. This
patch checks for the existence of a second port.
CVE-2016-3136
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
[johan: add error message ]
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int mct_u232_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct mct_u232_private *priv;
/* check first to simplify error handling */
if (!serial->port[1] || !serial->port[1]->interrupt_in_urb) {
dev_err(&port->dev, "expected endpoint missing\n");
return -ENODEV;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* Use second interrupt-in endpoint for reading. */
priv->read_urb = serial->port[1]->interrupt_in_urb;
priv->read_urb->context = port;
spin_lock_init(&priv->lock);
usb_set_serial_port_data(port, priv);
return 0;
}
| 167,361 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int uhid_write(int fd, const struct uhid_event *ev)
{
ssize_t ret = write(fd, ev, sizeof(*ev));
if (ret < 0){
int rtn = -errno;
APPL_TRACE_ERROR("%s: Cannot write to uhid:%s",
__FUNCTION__, strerror(errno));
return rtn;
} else if (ret != (ssize_t)sizeof(*ev)) {
APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu",
__FUNCTION__, ret, sizeof(*ev));
return -EFAULT;
}
return 0;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static int uhid_write(int fd, const struct uhid_event *ev)
{
ssize_t ret = TEMP_FAILURE_RETRY(write(fd, ev, sizeof(*ev)));
if (ret < 0){
int rtn = -errno;
APPL_TRACE_ERROR("%s: Cannot write to uhid:%s",
__FUNCTION__, strerror(errno));
return rtn;
} else if (ret != (ssize_t)sizeof(*ev)) {
APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu",
__FUNCTION__, ret, sizeof(*ev));
return -EFAULT;
}
return 0;
}
| 173,433 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_mlppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLPPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link
* best indicator if the cookie looks like a proto */
if (ndo->ndo_eflag &&
EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&
EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))
ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle));
p+=l2info.header_len;
/* first try the LSQ protos */
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
/* IP traffic going to the RE would not have a cookie
* -> this must be incoming IS-IS over PPP
*/
if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))
ppp_print(ndo, p, l2info.length);
else
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length, l2info.caplen);
return l2info.header_len;
default:
break;
}
/* zero length cookie ? */
switch (EXTRACT_16BITS(&l2info.cookie)) {
case PPP_OSI:
ppp_print(ndo, p - 2, l2info.length + 2);
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */
default:
ppp_print(ndo, p, l2info.length);
break;
}
return l2info.header_len;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | juniper_mlppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLPPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link
* best indicator if the cookie looks like a proto */
if (ndo->ndo_eflag &&
EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&
EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))
ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle));
p+=l2info.header_len;
/* first try the LSQ protos */
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
/* IP traffic going to the RE would not have a cookie
* -> this must be incoming IS-IS over PPP
*/
if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))
ppp_print(ndo, p, l2info.length);
else
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length);
return l2info.header_len;
default:
break;
}
/* zero length cookie ? */
switch (EXTRACT_16BITS(&l2info.cookie)) {
case PPP_OSI:
ppp_print(ndo, p - 2, l2info.length + 2);
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */
default:
ppp_print(ndo, p, l2info.length);
break;
}
return l2info.header_len;
}
| 167,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragTimeoutTest(void)
{
int i;
int ret = 0;
/* Setup a small numberr of trackers. */
if (ConfSet("defrag.trackers", "16") != 1) {
printf("ConfSet failed: ");
goto end;
}
DefragInit();
/* Load in 16 packets. */
for (i = 0; i < 16; i++) {
Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
Packet *tp = Defrag(NULL, NULL, p, NULL);
SCFree(p);
if (tp != NULL) {
SCFree(tp);
goto end;
}
}
/* Build a new packet but push the timestamp out by our timeout.
* This should force our previous fragments to be timed out. */
Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
p->ts.tv_sec += (defrag_context->timeout + 1);
Packet *tp = Defrag(NULL, NULL, p, NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
DefragTracker *tracker = DefragLookupTrackerFromHash(p);
if (tracker == NULL)
goto end;
if (tracker->id != 99)
goto end;
SCFree(p);
ret = 1;
end:
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragTimeoutTest(void)
{
int i;
int ret = 0;
/* Setup a small numberr of trackers. */
if (ConfSet("defrag.trackers", "16") != 1) {
printf("ConfSet failed: ");
goto end;
}
DefragInit();
/* Load in 16 packets. */
for (i = 0; i < 16; i++) {
Packet *p = BuildTestPacket(IPPROTO_ICMP,i, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
Packet *tp = Defrag(NULL, NULL, p, NULL);
SCFree(p);
if (tp != NULL) {
SCFree(tp);
goto end;
}
}
/* Build a new packet but push the timestamp out by our timeout.
* This should force our previous fragments to be timed out. */
Packet *p = BuildTestPacket(IPPROTO_ICMP, 99, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
p->ts.tv_sec += (defrag_context->timeout + 1);
Packet *tp = Defrag(NULL, NULL, p, NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
DefragTracker *tracker = DefragLookupTrackerFromHash(p);
if (tracker == NULL)
goto end;
if (tracker->id != 99)
goto end;
SCFree(p);
ret = 1;
end:
DefragDestroy();
return ret;
}
| 168,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickString(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickString(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
Commit Message: ...
CWE ID: CWE-189 | static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent-1);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickString(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickString(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
| 168,524 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) {
done_status_ = done_status;
if (TrackedCallback::IsPending(pending_callback_))
RunCallback(done_status_);
}
Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called.
BUG=137778
Review URL: https://chromiumcodereview.appspot.com/10797037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) {
done_status_ = done_status;
user_buffer_ = NULL;
user_buffer_size_ = 0;
if (TrackedCallback::IsPending(pending_callback_))
RunCallback(done_status_);
}
| 170,900 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
Commit Message: All: Merge some file writing extension checks
CWE ID: CWE-269 | void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
if (!COM_CompareExtension(filename, ".txt"))
{
Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n");
return;
}
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
| 170,079 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx();
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
/*
* The actual context is not yet determined, set the output
* context handle to refer to the spnego context itself.
*/
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
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 | init_ctx_new(OM_uint32 *minor_status,
spnego_gss_cred_id_t spcred,
gss_ctx_id_t *ctx,
send_token_flag *tokflag)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = NULL;
sc = create_spnego_ctx(1);
if (sc == NULL)
return GSS_S_FAILURE;
/* determine negotiation mech set */
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,
&sc->mech_set);
if (ret != GSS_S_COMPLETE)
goto cleanup;
/* Set an initial internal mech to make the first context token. */
sc->internal_mech = &sc->mech_set->elements[0];
if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->ctx_handle = GSS_C_NO_CONTEXT;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
*tokflag = INIT_TOKEN_SEND;
ret = GSS_S_CONTINUE_NEEDED;
cleanup:
release_spnego_ctx(&sc);
return ret;
}
| 166,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)
{
int i;
int ret = 0;
DefragInit();
/*
* Build the packets.
*/
int id = 1;
Packet *packets[17];
memset(packets, 0x00, sizeof(packets));
/*
* Original fragments.
*/
/* A*24 at 0. */
packets[0] = IPV6BuildTestPacket(id, 0, 1, 'A', 24);
/* B*15 at 32. */
packets[1] = IPV6BuildTestPacket(id, 32 >> 3, 1, 'B', 16);
/* C*24 at 48. */
packets[2] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'C', 24);
/* D*8 at 80. */
packets[3] = IPV6BuildTestPacket(id, 80 >> 3, 1, 'D', 8);
/* E*16 at 104. */
packets[4] = IPV6BuildTestPacket(id, 104 >> 3, 1, 'E', 16);
/* F*24 at 120. */
packets[5] = IPV6BuildTestPacket(id, 120 >> 3, 1, 'F', 24);
/* G*16 at 144. */
packets[6] = IPV6BuildTestPacket(id, 144 >> 3, 1, 'G', 16);
/* H*16 at 160. */
packets[7] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'H', 16);
/* I*8 at 176. */
packets[8] = IPV6BuildTestPacket(id, 176 >> 3, 1, 'I', 8);
/*
* Overlapping subsequent fragments.
*/
/* J*32 at 8. */
packets[9] = IPV6BuildTestPacket(id, 8 >> 3, 1, 'J', 32);
/* K*24 at 48. */
packets[10] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'K', 24);
/* L*24 at 72. */
packets[11] = IPV6BuildTestPacket(id, 72 >> 3, 1, 'L', 24);
/* M*24 at 96. */
packets[12] = IPV6BuildTestPacket(id, 96 >> 3, 1, 'M', 24);
/* N*8 at 128. */
packets[13] = IPV6BuildTestPacket(id, 128 >> 3, 1, 'N', 8);
/* O*8 at 152. */
packets[14] = IPV6BuildTestPacket(id, 152 >> 3, 1, 'O', 8);
/* P*8 at 160. */
packets[15] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'P', 8);
/* Q*16 at 176. */
packets[16] = IPV6BuildTestPacket(id, 176 >> 3, 0, 'Q', 16);
default_policy = policy;
/* Send all but the last. */
for (i = 0; i < 9; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) {
goto end;
}
}
int overlap = 0;
for (; i < 16; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) {
overlap++;
}
}
if (!overlap)
goto end;
/* And now the last one. */
Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);
if (reassembled == NULL)
goto end;
if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0)
goto end;
if (IPV6_GET_PLEN(reassembled) != 192)
goto end;
SCFree(reassembled);
/* Make sure all frags were returned to the pool. */
if (defrag_context->frag_pool->outstanding != 0) {
printf("defrag_context->frag_pool->outstanding %u: ", defrag_context->frag_pool->outstanding);
goto end;
}
ret = 1;
end:
for (i = 0; i < 17; i++) {
SCFree(packets[i]);
}
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len)
{
int i;
int ret = 0;
DefragInit();
/*
* Build the packets.
*/
int id = 1;
Packet *packets[17];
memset(packets, 0x00, sizeof(packets));
/*
* Original fragments.
*/
/* A*24 at 0. */
packets[0] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 24);
/* B*15 at 32. */
packets[1] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 32 >> 3, 1, 'B', 16);
/* C*24 at 48. */
packets[2] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'C', 24);
/* D*8 at 80. */
packets[3] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 80 >> 3, 1, 'D', 8);
/* E*16 at 104. */
packets[4] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 104 >> 3, 1, 'E', 16);
/* F*24 at 120. */
packets[5] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 120 >> 3, 1, 'F', 24);
/* G*16 at 144. */
packets[6] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 144 >> 3, 1, 'G', 16);
/* H*16 at 160. */
packets[7] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'H', 16);
/* I*8 at 176. */
packets[8] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 1, 'I', 8);
/*
* Overlapping subsequent fragments.
*/
/* J*32 at 8. */
packets[9] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 8 >> 3, 1, 'J', 32);
/* K*24 at 48. */
packets[10] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'K', 24);
/* L*24 at 72. */
packets[11] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 72 >> 3, 1, 'L', 24);
/* M*24 at 96. */
packets[12] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 96 >> 3, 1, 'M', 24);
/* N*8 at 128. */
packets[13] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 128 >> 3, 1, 'N', 8);
/* O*8 at 152. */
packets[14] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 152 >> 3, 1, 'O', 8);
/* P*8 at 160. */
packets[15] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'P', 8);
/* Q*16 at 176. */
packets[16] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 0, 'Q', 16);
default_policy = policy;
/* Send all but the last. */
for (i = 0; i < 9; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) {
goto end;
}
}
int overlap = 0;
for (; i < 16; i++) {
Packet *tp = Defrag(NULL, NULL, packets[i], NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) {
overlap++;
}
}
if (!overlap)
goto end;
/* And now the last one. */
Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL);
if (reassembled == NULL)
goto end;
if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0)
goto end;
if (IPV6_GET_PLEN(reassembled) != 192)
goto end;
SCFree(reassembled);
/* Make sure all frags were returned to the pool. */
if (defrag_context->frag_pool->outstanding != 0) {
printf("defrag_context->frag_pool->outstanding %u: ", defrag_context->frag_pool->outstanding);
goto end;
}
ret = 1;
end:
for (i = 0; i < 17; i++) {
SCFree(packets[i]);
}
DefragDestroy();
return ret;
}
| 168,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuChannel::OnChannelConnected(int32 peer_pid) {
| 170,932 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
Commit Message: CVE-2017-13000/IEEE 802.15.4: Fix bug introduced by previous fix.
We've already advanced the pointer past the PAN ID, if present; it now
points to the address, so don't add 2 to it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| 170,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(int argc, char * * argv)
{
const char command0[] = { 0x00, 0x00 };
char command1[] = "\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice";
char command2[] = "\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice";
const char command3[] = { 0x03, 0x00 };
/* old versions of minissdpd would reject a command with
* a zero length string argument */
char command3compat[] = "\x03\x00ssdp:all";
char command4[] = "\x04\x00test:test:test";
const char bad_command[] = { 0xff, 0xff };
const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
const char command5[] = { 0x05, 0x00 };
int s;
int i;
void * tmp;
unsigned char * resp = NULL;
size_t respsize = 0;
unsigned char buf[4096];
ssize_t n;
int total = 0;
const char * sockpath = "/var/run/minissdpd.sock";
for(i=0; i<argc-1; i++) {
if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
}
command1[1] = sizeof(command1) - 3;
command2[1] = sizeof(command2) - 3;
command3compat[1] = sizeof(command3compat) - 3;
command4[1] = sizeof(command4) - 3;
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command0, sizeof(command0));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
if(n > 0) {
printversion(buf, n);
} else {
printf("Command 0 (get version) not supported\n");
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command1, sizeof(command1) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command2, sizeof(command2) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
buf[0] = 0; /* Slight hack for printing num devices when 0 */
n = SENDCOMMAND(command3, sizeof(command3));
n = read(s, buf, sizeof(buf));
if(n == 0) {
printf("command3 failed, testing compatible one\n");
close(s);
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1);
n = read(s, buf, sizeof(buf));
}
printf("Response received %d bytes\n", (int)n);
printf("Number of devices %d\n", (int)buf[0]);
while(n > 0) {
tmp = realloc(resp, respsize + n);
if(tmp == NULL) {
fprintf(stderr, "memory allocation error\n");
break;
}
resp = tmp;
respsize += n;
if (n > 0) {
memcpy(resp + total, buf, n);
total += n;
}
if (n < (ssize_t)sizeof(buf)) {
break;
}
n = read(s, buf, sizeof(buf));
printf("response received %d bytes\n", (int)n);
}
if(resp != NULL) {
printresponse(resp, total);
free(resp);
resp = NULL;
}
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command4, sizeof(command4));
/* no response for request type 4 */
n = SENDCOMMAND(bad_command, sizeof(bad_command));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(overflow, sizeof(overflow));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command5, sizeof(command5));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
close(s);
return 0;
}
Commit Message: minissdpd: Fix broken overflow test (p+l > buf+n) thanks to Salva Piero
CWE ID: CWE-125 | main(int argc, char * * argv)
{
const char command0[] = { 0x00, 0x00 };
char command1[] = "\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice";
char command2[] = "\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice";
const char command3[] = { 0x03, 0x00 };
/* old versions of minissdpd would reject a command with
* a zero length string argument */
char command3compat[] = "\x03\x00ssdp:all";
char command4[] = "\x04\x00test:test:test";
const char bad_command[] = { 0xff, 0xff };
const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
const char command5[] = { 0x05, 0x00 };
const char bad_command4[] = { 0x04, 0x01, 0x60, 0x8f, 0xff, 0xff, 0xff, 0x7f};
int s;
int i;
void * tmp;
unsigned char * resp = NULL;
size_t respsize = 0;
unsigned char buf[4096];
ssize_t n;
int total = 0;
const char * sockpath = "/var/run/minissdpd.sock";
for(i=0; i<argc-1; i++) {
if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
}
command1[1] = sizeof(command1) - 3;
command2[1] = sizeof(command2) - 3;
command3compat[1] = sizeof(command3compat) - 3;
command4[1] = sizeof(command4) - 3;
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command0, sizeof(command0));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
if(n > 0) {
printversion(buf, n);
} else {
printf("Command 0 (get version) not supported\n");
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command1, sizeof(command1) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command2, sizeof(command2) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
buf[0] = 0; /* Slight hack for printing num devices when 0 */
n = SENDCOMMAND(command3, sizeof(command3));
n = read(s, buf, sizeof(buf));
if(n == 0) {
printf("command3 failed, testing compatible one\n");
close(s);
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1);
n = read(s, buf, sizeof(buf));
}
printf("Response received %d bytes\n", (int)n);
printf("Number of devices %d\n", (int)buf[0]);
while(n > 0) {
tmp = realloc(resp, respsize + n);
if(tmp == NULL) {
fprintf(stderr, "memory allocation error\n");
break;
}
resp = tmp;
respsize += n;
if (n > 0) {
memcpy(resp + total, buf, n);
total += n;
}
if (n < (ssize_t)sizeof(buf)) {
break;
}
n = read(s, buf, sizeof(buf));
printf("response received %d bytes\n", (int)n);
}
if(resp != NULL) {
printresponse(resp, total);
free(resp);
resp = NULL;
}
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command4, sizeof(command4));
/* no response for request type 4 */
n = SENDCOMMAND(bad_command, sizeof(bad_command));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(overflow, sizeof(overflow));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command5, sizeof(command5));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(bad_command4, sizeof(bad_command4));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
close(s);
return 0;
}
| 168,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
while (p != (const ExceptionInfo *) NULL)
{
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
if ((p->severity >= ErrorException) && (p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119 | MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
ssize_t
i;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
for (i=0; p != (const ExceptionInfo *) NULL; i++)
{
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
if (i < MaxExceptions)
{
if ((p->severity >= ErrorException) &&
(p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
}
else
if (i == MaxExceptions)
MagickError(ResourceLimitError,"too many exceptions",
"exception processing suspended");
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
| 168,541 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщฟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зҙӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add Lao/Thai spoofable entries
U+0E1E (พ) => w
U+0E9E (ພ) => w
U+0E9F (ຟ) => w
U+0EA3 (ຣ) => s
U+0EAE (ຮ) => s
U+0E1A (บ) => u
U+0E9A (ບ) => u
Note that U+0E1F(ฟ) and U+0E23 (ร) were added a while ago.
BUG=833143
TEST=components_unittests --gtest_filter=*IDN*
Change-Id: I882e7d272cdca1d80aa23be94b4d7906ff8653c1
Reviewed-on: https://chromium-review.googlesource.com/1058710
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#562565}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+03C9 (ω), U+0448 (ш), U+0449 (щ), U+0E1E (พ),
// U+0E1F (ฟ), U+0E9E (ພ), U+0E9F (ຟ)} => w
// - {U+0D1F (ട), U+0E23 (ร), U+0EA3 (ຣ), U+0EAE (ຮ)} => s
// - {U+0E1A (บ), U+0E9A (ບ)} => u
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache */
if ((level == 2) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
Commit Message:
CWE ID: CWE-200 | int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache and go into the error state */
if (level == SSL3_AL_FATAL) {
if (s->session != NULL)
SSL_CTX_remove_session(s->session_ctx, s->session);
s->state = SSL_ST_ERR;
}
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
| 165,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
diacritic_remover_.get()->transliterate(ustr_host);
extra_confusable_mapper_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton));
}
Commit Message: Map U+04CF to lowercase L as well.
U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase
I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered
in some fonts.
If a host name contains it, calculate the confusability skeleton
twice, once with the default mapping to 'i' (lowercase I) and the 2nd
time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L)
also gets it treated as similar to digit 1 because the confusability
skeleton of digit 1 is 'l'.
Bug: 817247
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c
Reviewed-on: https://chromium-review.googlesource.com/974165
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Reviewed-by: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#551263}
CWE ID: | bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(host, 0, USET_SPAN_CONTAINED) == host.length())
diacritic_remover_.get()->transliterate(host);
extra_confusable_mapper_.get()->transliterate(host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString skeleton;
// Map U+04CF (ӏ) to lowercase L in addition to what uspoof_getSkeleton does
// (mapping it to lowercase I).
int32_t u04cf_pos;
if ((u04cf_pos = host.indexOf(0x4CF)) != -1) {
icu::UnicodeString host_alt(host);
size_t length = host_alt.length();
char16_t* buffer = host_alt.getBuffer(-1);
for (char16_t* uc = buffer + u04cf_pos ; uc < buffer + length; ++uc) {
if (*uc == 0x4CF)
*uc = 0x6C; // Lowercase L
}
host_alt.releaseBuffer(length);
uspoof_getSkeletonUnicodeString(checker_, 0, host_alt, skeleton, &status);
if (U_SUCCESS(status) && LookupMatchInTopDomains(skeleton))
return true;
}
uspoof_getSkeletonUnicodeString(checker_, 0, host, skeleton, &status);
return U_SUCCESS(status) && LookupMatchInTopDomains(skeleton);
}
| 173,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetFileSystem",
base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID: | FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("GetFileSystem", "fileManagerPrivate",
base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem,
base::Unretained(this)));
RouteFunction(
"GetExternalFileEntry", "fileManagerPrivate",
base::Bind(&FileManagerPrivateCustomBindings::GetExternalFileEntry,
base::Unretained(this)));
RouteFunction("GetEntryURL", "fileManagerPrivate",
base::Bind(&FileManagerPrivateCustomBindings::GetEntryURL,
base::Unretained(this)));
}
| 173,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() {
using api::extension_types::ImageDetails;
EXTENSION_FUNCTION_VALIDATE(args_);
int context_id = extension_misc::kCurrentWindowId;
args_->GetInteger(0, &context_id);
std::unique_ptr<ImageDetails> image_details;
if (args_->GetSize() > 1) {
base::Value* spec = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec);
image_details = ImageDetails::FromValue(*spec);
}
std::string error;
WebContents* contents = GetWebContentsForID(context_id, &error);
const CaptureResult capture_result = CaptureAsync(
contents, image_details.get(),
base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete,
this));
if (capture_result == OK) {
return did_respond() ? AlreadyResponded() : RespondLater();
}
return RespondNow(Error(CaptureResultToErrorMessage(capture_result)));
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() {
using api::extension_types::ImageDetails;
EXTENSION_FUNCTION_VALIDATE(args_);
int context_id = extension_misc::kCurrentWindowId;
args_->GetInteger(0, &context_id);
std::unique_ptr<ImageDetails> image_details;
if (args_->GetSize() > 1) {
base::Value* spec = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec);
image_details = ImageDetails::FromValue(*spec);
}
std::string error;
WebContents* contents = GetWebContentsForID(context_id, &error);
if (!contents)
return RespondNow(Error(error));
const CaptureResult capture_result = CaptureAsync(
contents, image_details.get(),
base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete,
this));
if (capture_result == OK) {
return did_respond() ? AlreadyResponded() : RespondLater();
}
return RespondNow(Error(CaptureResultToErrorMessage(capture_result)));
}
| 173,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode)
{
if (state->state == mode)
return;
/* NB! List reordering - see the reclaim code for why. */
if ((mode & FMODE_WRITE) != (state->state & FMODE_WRITE)) {
if (mode & FMODE_WRITE)
list_move(&state->open_states, &state->owner->so_states);
else
list_move_tail(&state->open_states, &state->owner->so_states);
}
state->state = mode;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode)
nfs4_state_set_mode_locked(struct nfs4_state *state, fmode_t fmode)
{
if (state->state == fmode)
return;
/* NB! List reordering - see the reclaim code for why. */
if ((fmode & FMODE_WRITE) != (state->state & FMODE_WRITE)) {
if (fmode & FMODE_WRITE)
list_move(&state->open_states, &state->owner->so_states);
else
list_move_tail(&state->open_states, &state->owner->so_states);
}
state->state = fmode;
}
| 165,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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;
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 */
}
Commit Message: fix #59 : access to invalid address by reg->dmax value
CWE ID: CWE-476 | 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) {
if (p - str < reg->dmax) {
*low = (UChar* )str;
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc, str, *low);
}
else {
*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,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PromoResourceService::PostNotification(int64 delay_ms) {
if (web_resource_update_scheduled_)
return;
if (delay_ms > 0) {
web_resource_update_scheduled_ = true;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void PromoResourceService::PostNotification(int64 delay_ms) {
// Note that this could cause re-issuing a notification every time
// we receive an update from a server if something goes wrong.
// Given that this couldn't happen more frequently than every
// kCacheUpdateDelay milliseconds, we should be fine.
if (delay_ms > 0) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
| 170,781 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32(p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
}
Commit Message: Fix #6816 - null deref in r_read_*
CWE ID: CWE-476 | static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32 (p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
}
| 168,362 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool scoped_pixel_buffer_object::Init(CGLContextObj cgl_context,
int size_in_bytes) {
cgl_context_ = cgl_context;
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glGenBuffersARB(1, &pixel_buffer_object_);
if (glGetError() == GL_NO_ERROR) {
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL,
GL_STREAM_READ_ARB);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
if (glGetError() != GL_NO_ERROR) {
Release();
}
} else {
cgl_context_ = NULL;
pixel_buffer_object_ = 0;
}
return pixel_buffer_object_ != 0;
}
Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5.
BUG=87283
TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting.
Review URL: http://codereview.chromium.org/7373018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool scoped_pixel_buffer_object::Init(CGLContextObj cgl_context,
int size_in_bytes) {
// The PBO path is only done on 10.6 (SnowLeopard) and above due to
// a driver issue that was found on 10.5
// (specifically on a NVIDIA GeForce 7300 GT).
// http://crbug.com/87283
if (base::mac::IsOSLeopardOrEarlier()) {
return false;
}
cgl_context_ = cgl_context;
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glGenBuffersARB(1, &pixel_buffer_object_);
if (glGetError() == GL_NO_ERROR) {
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL,
GL_STREAM_READ_ARB);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
if (glGetError() != GL_NO_ERROR) {
Release();
}
} else {
cgl_context_ = NULL;
pixel_buffer_object_ = 0;
}
return pixel_buffer_object_ != 0;
}
| 170,317 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119 | void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
luaL_checkstack(L, 1, "in function mp_decode_to_lua_array");
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
| 169,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.dirp) {
RETURN_LONG(intern->u.dir.index);
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.dirp) {
RETURN_LONG(intern->u.dir.index);
} else {
RETURN_FALSE;
}
}
| 167,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static entity_table_opt determine_entity_table(int all, int doctype)
{
entity_table_opt retval = {NULL};
assert(!(doctype == ENT_HTML_DOC_XML1 && all));
if (all) {
retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
entity_ms_table_html5 : entity_ms_table_html4;
} else {
retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
}
return retval;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static entity_table_opt determine_entity_table(int all, int doctype)
{
entity_table_opt retval = {NULL};
assert(!(doctype == ENT_HTML_DOC_XML1 && all));
if (all) {
retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
entity_ms_table_html5 : entity_ms_table_html4;
} else {
retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
}
return retval;
}
| 167,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
{
static const char module[] = "TIFFReadEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint32 rowsperstrip;
uint32 stripsperplane;
uint32 stripinplane;
uint16 plane;
uint32 rows;
tmsize_t stripsize;
if (!TIFFCheckRead(tif,0))
return((tmsize_t)(-1));
if (strip>=td->td_nstrips)
{
TIFFErrorExt(tif->tif_clientdata,module,
"%lu: Strip out of range, max %lu",(unsigned long)strip,
(unsigned long)td->td_nstrips);
return((tmsize_t)(-1));
}
/*
* Calculate the strip size according to the number of
* rows in the strip (check for truncated last strip on any
* of the separations).
*/
rowsperstrip=td->td_rowsperstrip;
if (rowsperstrip>td->td_imagelength)
rowsperstrip=td->td_imagelength;
stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip);
stripinplane=(strip%stripsperplane);
plane=(uint16)(strip/stripsperplane);
rows=td->td_imagelength-stripinplane*rowsperstrip;
if (rows>rowsperstrip)
rows=rowsperstrip;
stripsize=TIFFVStripSize(tif,rows);
if (stripsize==0)
return((tmsize_t)(-1));
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE &&
size!=(tmsize_t)(-1) && size >= stripsize &&
!isMapped(tif) &&
((tif->tif_flags&TIFF_NOREADRAW)==0) )
{
if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(buf,stripsize);
(*tif->tif_postdecode)(tif,buf,stripsize);
return (stripsize);
}
if ((size!=(tmsize_t)(-1))&&(size<stripsize))
stripsize=size;
if (!TIFFFillStrip(tif,strip))
return((tmsize_t)(-1));
if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
return((tmsize_t)(-1));
(*tif->tif_postdecode)(tif,buf,stripsize);
return(stripsize);
}
Commit Message: * libtiff/tif_read.c, libtiff/tiffiop.h: fix uint32 overflow in
TIFFReadEncodedStrip() that caused an integer division by zero.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2596
CWE ID: CWE-369 | TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
{
static const char module[] = "TIFFReadEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint32 rowsperstrip;
uint32 stripsperplane;
uint32 stripinplane;
uint16 plane;
uint32 rows;
tmsize_t stripsize;
if (!TIFFCheckRead(tif,0))
return((tmsize_t)(-1));
if (strip>=td->td_nstrips)
{
TIFFErrorExt(tif->tif_clientdata,module,
"%lu: Strip out of range, max %lu",(unsigned long)strip,
(unsigned long)td->td_nstrips);
return((tmsize_t)(-1));
}
/*
* Calculate the strip size according to the number of
* rows in the strip (check for truncated last strip on any
* of the separations).
*/
rowsperstrip=td->td_rowsperstrip;
if (rowsperstrip>td->td_imagelength)
rowsperstrip=td->td_imagelength;
stripsperplane= TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
stripinplane=(strip%stripsperplane);
plane=(uint16)(strip/stripsperplane);
rows=td->td_imagelength-stripinplane*rowsperstrip;
if (rows>rowsperstrip)
rows=rowsperstrip;
stripsize=TIFFVStripSize(tif,rows);
if (stripsize==0)
return((tmsize_t)(-1));
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE &&
size!=(tmsize_t)(-1) && size >= stripsize &&
!isMapped(tif) &&
((tif->tif_flags&TIFF_NOREADRAW)==0) )
{
if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(buf,stripsize);
(*tif->tif_postdecode)(tif,buf,stripsize);
return (stripsize);
}
if ((size!=(tmsize_t)(-1))&&(size<stripsize))
stripsize=size;
if (!TIFFFillStrip(tif,strip))
return((tmsize_t)(-1));
if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
return((tmsize_t)(-1));
(*tif->tif_postdecode)(tif,buf,stripsize);
return(stripsize);
}
| 168,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
Commit Message: Fix bug #72750: wddx_deserialize null dereference
CWE ID: CWE-476 | static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
| 166,950 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t read_and_process_frames(struct audio_stream_in *stream, void* buffer, ssize_t frames_num)
{
struct stream_in *in = (struct stream_in *)stream;
ssize_t frames_wr = 0; /* Number of frames actually read */
size_t bytes_per_sample = audio_bytes_per_sample(stream->common.get_format(&stream->common));
void *proc_buf_out = buffer;
#ifdef PREPROCESSING_ENABLED
audio_buffer_t in_buf;
audio_buffer_t out_buf;
int i;
bool has_processing = in->num_preprocessors != 0;
#endif
/* Additional channels might be added on top of main_channels:
* - aux_channels (by processing effects)
* - extra channels due to HW limitations
* In case of additional channels, we cannot work inplace
*/
size_t src_channels = in->config.channels;
size_t dst_channels = audio_channel_count_from_in_mask(in->main_channels);
bool channel_remapping_needed = (dst_channels != src_channels);
size_t src_buffer_size = frames_num * src_channels * bytes_per_sample;
#ifdef PREPROCESSING_ENABLED
if (has_processing) {
/* since all the processing below is done in frames and using the config.channels
* as the number of channels, no changes is required in case aux_channels are present */
while (frames_wr < frames_num) {
/* first reload enough frames at the end of process input buffer */
if (in->proc_buf_frames < (size_t)frames_num) {
ssize_t frames_rd;
if (in->proc_buf_size < (size_t)frames_num) {
in->proc_buf_size = (size_t)frames_num;
in->proc_buf_in = realloc(in->proc_buf_in, src_buffer_size);
ALOG_ASSERT((in->proc_buf_in != NULL),
"process_frames() failed to reallocate proc_buf_in");
if (channel_remapping_needed) {
in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size);
ALOG_ASSERT((in->proc_buf_out != NULL),
"process_frames() failed to reallocate proc_buf_out");
proc_buf_out = in->proc_buf_out;
}
}
frames_rd = read_frames(in,
in->proc_buf_in +
in->proc_buf_frames * src_channels * bytes_per_sample,
frames_num - in->proc_buf_frames);
if (frames_rd < 0) {
/* Return error code */
frames_wr = frames_rd;
break;
}
in->proc_buf_frames += frames_rd;
}
/* in_buf.frameCount and out_buf.frameCount indicate respectively
* the maximum number of frames to be consumed and produced by process() */
in_buf.frameCount = in->proc_buf_frames;
in_buf.s16 = in->proc_buf_in;
out_buf.frameCount = frames_num - frames_wr;
out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * in->config.channels;
/* FIXME: this works because of current pre processing library implementation that
* does the actual process only when the last enabled effect process is called.
* The generic solution is to have an output buffer for each effect and pass it as
* input to the next.
*/
for (i = 0; i < in->num_preprocessors; i++) {
(*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe,
&in_buf,
&out_buf);
}
/* process() has updated the number of frames consumed and produced in
* in_buf.frameCount and out_buf.frameCount respectively
* move remaining frames to the beginning of in->proc_buf_in */
in->proc_buf_frames -= in_buf.frameCount;
if (in->proc_buf_frames) {
memcpy(in->proc_buf_in,
in->proc_buf_in + in_buf.frameCount * src_channels * bytes_per_sample,
in->proc_buf_frames * in->config.channels * audio_bytes_per_sample(in_get_format(in)));
}
/* if not enough frames were passed to process(), read more and retry. */
if (out_buf.frameCount == 0) {
ALOGW("No frames produced by preproc");
continue;
}
if ((frames_wr + (ssize_t)out_buf.frameCount) <= frames_num) {
frames_wr += out_buf.frameCount;
} else {
/* The effect does not comply to the API. In theory, we should never end up here! */
ALOGE("preprocessing produced too many frames: %d + %zd > %d !",
(unsigned int)frames_wr, out_buf.frameCount, (unsigned int)frames_num);
frames_wr = frames_num;
}
}
}
else
#endif //PREPROCESSING_ENABLED
{
/* No processing effects attached */
if (channel_remapping_needed) {
/* With additional channels, we cannot use original buffer */
if (in->proc_buf_size < src_buffer_size) {
in->proc_buf_size = src_buffer_size;
in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size);
ALOG_ASSERT((in->proc_buf_out != NULL),
"process_frames() failed to reallocate proc_buf_out");
}
proc_buf_out = in->proc_buf_out;
}
frames_wr = read_frames(in, proc_buf_out, frames_num);
ALOG_ASSERT(frames_wr <= frames_num, "read more frames than requested");
}
if (channel_remapping_needed) {
size_t ret = adjust_channels(proc_buf_out, src_channels, buffer, dst_channels,
bytes_per_sample, frames_wr * src_channels * bytes_per_sample);
ALOG_ASSERT(ret == (frames_wr * dst_channels * bytes_per_sample));
}
return frames_wr;
}
Commit Message: Fix audio record pre-processing
proc_buf_out consistently initialized.
intermediate scratch buffers consistently initialized.
prevent read failure from overwriting memory.
Test: POC, CTS, camera record
Bug: 62873231
Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686
(cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb)
CWE ID: CWE-125 | static ssize_t read_and_process_frames(struct audio_stream_in *stream, void* buffer, ssize_t frames_num)
{
struct stream_in *in = (struct stream_in *)stream;
ssize_t frames_wr = 0; /* Number of frames actually read */
size_t bytes_per_sample = audio_bytes_per_sample(stream->common.get_format(&stream->common));
void *proc_buf_out = buffer;
/* Additional channels might be added on top of main_channels:
* - aux_channels (by processing effects)
* - extra channels due to HW limitations
* In case of additional channels, we cannot work inplace
*/
size_t src_channels = in->config.channels;
size_t dst_channels = audio_channel_count_from_in_mask(in->main_channels);
bool channel_remapping_needed = (dst_channels != src_channels);
const size_t src_frame_size = src_channels * bytes_per_sample;
#ifdef PREPROCESSING_ENABLED
const bool has_processing = in->num_preprocessors != 0;
#else
const bool has_processing = false;
#endif
/* With additional channels or processing, we need intermediate buffers */
if (channel_remapping_needed || has_processing) {
const size_t src_buffer_size = frames_num * src_frame_size;
if (in->proc_buf_size < src_buffer_size) {
in->proc_buf_size = src_buffer_size;
#ifdef PREPROCESSING_ENABLED
/* we always reallocate both buffers in case # of effects change dynamically. */
in->proc_buf_in = realloc(in->proc_buf_in, src_buffer_size);
ALOG_ASSERT((in->proc_buf_in != NULL),
"process_frames() failed to reallocate proc_buf_in");
#endif
in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size);
ALOG_ASSERT((in->proc_buf_out != NULL),
"process_frames() failed to reallocate proc_buf_out");
}
if (channel_remapping_needed) {
proc_buf_out = in->proc_buf_out;
}
}
#ifdef PREPROCESSING_ENABLED
if (has_processing) {
/* since all the processing below is done in frames and using the config.channels
* as the number of channels, no changes is required in case aux_channels are present */
while (frames_wr < frames_num) {
/* first reload enough frames at the end of process input buffer */
if (in->proc_buf_frames < (size_t)frames_num) {
ssize_t frames_rd = read_frames(in,
(char *)in->proc_buf_in + in->proc_buf_frames * src_frame_size,
frames_num - in->proc_buf_frames);
if (frames_rd < 0) {
/* Return error code */
frames_wr = frames_rd;
break;
}
in->proc_buf_frames += frames_rd;
}
/* in_buf.frameCount and out_buf.frameCount indicate respectively
* the maximum number of frames to be consumed and produced by process() */
audio_buffer_t in_buf;
audio_buffer_t out_buf;
in_buf.frameCount = in->proc_buf_frames;
in_buf.s16 = in->proc_buf_in; /* currently assumes PCM 16 effects */
out_buf.frameCount = frames_num - frames_wr;
out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * src_channels;
/* FIXME: this works because of current pre processing library implementation that
* does the actual process only when the last enabled effect process is called.
* The generic solution is to have an output buffer for each effect and pass it as
* input to the next.
*/
for (int i = 0; i < in->num_preprocessors; i++) {
(*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe,
&in_buf,
&out_buf);
}
/* process() has updated the number of frames consumed and produced in
* in_buf.frameCount and out_buf.frameCount respectively
* move remaining frames to the beginning of in->proc_buf_in */
in->proc_buf_frames -= in_buf.frameCount;
if (in->proc_buf_frames) {
memcpy(in->proc_buf_in,
(char *)in->proc_buf_in + in_buf.frameCount * src_frame_size,
in->proc_buf_frames * src_frame_size);
}
/* if not enough frames were passed to process(), read more and retry. */
if (out_buf.frameCount == 0) {
ALOGW("No frames produced by preproc");
continue;
}
if ((frames_wr + (ssize_t)out_buf.frameCount) <= frames_num) {
frames_wr += out_buf.frameCount;
} else {
/* The effect does not comply to the API. In theory, we should never end up here! */
ALOGE("preprocessing produced too many frames: %d + %zd > %d !",
(unsigned int)frames_wr, out_buf.frameCount, (unsigned int)frames_num);
frames_wr = frames_num;
}
}
}
else
#endif //PREPROCESSING_ENABLED
{
/* No processing effects attached */
frames_wr = read_frames(in, proc_buf_out, frames_num);
ALOG_ASSERT(frames_wr <= frames_num, "read more frames than requested");
}
/* check negative frames_wr (error) before channel remapping to avoid overwriting memory. */
if (channel_remapping_needed && frames_wr > 0) {
size_t ret = adjust_channels(proc_buf_out, src_channels, buffer, dst_channels,
bytes_per_sample, frames_wr * src_frame_size);
ALOG_ASSERT(ret == (frames_wr * dst_channels * bytes_per_sample));
}
return frames_wr;
}
| 173,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct nlattr *link[TIPC_NLA_LINK_MAX + 1];
struct tipc_link_info link_info;
int err;
if (!attrs[TIPC_NLA_LINK])
return -EINVAL;
err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK],
NULL);
if (err)
return err;
link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]);
link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP]));
strcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME]));
return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO,
&link_info, sizeof(link_info));
}
Commit Message: tipc: fix an infoleak in tipc_nl_compat_link_dump
link_info.str is a char array of size 60. Memory after the NULL
byte is not initialized. Sending the whole object out can cause
a leak.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct nlattr *link[TIPC_NLA_LINK_MAX + 1];
struct tipc_link_info link_info;
int err;
if (!attrs[TIPC_NLA_LINK])
return -EINVAL;
err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK],
NULL);
if (err)
return err;
link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]);
link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP]));
nla_strlcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME]),
TIPC_MAX_LINK_NAME);
return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO,
&link_info, sizeof(link_info));
}
| 167,162 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int is_rndis(USBNetState *s)
{
return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE;
}
Commit Message:
CWE ID: | static int is_rndis(USBNetState *s)
{
return s->dev.config ?
s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE : 0;
}
| 165,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
| 169,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp,
struct rpcrdma_write_array *wr_ary,
struct rpcrdma_write_array *rp_ary)
{
struct rpcrdma_read_chunk *rd_ary;
struct rpcrdma_segment *arg_ch;
rd_ary = (struct rpcrdma_read_chunk *)&rdma_argp->rm_body.rm_chunks[0];
if (rd_ary->rc_discrim != xdr_zero)
return be32_to_cpu(rd_ary->rc_target.rs_handle);
if (wr_ary && be32_to_cpu(wr_ary->wc_nchunks)) {
arg_ch = &wr_ary->wc_array[0].wc_target;
return be32_to_cpu(arg_ch->rs_handle);
}
if (rp_ary && be32_to_cpu(rp_ary->wc_nchunks)) {
arg_ch = &rp_ary->wc_array[0].wc_target;
return be32_to_cpu(arg_ch->rs_handle);
}
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp,
static u32 svc_rdma_get_inv_rkey(__be32 *rdma_argp,
__be32 *wr_lst, __be32 *rp_ch)
{
__be32 *p;
p = rdma_argp + rpcrdma_fixed_maxsz;
if (*p != xdr_zero)
p += 2;
else if (wr_lst && be32_to_cpup(wr_lst + 1))
p = wr_lst + 2;
else if (rp_ch && be32_to_cpup(rp_ch + 1))
p = rp_ch + 2;
else
return 0;
return be32_to_cpup(p);
}
/* ib_dma_map_page() is used here because svc_rdma_dma_unmap()
* is used during completion to DMA-unmap this memory, and
* it uses ib_dma_unmap_page() exclusively.
*/
static int svc_rdma_dma_map_buf(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
unsigned int sge_no,
unsigned char *base,
unsigned int len)
{
unsigned long offset = (unsigned long)base & ~PAGE_MASK;
struct ib_device *dev = rdma->sc_cm_id->device;
dma_addr_t dma_addr;
dma_addr = ib_dma_map_page(dev, virt_to_page(base),
offset, len, DMA_TO_DEVICE);
if (ib_dma_mapping_error(dev, dma_addr))
return -EIO;
ctxt->sge[sge_no].addr = dma_addr;
ctxt->sge[sge_no].length = len;
ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey;
svc_rdma_count_mappings(rdma, ctxt);
return 0;
}
| 168,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLOzone* X11SurfaceFactory::GetGLOzone(gl::GLImplementation implementation) {
switch (implementation) {
case gl::kGLImplementationDesktopGL:
return glx_implementation_.get();
case gl::kGLImplementationEGLGLES2:
return egl_implementation_.get();
default:
return nullptr;
}
}
Commit Message: Add ThreadChecker for Ozone X11 GPU.
Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM.
BUG=none
Review-Url: https://codereview.chromium.org/2366643002
Cr-Commit-Position: refs/heads/master@{#421817}
CWE ID: CWE-284 | GLOzone* X11SurfaceFactory::GetGLOzone(gl::GLImplementation implementation) {
DCHECK(thread_checker_.CalledOnValidThread());
switch (implementation) {
case gl::kGLImplementationDesktopGL:
return glx_implementation_.get();
case gl::kGLImplementationEGLGLES2:
return egl_implementation_.get();
default:
return nullptr;
}
}
| 171,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
render_widget_host_view->AdjustSurfaceProtection();
}
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::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
}
| 171,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
char task_path[64];
//// Attach to a thread, and verify that it's still a member of the given process
snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
if (!d) {
ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
return;
}
struct dirent* de;
while ((de = readdir(d.get())) != NULL) {
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
continue;
}
char* end;
pid_t tid = strtoul(de->d_name, &end, 10);
if (*end) {
continue;
}
if (tid == main_tid) {
continue;
}
if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) {
ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
continue;
}
tids.insert(tid);
}
}
Commit Message: debuggerd: verify that traced threads belong to the right process.
Fix two races in debuggerd's PTRACE_ATTACH logic:
1. The target thread in a crash dump request could exit between the
/proc/<pid>/task/<tid> check and the PTRACE_ATTACH.
2. Sibling threads could exit between listing /proc/<pid>/task and the
PTRACE_ATTACH.
Bug: http://b/29555636
Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
CWE ID: CWE-264 | static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
//// Attach to a thread, and verify that it's still a member of the given process
static bool ptrace_attach_thread(pid_t pid, pid_t tid) {
if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) {
return false;
}
// Make sure that the task we attached to is actually part of the pid we're dumping.
if (!pid_contains_tid(pid, tid)) {
if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
ALOGE("debuggerd: failed to detach from thread '%d'", tid);
exit(1);
}
return false;
}
return true;
}
static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
char task_path[PATH_MAX];
if (snprintf(task_path, PATH_MAX, "/proc/%d/task", pid) >= PATH_MAX) {
ALOGE("debuggerd: task path overflow (pid = %d)\n", pid);
abort();
}
std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
if (!d) {
ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
return;
}
struct dirent* de;
while ((de = readdir(d.get())) != NULL) {
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
continue;
}
char* end;
pid_t tid = strtoul(de->d_name, &end, 10);
if (*end) {
continue;
}
if (tid == main_tid) {
continue;
}
if (!ptrace_attach_thread(pid, tid)) {
ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
continue;
}
tids.insert(tid);
}
}
| 173,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Compositor::Compositor(
const viz::FrameSinkId& frame_sink_id,
ui::ContextFactory* context_factory,
ui::ContextFactoryPrivate* context_factory_private,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
bool enable_pixel_canvas,
ui::ExternalBeginFrameClient* external_begin_frame_client,
bool force_software_compositor,
const char* trace_environment_name)
: context_factory_(context_factory),
context_factory_private_(context_factory_private),
frame_sink_id_(frame_sink_id),
task_runner_(task_runner),
vsync_manager_(new CompositorVSyncManager()),
external_begin_frame_client_(external_begin_frame_client),
force_software_compositor_(force_software_compositor),
layer_animator_collection_(this),
is_pixel_canvas_(enable_pixel_canvas),
lock_manager_(task_runner),
trace_environment_name_(trace_environment_name
? trace_environment_name
: kDefaultTraceEnvironmentName),
context_creation_weak_ptr_factory_(this) {
if (context_factory_private) {
auto* host_frame_sink_manager =
context_factory_private_->GetHostFrameSinkManager();
host_frame_sink_manager->RegisterFrameSinkId(
frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo);
host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_,
"Compositor");
}
root_web_layer_ = cc::Layer::Create();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
cc::LayerTreeSettings settings;
settings.layers_always_allowed_lcd_text = true;
settings.use_occlusion_for_tile_prioritization = true;
settings.main_frame_before_activation_enabled = false;
settings.delegated_sync_points_required =
context_factory_->SyncTokensRequiredForDisplayCompositor();
settings.enable_edge_anti_aliasing = false;
if (command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders)) {
std::string layer_borders_string = command_line->GetSwitchValueASCII(
cc::switches::kUIShowCompositedLayerBorders);
std::vector<base::StringPiece> entries = base::SplitStringPiece(
layer_borders_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (entries.empty()) {
settings.initial_debug_state.show_debug_borders.set();
} else {
for (const auto& entry : entries) {
const struct {
const char* name;
cc::DebugBorderType type;
} kBorders[] = {{cc::switches::kCompositedRenderPassBorders,
cc::DebugBorderType::RENDERPASS},
{cc::switches::kCompositedSurfaceBorders,
cc::DebugBorderType::SURFACE},
{cc::switches::kCompositedLayerBorders,
cc::DebugBorderType::LAYER}};
for (const auto& border : kBorders) {
if (border.name == entry) {
settings.initial_debug_state.show_debug_borders.set(border.type);
break;
}
}
}
}
}
settings.initial_debug_state.show_fps_counter =
command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
settings.initial_debug_state.show_layer_animation_bounds_rects =
command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
settings.initial_debug_state.show_paint_rects =
command_line->HasSwitch(switches::kUIShowPaintRects);
settings.initial_debug_state.show_property_changed_rects =
command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
settings.initial_debug_state.show_surface_damage_rects =
command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
settings.initial_debug_state.show_screen_space_rects =
command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
settings.initial_debug_state.SetRecordRenderingStats(
command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
settings.enable_surface_synchronization = true;
settings.build_hit_test_data = features::IsVizHitTestingSurfaceLayerEnabled();
settings.use_zero_copy = IsUIZeroCopyEnabled();
settings.use_layer_lists =
command_line->HasSwitch(cc::switches::kUIEnableLayerLists);
settings.use_partial_raster = !settings.use_zero_copy;
settings.use_rgba_4444 =
command_line->HasSwitch(switches::kUIEnableRGBA4444Textures);
#if defined(OS_MACOSX)
settings.resource_settings.use_gpu_memory_buffer_resources =
settings.use_zero_copy;
settings.enable_elastic_overscroll = true;
#endif
settings.memory_policy.bytes_limit_when_visible = 512 * 1024 * 1024;
if (command_line->HasSwitch(
switches::kUiCompositorMemoryLimitWhenVisibleMB)) {
std::string value_str = command_line->GetSwitchValueASCII(
switches::kUiCompositorMemoryLimitWhenVisibleMB);
unsigned value_in_mb;
if (base::StringToUint(value_str, &value_in_mb)) {
settings.memory_policy.bytes_limit_when_visible =
1024 * 1024 * value_in_mb;
}
}
settings.memory_policy.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
settings.disallow_non_exact_resource_reuse =
command_line->HasSwitch(switches::kDisallowNonExactResourceReuse);
if (command_line->HasSwitch(switches::kRunAllCompositorStagesBeforeDraw)) {
settings.wait_for_all_pipeline_stages_before_draw = true;
settings.enable_latency_recovery = false;
}
if (base::FeatureList::IsEnabled(
features::kCompositorThreadedScrollbarScrolling)) {
settings.compositor_threaded_scrollbar_scrolling = true;
}
animation_host_ = cc::AnimationHost::CreateMainInstance();
cc::LayerTreeHost::InitParams params;
params.client = this;
params.task_graph_runner = context_factory_->GetTaskGraphRunner();
params.settings = &settings;
params.main_task_runner = task_runner_;
params.mutator_host = animation_host_.get();
host_ = cc::LayerTreeHost::CreateSingleThreaded(this, std::move(params));
if (base::FeatureList::IsEnabled(features::kUiCompositorScrollWithLayers) &&
host_->GetInputHandler()) {
scroll_input_handler_.reset(
new ScrollInputHandler(host_->GetInputHandler()));
}
animation_timeline_ =
cc::AnimationTimeline::Create(cc::AnimationIdProvider::NextTimelineId());
animation_host_->AddAnimationTimeline(animation_timeline_.get());
host_->SetHasGpuRasterizationTrigger(features::IsUiGpuRasterizationEnabled());
host_->SetRootLayer(root_web_layer_);
host_->SetVisible(true);
if (command_line->HasSwitch(switches::kUISlowAnimations)) {
slow_animations_ = std::make_unique<ScopedAnimationDurationScaleMode>(
ScopedAnimationDurationScaleMode::SLOW_DURATION);
}
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284 | Compositor::Compositor(
const viz::FrameSinkId& frame_sink_id,
ui::ContextFactory* context_factory,
ui::ContextFactoryPrivate* context_factory_private,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
bool enable_pixel_canvas,
ui::ExternalBeginFrameClient* external_begin_frame_client,
bool force_software_compositor,
const char* trace_environment_name)
: context_factory_(context_factory),
context_factory_private_(context_factory_private),
frame_sink_id_(frame_sink_id),
task_runner_(task_runner),
vsync_manager_(new CompositorVSyncManager()),
external_begin_frame_client_(external_begin_frame_client),
force_software_compositor_(force_software_compositor),
layer_animator_collection_(this),
is_pixel_canvas_(enable_pixel_canvas),
lock_manager_(task_runner),
trace_environment_name_(trace_environment_name
? trace_environment_name
: kDefaultTraceEnvironmentName),
context_creation_weak_ptr_factory_(this) {
if (context_factory_private) {
auto* host_frame_sink_manager =
context_factory_private_->GetHostFrameSinkManager();
host_frame_sink_manager->RegisterFrameSinkId(
frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo);
host_frame_sink_manager->SetFrameSinkDebugLabel(frame_sink_id_,
"Compositor");
}
root_web_layer_ = cc::Layer::Create();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
cc::LayerTreeSettings settings;
settings.layers_always_allowed_lcd_text = true;
settings.use_occlusion_for_tile_prioritization = true;
settings.main_frame_before_activation_enabled = false;
settings.delegated_sync_points_required =
context_factory_->SyncTokensRequiredForDisplayCompositor();
settings.enable_edge_anti_aliasing = false;
if (command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders)) {
std::string layer_borders_string = command_line->GetSwitchValueASCII(
cc::switches::kUIShowCompositedLayerBorders);
std::vector<base::StringPiece> entries = base::SplitStringPiece(
layer_borders_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (entries.empty()) {
settings.initial_debug_state.show_debug_borders.set();
} else {
for (const auto& entry : entries) {
const struct {
const char* name;
cc::DebugBorderType type;
} kBorders[] = {{cc::switches::kCompositedRenderPassBorders,
cc::DebugBorderType::RENDERPASS},
{cc::switches::kCompositedSurfaceBorders,
cc::DebugBorderType::SURFACE},
{cc::switches::kCompositedLayerBorders,
cc::DebugBorderType::LAYER}};
for (const auto& border : kBorders) {
if (border.name == entry) {
settings.initial_debug_state.show_debug_borders.set(border.type);
break;
}
}
}
}
}
settings.initial_debug_state.show_fps_counter =
command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
settings.initial_debug_state.show_layer_animation_bounds_rects =
command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
settings.initial_debug_state.show_paint_rects =
command_line->HasSwitch(switches::kUIShowPaintRects);
settings.initial_debug_state.show_property_changed_rects =
command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
settings.initial_debug_state.show_surface_damage_rects =
command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
settings.initial_debug_state.show_screen_space_rects =
command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
settings.initial_debug_state.SetRecordRenderingStats(
command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
settings.enable_surface_synchronization = true;
settings.build_hit_test_data = features::IsVizHitTestingSurfaceLayerEnabled();
settings.use_zero_copy = IsUIZeroCopyEnabled();
settings.use_layer_lists =
command_line->HasSwitch(cc::switches::kUIEnableLayerLists);
settings.use_partial_raster = !settings.use_zero_copy;
settings.use_rgba_4444 =
command_line->HasSwitch(switches::kUIEnableRGBA4444Textures);
#if defined(OS_MACOSX)
settings.resource_settings.use_gpu_memory_buffer_resources =
settings.use_zero_copy;
settings.enable_elastic_overscroll = true;
#endif
settings.memory_policy.bytes_limit_when_visible = 512 * 1024 * 1024;
if (command_line->HasSwitch(
switches::kUiCompositorMemoryLimitWhenVisibleMB)) {
std::string value_str = command_line->GetSwitchValueASCII(
switches::kUiCompositorMemoryLimitWhenVisibleMB);
unsigned value_in_mb;
if (base::StringToUint(value_str, &value_in_mb)) {
settings.memory_policy.bytes_limit_when_visible =
1024 * 1024 * value_in_mb;
}
}
settings.memory_policy.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
settings.disallow_non_exact_resource_reuse =
command_line->HasSwitch(switches::kDisallowNonExactResourceReuse);
if (command_line->HasSwitch(switches::kRunAllCompositorStagesBeforeDraw)) {
settings.wait_for_all_pipeline_stages_before_draw = true;
settings.enable_latency_recovery = false;
}
if (base::FeatureList::IsEnabled(
features::kCompositorThreadedScrollbarScrolling)) {
settings.compositor_threaded_scrollbar_scrolling = true;
}
animation_host_ = cc::AnimationHost::CreateMainInstance();
cc::LayerTreeHost::InitParams params;
params.client = this;
params.task_graph_runner = context_factory_->GetTaskGraphRunner();
params.settings = &settings;
params.main_task_runner = task_runner_;
params.mutator_host = animation_host_.get();
host_ = cc::LayerTreeHost::CreateSingleThreaded(this, std::move(params));
if (base::FeatureList::IsEnabled(features::kUiCompositorScrollWithLayers) &&
host_->GetInputHandler()) {
scroll_input_handler_.reset(
new ScrollInputHandler(host_->GetInputHandler()));
}
animation_timeline_ =
cc::AnimationTimeline::Create(cc::AnimationIdProvider::NextTimelineId());
animation_host_->AddAnimationTimeline(animation_timeline_.get());
host_->SetHasGpuRasterizationTrigger(features::IsUiGpuRasterizationEnabled());
host_->SetRootLayer(root_web_layer_);
// This shouldn't be done in the constructor in order to match Widget.
// See: http://crbug.com/956264.
host_->SetVisible(true);
if (command_line->HasSwitch(switches::kUISlowAnimations)) {
slow_animations_ = std::make_unique<ScopedAnimationDurationScaleMode>(
ScopedAnimationDurationScaleMode::SLOW_DURATION);
}
}
| 172,515 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
{
char *str, *hint_charset = NULL;
int str_len, hint_charset_len = 0;
size_t new_len;
long flags = ENT_COMPAT;
char *replaced;
zend_bool double_encode = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) {
return;
}
replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC);
RETVAL_STRINGL(replaced, (int)new_len, 0);
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
{
char *str, *hint_charset = NULL;
int str_len, hint_charset_len = 0;
size_t new_len;
long flags = ENT_COMPAT;
char *replaced;
zend_bool double_encode = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) {
return;
}
replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC);
if (new_len > INT_MAX) {
efree(replaced);
RETURN_FALSE;
}
RETVAL_STRINGL(replaced, (int)new_len, 0);
}
| 167,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuMessageFilter::EstablishChannelCallback(
IPC::Message* reply,
const IPC::ChannelHandle& channel,
base::ProcessHandle gpu_process_for_browser,
const content::GPUInfo& gpu_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
base::ProcessHandle renderer_process_for_gpu;
if (gpu_process_for_browser != 0) {
#if defined(OS_WIN)
DuplicateHandle(base::GetCurrentProcessHandle(),
peer_handle(),
gpu_process_for_browser,
&renderer_process_for_gpu,
PROCESS_DUP_HANDLE,
FALSE,
0);
#else
renderer_process_for_gpu = peer_handle();
#endif
} else {
renderer_process_for_gpu = 0;
}
GpuHostMsg_EstablishGpuChannel::WriteReplyParams(
reply, render_process_id_, channel, renderer_process_for_gpu, gpu_info);
Send(reply);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuMessageFilter::EstablishChannelCallback(
IPC::Message* reply,
const IPC::ChannelHandle& channel,
const content::GPUInfo& gpu_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
GpuHostMsg_EstablishGpuChannel::WriteReplyParams(
reply, render_process_id_, channel, gpu_info);
Send(reply);
}
| 170,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::configureVideoTunnelMode(
OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync,
native_handle_t **sidebandHandle) {
Mutex::Autolock autolock(mLock);
CLOG_CONFIG(configureVideoTunnelMode, "%s:%u tun=%d sync=%u",
portString(portIndex), portIndex, tunneled, audioHwSync);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.configureVideoTunnelMode");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(tunneled, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
ConfigureVideoTunnelModeParams tunnelParams;
InitOMXParams(&tunnelParams);
tunnelParams.nPortIndex = portIndex;
tunnelParams.bTunneled = tunneled;
tunnelParams.nAudioHwSync = audioHwSync;
err = OMX_SetParameter(mHandle, index, &tunnelParams);
if (err != OMX_ErrorNone) {
CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index,
portString(portIndex), portIndex, tunneled, audioHwSync);
return StatusFromOMXError(err);
}
err = OMX_GetParameter(mHandle, index, &tunnelParams);
if (err != OMX_ErrorNone) {
CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index,
portString(portIndex), portIndex, tunneled, audioHwSync);
return StatusFromOMXError(err);
}
if (sidebandHandle) {
*sidebandHandle = (native_handle_t*)tunnelParams.pSidebandWindow;
}
return OK;
}
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 | status_t OMXNodeInstance::configureVideoTunnelMode(
OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync,
native_handle_t **sidebandHandle) {
Mutex::Autolock autolock(mLock);
if (mSailed) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
CLOG_CONFIG(configureVideoTunnelMode, "%s:%u tun=%d sync=%u",
portString(portIndex), portIndex, tunneled, audioHwSync);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.configureVideoTunnelMode");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(tunneled, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
ConfigureVideoTunnelModeParams tunnelParams;
InitOMXParams(&tunnelParams);
tunnelParams.nPortIndex = portIndex;
tunnelParams.bTunneled = tunneled;
tunnelParams.nAudioHwSync = audioHwSync;
err = OMX_SetParameter(mHandle, index, &tunnelParams);
if (err != OMX_ErrorNone) {
CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index,
portString(portIndex), portIndex, tunneled, audioHwSync);
return StatusFromOMXError(err);
}
err = OMX_GetParameter(mHandle, index, &tunnelParams);
if (err != OMX_ErrorNone) {
CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index,
portString(portIndex), portIndex, tunneled, audioHwSync);
return StatusFromOMXError(err);
}
if (sidebandHandle) {
*sidebandHandle = (native_handle_t*)tunnelParams.pSidebandWindow;
}
return OK;
}
| 174,131 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void nfs4_close_state(struct path *path, struct nfs4_state *state, mode_t mode)
{
__nfs4_close(path, state, mode, 0);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | void nfs4_close_state(struct path *path, struct nfs4_state *state, mode_t mode)
void nfs4_close_state(struct path *path, struct nfs4_state *state, fmode_t fmode)
{
__nfs4_close(path, state, fmode, 0);
}
| 165,710 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewDataService::RemoveEntry(
const std::string& preview_ui_addr_str) {
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
data_store_map_.erase(it);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewDataService::RemoveEntry(
void PrintPreviewDataService::RemoveEntry(int32 preview_ui_id) {
data_store_map_.erase(preview_ui_id);
}
| 170,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZSTD_encodeSequences_body(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets)
{
BIT_CStream_t blockStream;
FSE_CState_t stateMatchLength;
FSE_CState_t stateOffsetBits;
FSE_CState_t stateLitLength;
CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
/* first symbols */
FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
if (longOffsets) {
U32 const ofBits = ofCodeTable[nbSeq-1];
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
BIT_flushBits(&blockStream);
}
BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
ofBits - extraBits);
} else {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
}
BIT_flushBits(&blockStream);
{ size_t n;
for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
BYTE const llCode = llCodeTable[n];
BYTE const ofCode = ofCodeTable[n];
BYTE const mlCode = mlCodeTable[n];
U32 const llBits = LL_bits[llCode];
U32 const ofBits = ofCode;
U32 const mlBits = ML_bits[mlCode];
DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
sequences[n].litLength,
sequences[n].matchLength + MINMATCH,
sequences[n].offset);
/* 32b*/ /* 64b*/
/* (7)*/ /* (7)*/
FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
BIT_flushBits(&blockStream); /* (7)*/
BIT_addBits(&blockStream, sequences[n].litLength, llBits);
if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
if (longOffsets) {
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[n].offset, extraBits);
BIT_flushBits(&blockStream); /* (7)*/
}
BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
ofBits - extraBits); /* 31 */
} else {
BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
}
BIT_flushBits(&blockStream); /* (7)*/
} }
DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
FSE_flushCState(&blockStream, &stateMatchLength);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
FSE_flushCState(&blockStream, &stateOffsetBits);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
FSE_flushCState(&blockStream, &stateLitLength);
{ size_t const streamSize = BIT_closeCStream(&blockStream);
if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
return streamSize;
}
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | ZSTD_encodeSequences_body(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets)
{
BIT_CStream_t blockStream;
FSE_CState_t stateMatchLength;
FSE_CState_t stateOffsetBits;
FSE_CState_t stateLitLength;
CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
(int)(blockStream.endPtr - blockStream.startPtr),
(unsigned)dstCapacity);
/* first symbols */
FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
if (longOffsets) {
U32 const ofBits = ofCodeTable[nbSeq-1];
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
BIT_flushBits(&blockStream);
}
BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
ofBits - extraBits);
} else {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
}
BIT_flushBits(&blockStream);
{ size_t n;
for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
BYTE const llCode = llCodeTable[n];
BYTE const ofCode = ofCodeTable[n];
BYTE const mlCode = mlCodeTable[n];
U32 const llBits = LL_bits[llCode];
U32 const ofBits = ofCode;
U32 const mlBits = ML_bits[mlCode];
DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
sequences[n].litLength,
sequences[n].matchLength + MINMATCH,
sequences[n].offset);
/* 32b*/ /* 64b*/
/* (7)*/ /* (7)*/
FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
BIT_flushBits(&blockStream); /* (7)*/
BIT_addBits(&blockStream, sequences[n].litLength, llBits);
if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
if (longOffsets) {
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[n].offset, extraBits);
BIT_flushBits(&blockStream); /* (7)*/
}
BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
ofBits - extraBits); /* 31 */
} else {
BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
}
BIT_flushBits(&blockStream); /* (7)*/
DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
} }
DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
FSE_flushCState(&blockStream, &stateMatchLength);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
FSE_flushCState(&blockStream, &stateOffsetBits);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
FSE_flushCState(&blockStream, &stateLitLength);
{ size_t const streamSize = BIT_closeCStream(&blockStream);
if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
return streamSize;
}
}
| 169,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host,
void DevToolsDomainHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {}
| 172,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
const NavigationRequest& request) {
DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme))
<< "Don't call this method for JavaScript URLs as those create a "
"temporary NavigationRequest and we don't want to reset an ongoing "
"navigation's speculative RFH.";
RenderFrameHostImpl* navigation_rfh = nullptr;
SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
scoped_refptr<SiteInstance> dest_site_instance =
GetSiteInstanceForNavigationRequest(request);
bool use_current_rfh = current_site_instance == dest_site_instance;
bool notify_webui_of_rf_creation = false;
if (use_current_rfh) {
if (speculative_render_frame_host_) {
if (speculative_render_frame_host_->navigation_handle()) {
frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(
speculative_render_frame_host_->navigation_handle()
->pending_nav_entry_id());
}
DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
}
if (frame_tree_node_->IsMainFrame()) {
UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url,
request.bindings());
}
navigation_rfh = render_frame_host_.get();
DCHECK(!speculative_render_frame_host_);
} else {
if (!speculative_render_frame_host_ ||
speculative_render_frame_host_->GetSiteInstance() !=
dest_site_instance.get()) {
CleanUpNavigation();
bool success = CreateSpeculativeRenderFrameHost(current_site_instance,
dest_site_instance.get());
DCHECK(success);
}
DCHECK(speculative_render_frame_host_);
if (frame_tree_node_->IsMainFrame()) {
bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI(
request.common_params().url, request.bindings());
speculative_render_frame_host_->CommitPendingWebUI();
DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui());
notify_webui_of_rf_creation =
changed_web_ui && speculative_render_frame_host_->web_ui();
}
navigation_rfh = speculative_render_frame_host_.get();
if (!render_frame_host_->IsRenderFrameLive()) {
if (GetRenderFrameProxyHost(dest_site_instance.get())) {
navigation_rfh->Send(
new FrameMsg_SwapIn(navigation_rfh->GetRoutingID()));
}
CommitPending();
if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) {
render_frame_host_->web_ui()->RenderFrameCreated(
render_frame_host_.get());
notify_webui_of_rf_creation = false;
}
}
}
DCHECK(navigation_rfh &&
(navigation_rfh == render_frame_host_.get() ||
navigation_rfh == speculative_render_frame_host_.get()));
if (!navigation_rfh->IsRenderFrameLive()) {
if (!ReinitializeRenderFrame(navigation_rfh))
return nullptr;
notify_webui_of_rf_creation = true;
if (navigation_rfh == render_frame_host_.get()) {
EnsureRenderFrameHostVisibilityConsistent();
EnsureRenderFrameHostPageFocusConsistent();
delegate_->NotifyMainFrameSwappedFromRenderManager(
nullptr, render_frame_host_->render_view_host());
}
}
if (notify_webui_of_rf_creation && GetNavigatingWebUI() &&
frame_tree_node_->IsMainFrame()) {
GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh);
}
return navigation_rfh;
}
Commit Message: Fix issue with pending NavigationEntry being discarded incorrectly
This CL fixes an issue where we would attempt to discard a pending
NavigationEntry when a cross-process navigation to this NavigationEntry
is interrupted by another navigation to the same NavigationEntry.
BUG=760342,797656,796135
Change-Id: I204deff1efd4d572dd2e0b20e492592d48d787d9
Reviewed-on: https://chromium-review.googlesource.com/850877
Reviewed-by: Charlie Reis <[email protected]>
Commit-Queue: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528611}
CWE ID: CWE-20 | RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
const NavigationRequest& request) {
DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme))
<< "Don't call this method for JavaScript URLs as those create a "
"temporary NavigationRequest and we don't want to reset an ongoing "
"navigation's speculative RFH.";
RenderFrameHostImpl* navigation_rfh = nullptr;
SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
scoped_refptr<SiteInstance> dest_site_instance =
GetSiteInstanceForNavigationRequest(request);
bool use_current_rfh = current_site_instance == dest_site_instance;
bool notify_webui_of_rf_creation = false;
if (use_current_rfh) {
if (speculative_render_frame_host_) {
// NavigationEntry stopped if needed. This is the case if the new
// navigation was started from BeginNavigation. If the navigation was
// started through the NavigationController, the NavigationController has
// already updated its state properly, and doesn't need to be notified.
if (speculative_render_frame_host_->navigation_handle() &&
request.from_begin_navigation()) {
frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(
speculative_render_frame_host_->navigation_handle()
->pending_nav_entry_id());
}
DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
}
if (frame_tree_node_->IsMainFrame()) {
UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url,
request.bindings());
}
navigation_rfh = render_frame_host_.get();
DCHECK(!speculative_render_frame_host_);
} else {
if (!speculative_render_frame_host_ ||
speculative_render_frame_host_->GetSiteInstance() !=
dest_site_instance.get()) {
CleanUpNavigation();
bool success = CreateSpeculativeRenderFrameHost(current_site_instance,
dest_site_instance.get());
DCHECK(success);
}
DCHECK(speculative_render_frame_host_);
if (frame_tree_node_->IsMainFrame()) {
bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI(
request.common_params().url, request.bindings());
speculative_render_frame_host_->CommitPendingWebUI();
DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui());
notify_webui_of_rf_creation =
changed_web_ui && speculative_render_frame_host_->web_ui();
}
navigation_rfh = speculative_render_frame_host_.get();
if (!render_frame_host_->IsRenderFrameLive()) {
if (GetRenderFrameProxyHost(dest_site_instance.get())) {
navigation_rfh->Send(
new FrameMsg_SwapIn(navigation_rfh->GetRoutingID()));
}
CommitPending();
if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) {
render_frame_host_->web_ui()->RenderFrameCreated(
render_frame_host_.get());
notify_webui_of_rf_creation = false;
}
}
}
DCHECK(navigation_rfh &&
(navigation_rfh == render_frame_host_.get() ||
navigation_rfh == speculative_render_frame_host_.get()));
if (!navigation_rfh->IsRenderFrameLive()) {
if (!ReinitializeRenderFrame(navigation_rfh))
return nullptr;
notify_webui_of_rf_creation = true;
if (navigation_rfh == render_frame_host_.get()) {
EnsureRenderFrameHostVisibilityConsistent();
EnsureRenderFrameHostPageFocusConsistent();
delegate_->NotifyMainFrameSwappedFromRenderManager(
nullptr, render_frame_host_->render_view_host());
}
}
if (notify_webui_of_rf_creation && GetNavigatingWebUI() &&
frame_tree_node_->IsMainFrame()) {
GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh);
}
return navigation_rfh;
}
| 172,684 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
(*GetProcessIdToFilterMap())[render_process_id_] = nullptr;
base::PostTaskWithTraits(
FROM_HERE, BrowserThread::UI,
base::BindOnce(RemoveProcessIdFromGlobalMap, render_process_id_));
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
}
| 173,051 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cues::GetCount() const
{
if (m_cue_points == NULL)
return -1;
return m_count; //TODO: really ignore preload count?
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cues::GetCount() const
const long long stop = m_start + m_size;
| 174,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VP8XChunk::width(XMP_Uns32 val)
{
PutLE24(&this->data[4], val - 1);
}
Commit Message:
CWE ID: CWE-20 | void VP8XChunk::width(XMP_Uns32 val)
{
PutLE24(&this->data[4], val > 0 ? val - 1 : 0);
}
| 165,366 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
Commit Message: OomIntervention opt-out should work properly with 'show original'
OomIntervention should not be re-triggered on the same page if the user declines the intervention once.
This CL fixes the bug.
Bug: 889131, 887119
Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8
Reviewed-on: https://chromium-review.googlesource.com/1245019
Commit-Queue: Yuzu Saijo <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594574}
CWE ID: CWE-119 | void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
DCHECK(renderer_pause_enabled_ || navigate_ads_enabled_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
| 172,115 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
size_t width = static_cast<size_t>(input->width());
size_t height = static_cast<size_t>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
size_t imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (size_t i = 0; i < height / 2; i++) {
size_t topFirstElement = i * imageRowBytes;
size_t topLastElement = (i + 1) * imageRowBytes;
size_t bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
unsigned width = static_cast<unsigned>(input->width());
unsigned height = static_cast<unsigned>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
unsigned imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (unsigned i = 0; i < height / 2; i++) {
unsigned topFirstElement = i * imageRowBytes;
unsigned topLastElement = (i + 1) * imageRowBytes;
unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
| 172,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N)
{
/* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */
BIGNUM *u;
unsigned char cu[SHA_DIGEST_LENGTH];
unsigned char *cAB;
EVP_MD_CTX ctxt;
int longN;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
longN= BN_num_bytes(N);
if ((cAB = OPENSSL_malloc(2*longN)) == NULL)
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN);
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN);
OPENSSL_free(cAB);
EVP_DigestFinal_ex(&ctxt, cu, NULL);
EVP_MD_CTX_cleanup(&ctxt);
if (!(u = BN_bin2bn(cu, sizeof(cu), NULL)))
return NULL;
if (!BN_is_zero(u))
return u;
BN_free(u);
return NULL;
}
Commit Message:
CWE ID: CWE-119 | BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N)
{
/* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */
BIGNUM *u;
unsigned char cu[SHA_DIGEST_LENGTH];
unsigned char *cAB;
EVP_MD_CTX ctxt;
int longN;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if (BN_ucmp(A, N) >= 0 || BN_ucmp(B, N) >= 0)
return NULL;
longN= BN_num_bytes(N);
if ((cAB = OPENSSL_malloc(2*longN)) == NULL)
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN);
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN);
OPENSSL_free(cAB);
EVP_DigestFinal_ex(&ctxt, cu, NULL);
EVP_MD_CTX_cleanup(&ctxt);
if (!(u = BN_bin2bn(cu, sizeof(cu), NULL)))
return NULL;
if (!BN_is_zero(u))
return u;
BN_free(u);
return NULL;
}
| 165,172 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuDataManager::UpdateGpuFeatureFlags() {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags));
return;
}
GpuBlacklist* gpu_blacklist = GetGpuBlacklist();
if (gpu_blacklist == NULL)
return;
if (!gpu_blacklist) {
gpu_feature_flags_.set_flags(0);
return;
}
{
base::AutoLock auto_lock(gpu_info_lock_);
gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags(
GpuBlacklist::kOsAny, NULL, gpu_info_);
}
uint32 max_entry_id = gpu_blacklist->max_entry_id();
if (!gpu_feature_flags_.flags()) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
0, max_entry_id + 1);
return;
}
RunGpuInfoUpdateCallbacks();
std::vector<uint32> flag_entries;
gpu_blacklist->GetGpuFeatureFlagEntries(
GpuFeatureFlags::kGpuFeatureAll, flag_entries);
DCHECK_GT(flag_entries.size(), 0u);
for (size_t i = 0; i < flag_entries.size(); ++i) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
flag_entries[i], max_entry_id + 1);
}
}
Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE)
CIDs 16230, 16439, 16610, 16635
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/7215029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void GpuDataManager::UpdateGpuFeatureFlags() {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags));
return;
}
GpuBlacklist* gpu_blacklist = GetGpuBlacklist();
if (!gpu_blacklist) {
gpu_feature_flags_.set_flags(0);
return;
}
{
base::AutoLock auto_lock(gpu_info_lock_);
gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags(
GpuBlacklist::kOsAny, NULL, gpu_info_);
}
uint32 max_entry_id = gpu_blacklist->max_entry_id();
if (!gpu_feature_flags_.flags()) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
0, max_entry_id + 1);
return;
}
RunGpuInfoUpdateCallbacks();
std::vector<uint32> flag_entries;
gpu_blacklist->GetGpuFeatureFlagEntries(
GpuFeatureFlags::kGpuFeatureAll, flag_entries);
DCHECK_GT(flag_entries.size(), 0u);
for (size_t i = 0; i < flag_entries.size(); ++i) {
UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
flag_entries[i], max_entry_id + 1);
}
}
| 170,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
Commit Message: drm: integer overflow in drm_mode_dirtyfb_ioctl()
There is a potential integer overflow in drm_mode_dirtyfb_ioctl()
if userspace passes in a large num_clips. The call to kmalloc would
allocate a small buffer, and the call to fb->funcs->dirty may result
in a memory corruption.
Reported-by: Haogang Chen <[email protected]>
Signed-off-by: Xi Wang <[email protected]>
Cc: [email protected]
Signed-off-by: Dave Airlie <[email protected]>
CWE ID: CWE-189 | int drm_mode_dirtyfb_ioctl(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_clip_rect __user *clips_ptr;
struct drm_clip_rect *clips = NULL;
struct drm_mode_fb_dirty_cmd *r = data;
struct drm_mode_object *obj;
struct drm_framebuffer *fb;
unsigned flags;
int num_clips;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
mutex_lock(&dev->mode_config.mutex);
obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB);
if (!obj) {
DRM_ERROR("invalid framebuffer id\n");
ret = -EINVAL;
goto out_err1;
}
fb = obj_to_fb(obj);
num_clips = r->num_clips;
clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr;
if (!num_clips != !clips_ptr) {
ret = -EINVAL;
goto out_err1;
}
flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags;
/* If userspace annotates copy, clips must come in pairs */
if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) {
ret = -EINVAL;
goto out_err1;
}
if (num_clips && clips_ptr) {
if (num_clips < 0 || num_clips > DRM_MODE_FB_DIRTY_MAX_CLIPS) {
ret = -EINVAL;
goto out_err1;
}
clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL);
if (!clips) {
ret = -ENOMEM;
goto out_err1;
}
ret = copy_from_user(clips, clips_ptr,
num_clips * sizeof(*clips));
if (ret) {
ret = -EFAULT;
goto out_err2;
}
}
if (fb->funcs->dirty) {
ret = fb->funcs->dirty(fb, file_priv, flags, r->color,
clips, num_clips);
} else {
ret = -ENOSYS;
goto out_err2;
}
out_err2:
kfree(clips);
out_err1:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
| 165,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
}
return GF_OK;
}
Commit Message: prevent dref memleak on invalid input (#1183)
CWE ID: CWE-400 | GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_Box* dref;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref;
gf_isom_box_add_for_dump_mode(s, dref);
}
return GF_OK;
}
| 169,759 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t socket_read(const socket_t *socket, void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return recv(socket->fd, buf, count, MSG_DONTWAIT);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | ssize_t socket_read(const socket_t *socket, void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return TEMP_FAILURE_RETRY(recv(socket->fd, buf, count, MSG_DONTWAIT));
}
| 173,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
Commit Message:
CWE ID: CWE-189 | gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname)
{
gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem;
byte *ptr = 0;
#ifdef DEBUG
const char *msg;
static const char *const ok_msg = "OK";
# define set_msg(str) (msg = (str))
#else
# define set_msg(str) DO_NOTHING
#endif
/* Exclusive acces so our decisions and changes are 'atomic' */
if (mmem->monitor)
gx_monitor_enter(mmem->monitor);
if (size > mmem->limit - sizeof(gs_malloc_block_t)) {
/* Definitely too large to allocate; also avoids overflow. */
set_msg("exceeded limit");
} else {
uint added = size + sizeof(gs_malloc_block_t);
if (added <= size || mmem->limit - added < mmem->used)
set_msg("exceeded limit");
else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0)
set_msg("failed");
else {
gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr;
/*
* We would like to check that malloc aligns blocks at least as
* strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD).
* However, Microsoft VC 6 does not satisfy this requirement.
* See gsmemory.h for more explanation.
*/
set_msg(ok_msg);
if (mmem->allocated)
mmem->allocated->prev = bp;
bp->next = mmem->allocated;
bp->prev = 0;
bp->size = size;
bp->type = &st_bytes;
bp->cname = cname;
mmem->allocated = bp;
ptr = (byte *) (bp + 1);
mmem->used += size + sizeof(gs_malloc_block_t);
if (mmem->used > mmem->max_used)
mmem->max_used = mmem->used;
}
}
if (mmem->monitor)
gx_monitor_leave(mmem->monitor); /* Done with exclusive access */
/* We don't want to 'fill' under mutex to keep the window smaller */
if (ptr)
gs_alloc_fill(ptr, gs_alloc_fill_alloc, size);
#ifdef DEBUG
if (gs_debug_c('a') || msg != ok_msg)
dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n",
client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used);
#endif
return ptr;
#undef set_msg
}
| 164,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
progress_event_timer_.Stop();
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
ScheduleEvent(EventTypeNames::progress);
ScheduleEvent(EventTypeNames::suspend);
SetNetworkState(kNetworkIdle);
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200 | void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
progress_event_timer_.Stop();
if (!MediaShouldBeOpaque()) {
// Schedule one last progress event so we guarantee that at least one is
// fired for files that load very quickly.
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
ScheduleEvent(EventTypeNames::progress);
ScheduleEvent(EventTypeNames::suspend);
SetNetworkState(kNetworkIdle);
}
}
| 173,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MaybeChangeCurrentKeyboardLayout(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void MaybeChangeCurrentKeyboardLayout(const std::string& section,
void MaybeChangeCurrentKeyboardLayout(
const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
| 170,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int DefragTrackerReuseTest(void)
{
int ret = 0;
int id = 1;
Packet *p1 = NULL;
DefragTracker *tracker1 = NULL, *tracker2 = NULL;
DefragInit();
/* Build a packet, its not a fragment but shouldn't matter for
* this test. */
p1 = BuildTestPacket(id, 0, 0, 'A', 8);
if (p1 == NULL) {
goto end;
}
/* Get a tracker. It shouldn't look like its already in use. */
tracker1 = DefragGetTracker(NULL, NULL, p1);
if (tracker1 == NULL) {
goto end;
}
if (tracker1->seen_last) {
goto end;
}
if (tracker1->remove) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Get a tracker again, it should be the same one. */
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 != tracker1) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Now mark the tracker for removal. It should not be returned
* when we get a tracker for a packet that may have the same
* attributes. */
tracker1->remove = 1;
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 == tracker1) {
goto end;
}
if (tracker2->remove) {
goto end;
}
ret = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | static int DefragTrackerReuseTest(void)
{
int ret = 0;
int id = 1;
Packet *p1 = NULL;
DefragTracker *tracker1 = NULL, *tracker2 = NULL;
DefragInit();
/* Build a packet, its not a fragment but shouldn't matter for
* this test. */
p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 0, 'A', 8);
if (p1 == NULL) {
goto end;
}
/* Get a tracker. It shouldn't look like its already in use. */
tracker1 = DefragGetTracker(NULL, NULL, p1);
if (tracker1 == NULL) {
goto end;
}
if (tracker1->seen_last) {
goto end;
}
if (tracker1->remove) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Get a tracker again, it should be the same one. */
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 != tracker1) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Now mark the tracker for removal. It should not be returned
* when we get a tracker for a packet that may have the same
* attributes. */
tracker1->remove = 1;
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 == tracker1) {
goto end;
}
if (tracker2->remove) {
goto end;
}
ret = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
DefragDestroy();
return ret;
}
| 168,304 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)
{
int i, x;
u_int c;
const u_char *osp, *p;
#define FETCH(c, sp, length) \
do { \
if (length < 1) \
goto pktend; \
ND_TCHECK(*sp); \
c = *sp++; \
length--; \
} while (0)
osp = sp;
FETCH(c, sp, length);
if (c != IAC)
goto pktend;
FETCH(c, sp, length);
if (c == IAC) { /* <IAC><IAC>! */
if (print)
ND_PRINT((ndo, "IAC IAC"));
goto done;
}
i = c - TELCMD_FIRST;
if (i < 0 || i > IAC - TELCMD_FIRST)
goto pktend;
switch (c) {
case DONT:
case DO:
case WONT:
case WILL:
case SB:
/* DONT/DO/WONT/WILL x */
FETCH(x, sp, length);
if (x >= 0 && x < NTELOPTS) {
if (print)
ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x]));
} else {
if (print)
ND_PRINT((ndo, "%s %#x", telcmds[i], x));
}
if (c != SB)
break;
/* IAC SB .... IAC SE */
p = sp;
while (length > (u_int)(p + 1 - sp)) {
ND_TCHECK2(*p, 2);
if (p[0] == IAC && p[1] == SE)
break;
p++;
}
if (*p != IAC)
goto pktend;
switch (x) {
case TELOPT_AUTHENTICATION:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype)));
break;
case TELOPT_ENCRYPT:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype)));
break;
default:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds)));
break;
}
while (p > sp) {
FETCH(x, sp, length);
if (print)
ND_PRINT((ndo, " %#x", x));
}
/* terminating IAC SE */
if (print)
ND_PRINT((ndo, " SE"));
sp += 2;
break;
default:
if (print)
ND_PRINT((ndo, "%s", telcmds[i]));
goto done;
}
done:
return sp - osp;
trunc:
ND_PRINT((ndo, "%s", tstr));
pktend:
return -1;
#undef FETCH
}
Commit Message: CVE-2017-12988/TELNET: Add a missing bounds check.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)
{
int i, x;
u_int c;
const u_char *osp, *p;
#define FETCH(c, sp, length) \
do { \
if (length < 1) \
goto pktend; \
ND_TCHECK(*sp); \
c = *sp++; \
length--; \
} while (0)
osp = sp;
FETCH(c, sp, length);
if (c != IAC)
goto pktend;
FETCH(c, sp, length);
if (c == IAC) { /* <IAC><IAC>! */
if (print)
ND_PRINT((ndo, "IAC IAC"));
goto done;
}
i = c - TELCMD_FIRST;
if (i < 0 || i > IAC - TELCMD_FIRST)
goto pktend;
switch (c) {
case DONT:
case DO:
case WONT:
case WILL:
case SB:
/* DONT/DO/WONT/WILL x */
FETCH(x, sp, length);
if (x >= 0 && x < NTELOPTS) {
if (print)
ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x]));
} else {
if (print)
ND_PRINT((ndo, "%s %#x", telcmds[i], x));
}
if (c != SB)
break;
/* IAC SB .... IAC SE */
p = sp;
while (length > (u_int)(p + 1 - sp)) {
ND_TCHECK2(*p, 2);
if (p[0] == IAC && p[1] == SE)
break;
p++;
}
ND_TCHECK(*p);
if (*p != IAC)
goto pktend;
switch (x) {
case TELOPT_AUTHENTICATION:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype)));
break;
case TELOPT_ENCRYPT:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype)));
break;
default:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds)));
break;
}
while (p > sp) {
FETCH(x, sp, length);
if (print)
ND_PRINT((ndo, " %#x", x));
}
/* terminating IAC SE */
if (print)
ND_PRINT((ndo, " SE"));
sp += 2;
break;
default:
if (print)
ND_PRINT((ndo, "%s", telcmds[i]));
goto done;
}
done:
return sp - osp;
trunc:
ND_PRINT((ndo, "%s", tstr));
pktend:
return -1;
#undef FETCH
}
| 167,929 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fdct4x4_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fdct4x4_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.