instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionRemoveEventListener(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
JSValue listener = exec->argument(1);
if (!listener.isObject())
return JSValue::encode(jsUndefined());
impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec));
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionRemoveEventListener(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
JSValue listener = exec->argument(1);
if (!listener.isObject())
return JSValue::encode(jsUndefined());
impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec));
return JSValue::encode(jsUndefined());
}
| 170,607 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp,
struct inode *parent)
{
int len = *lenp;
struct kernel_lb_addr location = UDF_I(inode)->i_location;
struct fid *fid = (struct fid *)fh;
int type = FILEID_UDF_WITHOUT_PARENT;
if (parent && (len < 5)) {
*lenp = 5;
return 255;
} else if (len < 3) {
*lenp = 3;
return 255;
}
*lenp = 3;
fid->udf.block = location.logicalBlockNum;
fid->udf.partref = location.partitionReferenceNum;
fid->udf.generation = inode->i_generation;
if (parent) {
location = UDF_I(parent)->i_location;
fid->udf.parent_block = location.logicalBlockNum;
fid->udf.parent_partref = location.partitionReferenceNum;
fid->udf.parent_generation = inode->i_generation;
*lenp = 5;
type = FILEID_UDF_WITH_PARENT;
}
return type;
}
Commit Message: udf: avoid info leak on export
For type 0x51 the udf.parent_partref member in struct fid gets copied
uninitialized to userland. Fix this by initializing it to 0.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-200 | static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp,
struct inode *parent)
{
int len = *lenp;
struct kernel_lb_addr location = UDF_I(inode)->i_location;
struct fid *fid = (struct fid *)fh;
int type = FILEID_UDF_WITHOUT_PARENT;
if (parent && (len < 5)) {
*lenp = 5;
return 255;
} else if (len < 3) {
*lenp = 3;
return 255;
}
*lenp = 3;
fid->udf.block = location.logicalBlockNum;
fid->udf.partref = location.partitionReferenceNum;
fid->udf.parent_partref = 0;
fid->udf.generation = inode->i_generation;
if (parent) {
location = UDF_I(parent)->i_location;
fid->udf.parent_block = location.logicalBlockNum;
fid->udf.parent_partref = location.partitionReferenceNum;
fid->udf.parent_generation = inode->i_generation;
*lenp = 5;
type = FILEID_UDF_WITH_PARENT;
}
return type;
}
| 166,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PromoResourceService::PromoResourceStateChange() {
web_resource_update_scheduled_ = false;
content::NotificationService* service =
content::NotificationService::current();
service->Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED,
content::Source<WebResourceService>(this),
content::NotificationService::NoDetails());
}
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::PromoResourceStateChange() {
content::NotificationService* service =
content::NotificationService::current();
service->Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED,
content::Source<WebResourceService>(this),
content::NotificationService::NoDetails());
}
| 170,783 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: huff_get_next_word(Jbig2HuffmanState *hs, int offset)
{
uint32_t word = 0;
Jbig2WordStream *ws = hs->ws;
if ((ws->get_next_word(ws, offset, &word)) && ((hs->offset_limit == 0) || (offset < hs->offset_limit)))
hs->offset_limit = offset;
return word;
}
Commit Message:
CWE ID: CWE-119 | huff_get_next_word(Jbig2HuffmanState *hs, int offset)
huff_get_next_word(Jbig2HuffmanState *hs, uint32_t offset)
{
uint32_t word = 0;
Jbig2WordStream *ws = hs->ws;
if ((ws->get_next_word(ws, offset, &word)) && ((hs->offset_limit == 0) || (offset < hs->offset_limit)))
hs->offset_limit = offset;
return word;
}
| 165,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread())
blobRegistry().registerBlobURL(url, srcURL);
else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry())
registry->registerBlobURL(url, srcURL);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
| 170,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
struct search_domain *dom;
for (dom = state->head; dom; dom = dom->next) {
if (!n--) {
/* this is the postfix we want */
/* the actual postfix string is kept at the end of the structure */
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
const int postfix_len = dom->len;
char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
if (!newname) return NULL;
memcpy(newname, base_name, base_len);
if (need_to_append_dot) newname[base_len] = '.';
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
newname[base_len + need_to_append_dot + postfix_len] = 0;
return newname;
}
}
/* we ran off the end of the list and still didn't find the requested string */
EVUTIL_ASSERT(0);
return NULL; /* unreachable; stops warnings in some compilers. */
}
Commit Message: evdns: fix searching empty hostnames
From #332:
Here follows a bug report by **Guido Vranken** via the _Tor bug bounty program_. Please credit Guido accordingly.
## Bug report
The DNS code of Libevent contains this rather obvious OOB read:
```c
static char *
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
```
If the length of ```base_name``` is 0, then line 3125 reads 1 byte before the buffer. This will trigger a crash on ASAN-protected builds.
To reproduce:
Build libevent with ASAN:
```
$ CFLAGS='-fomit-frame-pointer -fsanitize=address' ./configure && make -j4
```
Put the attached ```resolv.conf``` and ```poc.c``` in the source directory and then do:
```
$ gcc -fsanitize=address -fomit-frame-pointer poc.c .libs/libevent.a
$ ./a.out
=================================================================
==22201== ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60060000efdf at pc 0x4429da bp 0x7ffe1ed47300 sp 0x7ffe1ed472f8
READ of size 1 at 0x60060000efdf thread T0
```
P.S. we can add a check earlier, but since this is very uncommon, I didn't add it.
Fixes: #332
CWE ID: CWE-125 | search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
char need_to_append_dot;
struct search_domain *dom;
if (!base_len) return NULL;
need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
for (dom = state->head; dom; dom = dom->next) {
if (!n--) {
/* this is the postfix we want */
/* the actual postfix string is kept at the end of the structure */
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
const int postfix_len = dom->len;
char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
if (!newname) return NULL;
memcpy(newname, base_name, base_len);
if (need_to_append_dot) newname[base_len] = '.';
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
newname[base_len + need_to_append_dot + postfix_len] = 0;
return newname;
}
}
/* we ran off the end of the list and still didn't find the requested string */
EVUTIL_ASSERT(0);
return NULL; /* unreachable; stops warnings in some compilers. */
}
| 168,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: call_bind_status(struct rpc_task *task)
{
int status = -EIO;
if (task->tk_status >= 0) {
dprint_status(task);
task->tk_status = 0;
task->tk_action = call_connect;
return;
}
switch (task->tk_status) {
case -ENOMEM:
dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid);
rpc_delay(task, HZ >> 2);
goto retry_timeout;
case -EACCES:
dprintk("RPC: %5u remote rpcbind: RPC program/version "
"unavailable\n", task->tk_pid);
/* fail immediately if this is an RPC ping */
if (task->tk_msg.rpc_proc->p_proc == 0) {
status = -EOPNOTSUPP;
break;
}
rpc_delay(task, 3*HZ);
goto retry_timeout;
case -ETIMEDOUT:
dprintk("RPC: %5u rpcbind request timed out\n",
task->tk_pid);
goto retry_timeout;
case -EPFNOSUPPORT:
/* server doesn't support any rpcbind version we know of */
dprintk("RPC: %5u unrecognized remote rpcbind service\n",
task->tk_pid);
break;
case -EPROTONOSUPPORT:
dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n",
task->tk_pid);
task->tk_status = 0;
task->tk_action = call_bind;
return;
case -ECONNREFUSED: /* connection problems */
case -ECONNRESET:
case -ENOTCONN:
case -EHOSTDOWN:
case -EHOSTUNREACH:
case -ENETUNREACH:
case -EPIPE:
dprintk("RPC: %5u remote rpcbind unreachable: %d\n",
task->tk_pid, task->tk_status);
if (!RPC_IS_SOFTCONN(task)) {
rpc_delay(task, 5*HZ);
goto retry_timeout;
}
status = task->tk_status;
break;
default:
dprintk("RPC: %5u unrecognized rpcbind error (%d)\n",
task->tk_pid, -task->tk_status);
}
rpc_exit(task, status);
return;
retry_timeout:
task->tk_action = call_timeout;
}
Commit Message: NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
Cc: [email protected]
CWE ID: CWE-399 | call_bind_status(struct rpc_task *task)
{
int status = -EIO;
if (task->tk_status >= 0) {
dprint_status(task);
task->tk_status = 0;
task->tk_action = call_connect;
return;
}
switch (task->tk_status) {
case -ENOMEM:
dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid);
rpc_delay(task, HZ >> 2);
goto retry_timeout;
case -EACCES:
dprintk("RPC: %5u remote rpcbind: RPC program/version "
"unavailable\n", task->tk_pid);
/* fail immediately if this is an RPC ping */
if (task->tk_msg.rpc_proc->p_proc == 0) {
status = -EOPNOTSUPP;
break;
}
if (task->tk_rebind_retry == 0)
break;
task->tk_rebind_retry--;
rpc_delay(task, 3*HZ);
goto retry_timeout;
case -ETIMEDOUT:
dprintk("RPC: %5u rpcbind request timed out\n",
task->tk_pid);
goto retry_timeout;
case -EPFNOSUPPORT:
/* server doesn't support any rpcbind version we know of */
dprintk("RPC: %5u unrecognized remote rpcbind service\n",
task->tk_pid);
break;
case -EPROTONOSUPPORT:
dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n",
task->tk_pid);
task->tk_status = 0;
task->tk_action = call_bind;
return;
case -ECONNREFUSED: /* connection problems */
case -ECONNRESET:
case -ENOTCONN:
case -EHOSTDOWN:
case -EHOSTUNREACH:
case -ENETUNREACH:
case -EPIPE:
dprintk("RPC: %5u remote rpcbind unreachable: %d\n",
task->tk_pid, task->tk_status);
if (!RPC_IS_SOFTCONN(task)) {
rpc_delay(task, 5*HZ);
goto retry_timeout;
}
status = task->tk_status;
break;
default:
dprintk("RPC: %5u unrecognized rpcbind error (%d)\n",
task->tk_pid, -task->tk_status);
}
rpc_exit(task, status);
return;
retry_timeout:
task->tk_action = call_timeout;
}
| 166,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LayoutSVGContainer::layout()
{
ASSERT(needsLayout());
LayoutAnalyzer::Scope analyzer(*this);
calcViewport();
bool updatedTransform = calculateLocalTransform();
m_didScreenScaleFactorChange = updatedTransform || SVGLayoutSupport::screenScaleFactorChanged(parent());
determineIfLayoutSizeChanged();
bool layoutSizeChanged = element()->hasRelativeLengths()
&& SVGLayoutSupport::layoutSizeOfNearestViewportChanged(this);
SVGLayoutSupport::layoutChildren(firstChild(), false, m_didScreenScaleFactorChange, layoutSizeChanged);
if (everHadLayout() && needsLayout())
SVGResourcesCache::clientLayoutChanged(this);
if (m_needsBoundariesUpdate || updatedTransform) {
updateCachedBoundaries();
m_needsBoundariesUpdate = false;
LayoutSVGModelObject::setNeedsBoundariesUpdate();
}
ASSERT(!m_needsBoundariesUpdate);
clearNeedsLayout();
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | void LayoutSVGContainer::layout()
{
ASSERT(needsLayout());
LayoutAnalyzer::Scope analyzer(*this);
calcViewport();
TransformChange transformChange = calculateLocalTransform();
m_didScreenScaleFactorChange =
transformChange == TransformChange::Full || SVGLayoutSupport::screenScaleFactorChanged(parent());
determineIfLayoutSizeChanged();
bool layoutSizeChanged = element()->hasRelativeLengths()
&& SVGLayoutSupport::layoutSizeOfNearestViewportChanged(this);
SVGLayoutSupport::layoutChildren(firstChild(), false, m_didScreenScaleFactorChange, layoutSizeChanged);
if (everHadLayout() && needsLayout())
SVGResourcesCache::clientLayoutChanged(this);
if (m_needsBoundariesUpdate || transformChange != TransformChange::None) {
updateCachedBoundaries();
m_needsBoundariesUpdate = false;
LayoutSVGModelObject::setNeedsBoundariesUpdate();
}
ASSERT(!m_needsBoundariesUpdate);
clearNeedsLayout();
}
| 171,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == nameAttr) {
removeFromRadioButtonGroup();
m_name = value;
addToRadioButtonGroup();
HTMLTextFormControlElement::parseAttribute(name, value);
} else if (name == autocompleteAttr) {
if (equalIgnoringCase(value, "off"))
m_autocomplete = Off;
else {
if (value.isEmpty())
m_autocomplete = Uninitialized;
else
m_autocomplete = On;
}
} else if (name == typeAttr)
updateType();
else if (name == valueAttr) {
if (!hasDirtyValue()) {
updatePlaceholderVisibility(false);
setNeedsStyleRecalc();
}
setFormControlValueMatchesRenderer(false);
setNeedsValidityCheck();
m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
m_inputType->valueAttributeChanged();
} else if (name == checkedAttr) {
if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
setChecked(!value.isNull());
m_reflectsCheckedAttribute = true;
}
} else if (name == maxlengthAttr)
parseMaxLengthAttribute(value);
else if (name == sizeAttr) {
int oldSize = m_size;
int valueAsInteger = value.toInt();
m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize;
if (m_size != oldSize && renderer())
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
} else if (name == altAttr)
m_inputType->altAttributeChanged();
else if (name == srcAttr)
m_inputType->srcAttributeChanged();
else if (name == usemapAttr || name == accesskeyAttr) {
} else if (name == onsearchAttr) {
setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value));
} else if (name == resultsAttr) {
int oldResults = m_maxResults;
m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
lazyReattachIfAttached();
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::ResultsAttribute);
} else if (name == incrementalAttr) {
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::IncrementalAttribute);
} else if (name == minAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MinAttribute);
} else if (name == maxAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MaxAttribute);
} else if (name == multipleAttr) {
m_inputType->multipleAttributeChanged();
setNeedsValidityCheck();
} else if (name == stepAttr) {
m_inputType->stepAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::StepAttribute);
} else if (name == patternAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PatternAttribute);
} else if (name == precisionAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PrecisionAttribute);
} else if (name == disabledAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->disabledAttributeChanged();
} else if (name == readonlyAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->readonlyAttributeChanged();
} else if (name == listAttr) {
m_hasNonEmptyList = !value.isEmpty();
if (m_hasNonEmptyList) {
resetListAttributeTargetObserver();
listAttributeTargetChanged();
}
UseCounter::count(document(), UseCounter::ListAttribute);
}
#if ENABLE(INPUT_SPEECH)
else if (name == webkitspeechAttr) {
if (renderer()) {
detach();
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
if (!attached())
attach();
} else {
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
}
setFormControlValueMatchesRenderer(false);
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
} else if (name == onwebkitspeechchangeAttr)
setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
#endif
else if (name == webkitdirectoryAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
}
else
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->attributeChanged();
}
Commit Message: Setting input.x-webkit-speech should not cause focus change
In r150866, we introduced element()->focus() in destroyShadowSubtree()
to retain focus on <input> when its type attribute gets changed.
But when x-webkit-speech attribute is changed, the element is detached
before calling destroyShadowSubtree() and element()->focus() failed
This patch moves detach() after destroyShadowSubtree() to fix the
problem.
BUG=243818
TEST=fast/forms/input-type-change-focusout.html
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/16084005
git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == nameAttr) {
removeFromRadioButtonGroup();
m_name = value;
addToRadioButtonGroup();
HTMLTextFormControlElement::parseAttribute(name, value);
} else if (name == autocompleteAttr) {
if (equalIgnoringCase(value, "off"))
m_autocomplete = Off;
else {
if (value.isEmpty())
m_autocomplete = Uninitialized;
else
m_autocomplete = On;
}
} else if (name == typeAttr)
updateType();
else if (name == valueAttr) {
if (!hasDirtyValue()) {
updatePlaceholderVisibility(false);
setNeedsStyleRecalc();
}
setFormControlValueMatchesRenderer(false);
setNeedsValidityCheck();
m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
m_inputType->valueAttributeChanged();
} else if (name == checkedAttr) {
if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
setChecked(!value.isNull());
m_reflectsCheckedAttribute = true;
}
} else if (name == maxlengthAttr)
parseMaxLengthAttribute(value);
else if (name == sizeAttr) {
int oldSize = m_size;
int valueAsInteger = value.toInt();
m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize;
if (m_size != oldSize && renderer())
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
} else if (name == altAttr)
m_inputType->altAttributeChanged();
else if (name == srcAttr)
m_inputType->srcAttributeChanged();
else if (name == usemapAttr || name == accesskeyAttr) {
} else if (name == onsearchAttr) {
setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value));
} else if (name == resultsAttr) {
int oldResults = m_maxResults;
m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
lazyReattachIfAttached();
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::ResultsAttribute);
} else if (name == incrementalAttr) {
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::IncrementalAttribute);
} else if (name == minAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MinAttribute);
} else if (name == maxAttr) {
m_inputType->minOrMaxAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::MaxAttribute);
} else if (name == multipleAttr) {
m_inputType->multipleAttributeChanged();
setNeedsValidityCheck();
} else if (name == stepAttr) {
m_inputType->stepAttributeChanged();
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::StepAttribute);
} else if (name == patternAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PatternAttribute);
} else if (name == precisionAttr) {
setNeedsValidityCheck();
UseCounter::count(document(), UseCounter::PrecisionAttribute);
} else if (name == disabledAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->disabledAttributeChanged();
} else if (name == readonlyAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->readonlyAttributeChanged();
} else if (name == listAttr) {
m_hasNonEmptyList = !value.isEmpty();
if (m_hasNonEmptyList) {
resetListAttributeTargetObserver();
listAttributeTargetChanged();
}
UseCounter::count(document(), UseCounter::ListAttribute);
}
#if ENABLE(INPUT_SPEECH)
else if (name == webkitspeechAttr) {
if (renderer()) {
m_inputType->destroyShadowSubtree();
detach();
m_inputType->createShadowSubtree();
if (!attached())
attach();
} else {
m_inputType->destroyShadowSubtree();
m_inputType->createShadowSubtree();
}
setFormControlValueMatchesRenderer(false);
setNeedsStyleRecalc();
UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
} else if (name == onwebkitspeechchangeAttr)
setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
#endif
else if (name == webkitdirectoryAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
}
else
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputType->attributeChanged();
}
| 171,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk,
int depth) {
xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL;
const xmlChar *elem;
xmlChar type = 0;
if (((depth > 128) && ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(depth > 2048)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED,
"xmlParseElementChildrenContentDecl : depth %d too deep, use XML_PARSE_HUGE\n",
depth);
return(NULL);
}
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on first child */
NEXT;
SKIP_BLANKS;
cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
GROW;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
return(NULL);
}
cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (cur == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
GROW;
if (RAW == '?') {
cur->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
cur->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
cur->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
cur->ocur = XML_ELEMENT_CONTENT_ONCE;
}
GROW;
}
SKIP_BLANKS;
SHRINK;
while (RAW != ')') {
/*
* Each loop we parse one separator and one element.
*/
if (RAW == ',') {
if (type == 0) type = CUR;
/*
* Detect "Name | Name , Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else if (RAW == '|') {
if (type == 0) type = CUR;
/*
* Detect "Name , Name | Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
GROW;
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on second child */
NEXT;
SKIP_BLANKS;
last = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (last == NULL) {
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (RAW == '?') {
last->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
last->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
last->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
last->ocur = XML_ELEMENT_CONTENT_ONCE;
}
}
SKIP_BLANKS;
GROW;
}
if ((cur != NULL) && (last != NULL)) {
cur->c2 = last;
if (last != NULL)
last->parent = cur;
}
if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
if (RAW == '?') {
if (ret != NULL) {
if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_OPT;
}
NEXT;
} else if (RAW == '*') {
if (ret != NULL) {
ret->ocur = XML_ELEMENT_CONTENT_MULT;
cur = ret;
/*
* Some normalization:
* (a | b* | c?)* == (a | b | c)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
cur = cur->c2;
}
}
NEXT;
} else if (RAW == '+') {
if (ret != NULL) {
int found = 0;
if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_PLUS;
/*
* Some normalization:
* (a | b*)+ == (a | b)*
* (a | b?)+ == (a | b)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
cur = cur->c2;
}
if (found)
ret->ocur = XML_ELEMENT_CONTENT_MULT;
}
NEXT;
}
return(ret);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk,
int depth) {
xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL;
const xmlChar *elem;
xmlChar type = 0;
if (((depth > 128) && ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(depth > 2048)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED,
"xmlParseElementChildrenContentDecl : depth %d too deep, use XML_PARSE_HUGE\n",
depth);
return(NULL);
}
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on first child */
NEXT;
SKIP_BLANKS;
cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
GROW;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
return(NULL);
}
cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (cur == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
GROW;
if (RAW == '?') {
cur->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
cur->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
cur->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
cur->ocur = XML_ELEMENT_CONTENT_ONCE;
}
GROW;
}
SKIP_BLANKS;
SHRINK;
while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) {
/*
* Each loop we parse one separator and one element.
*/
if (RAW == ',') {
if (type == 0) type = CUR;
/*
* Detect "Name | Name , Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else if (RAW == '|') {
if (type == 0) type = CUR;
/*
* Detect "Name , Name | Name" error
*/
else if (type != CUR) {
xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
"xmlParseElementChildrenContentDecl : '%c' expected\n",
type);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
NEXT;
op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
if (op == NULL) {
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (last == NULL) {
op->c1 = ret;
if (ret != NULL)
ret->parent = op;
ret = cur = op;
} else {
cur->c2 = op;
if (op != NULL)
op->parent = cur;
op->c1 = last;
if (last != NULL)
last->parent = op;
cur =op;
last = NULL;
}
} else {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
if ((last != NULL) && (last != ret))
xmlFreeDocElementContent(ctxt->myDoc, last);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
GROW;
SKIP_BLANKS;
GROW;
if (RAW == '(') {
int inputid = ctxt->input->id;
/* Recurse on second child */
NEXT;
SKIP_BLANKS;
last = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
depth + 1);
SKIP_BLANKS;
} else {
elem = xmlParseName(ctxt);
if (elem == NULL) {
xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
if (last == NULL) {
if (ret != NULL)
xmlFreeDocElementContent(ctxt->myDoc, ret);
return(NULL);
}
if (RAW == '?') {
last->ocur = XML_ELEMENT_CONTENT_OPT;
NEXT;
} else if (RAW == '*') {
last->ocur = XML_ELEMENT_CONTENT_MULT;
NEXT;
} else if (RAW == '+') {
last->ocur = XML_ELEMENT_CONTENT_PLUS;
NEXT;
} else {
last->ocur = XML_ELEMENT_CONTENT_ONCE;
}
}
SKIP_BLANKS;
GROW;
}
if ((cur != NULL) && (last != NULL)) {
cur->c2 = last;
if (last != NULL)
last->parent = cur;
}
if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
if (RAW == '?') {
if (ret != NULL) {
if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_OPT;
}
NEXT;
} else if (RAW == '*') {
if (ret != NULL) {
ret->ocur = XML_ELEMENT_CONTENT_MULT;
cur = ret;
/*
* Some normalization:
* (a | b* | c?)* == (a | b | c)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT)))
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
cur = cur->c2;
}
}
NEXT;
} else if (RAW == '+') {
if (ret != NULL) {
int found = 0;
if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) ||
(ret->ocur == XML_ELEMENT_CONTENT_MULT))
ret->ocur = XML_ELEMENT_CONTENT_MULT;
else
ret->ocur = XML_ELEMENT_CONTENT_PLUS;
/*
* Some normalization:
* (a | b*)+ == (a | b)*
* (a | b?)+ == (a | b)*
*/
while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
if ((cur->c1 != NULL) &&
((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
if ((cur->c2 != NULL) &&
((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
(cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) {
cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
found = 1;
}
cur = cur->c2;
}
if (found)
ret->ocur = XML_ELEMENT_CONTENT_MULT;
}
NEXT;
}
return(ret);
}
| 171,284 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
PNG_CONST png_modifier *pm)
{
pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
pm->current_gamma);
if (pm->encoding_ignored)
pos = safecat(buffer, bufsize, pos, "[overridden]");
return pos;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
const png_modifier *pm)
{
pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
pm->current_gamma);
if (pm->encoding_ignored)
pos = safecat(buffer, bufsize, pos, "[overridden]");
return pos;
}
| 173,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void coroutine_fn v9fs_write(void *opaque)
{
ssize_t err;
int32_t fid;
uint64_t off;
uint32_t count;
int32_t len = 0;
int32_t total = 0;
size_t offset = 7;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
QEMUIOVector qiov_full;
QEMUIOVector qiov;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);
if (err < 0) {
pdu_complete(pdu, err);
return;
}
offset += err;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);
trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_FILE) {
if (fidp->fs.fd == -1) {
err = -EINVAL;
goto out;
}
} else if (fidp->fid_type == P9_FID_XATTR) {
/*
* setxattr operation
*/
err = v9fs_xattr_write(s, pdu, fidp, off, count,
qiov_full.iov, qiov_full.niov);
goto out;
} else {
err = -EINVAL;
goto out;
}
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
total += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out_qiov;
}
} while (total < count && len > 0);
offset = 7;
err = pdu_marshal(pdu, offset, "d", total);
if (err < 0) {
goto out;
}
err += offset;
trace_v9fs_write_return(pdu->tag, pdu->id, total, err);
out_qiov:
qemu_iovec_destroy(&qiov);
out:
put_fid(pdu, fidp);
out_nofid:
qemu_iovec_destroy(&qiov_full);
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399 | static void coroutine_fn v9fs_write(void *opaque)
{
ssize_t err;
int32_t fid;
uint64_t off;
uint32_t count;
int32_t len = 0;
int32_t total = 0;
size_t offset = 7;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
QEMUIOVector qiov_full;
QEMUIOVector qiov;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);
if (err < 0) {
pdu_complete(pdu, err);
return;
}
offset += err;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);
trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_FILE) {
if (fidp->fs.fd == -1) {
err = -EINVAL;
goto out;
}
} else if (fidp->fid_type == P9_FID_XATTR) {
/*
* setxattr operation
*/
err = v9fs_xattr_write(s, pdu, fidp, off, count,
qiov_full.iov, qiov_full.niov);
goto out;
} else {
err = -EINVAL;
goto out;
}
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
total += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out_qiov;
}
} while (total < count && len > 0);
offset = 7;
err = pdu_marshal(pdu, offset, "d", total);
if (err < 0) {
goto out_qiov;
}
err += offset;
trace_v9fs_write_return(pdu->tag, pdu->id, total, err);
out_qiov:
qemu_iovec_destroy(&qiov);
out:
put_fid(pdu, fidp);
out_nofid:
qemu_iovec_destroy(&qiov_full);
pdu_complete(pdu, err);
}
| 164,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int opmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st64 offset = 0;
int mod = 0;
int base = 0;
int rex = 0;
ut64 immediate = 0;
if (op->operands[1].type & OT_CONSTANT) {
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[1].immediate == -1) {
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) {
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) {
data[l++] = 0x49;
} else {
data[l++] = 0x48;
}
} else if (op->operands[0].extended) {
data[l++] = 0x41;
}
if (op->operands[0].type & OT_WORD) {
if (a->bits > 16) {
data[l++] = 0x66;
}
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xb0 | op->operands[0].reg;
data[l++] = immediate;
} else {
if (a->bits == 64 &&
((op->operands[0].type & OT_QWORD) |
(op->operands[1].type & OT_QWORD)) &&
immediate < UT32_MAX) {
data[l++] = 0xc7;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
data[l++] = 0xb8 | op->operands[0].reg;
}
data[l++] = immediate;
data[l++] = immediate >> 8;
if (!(op->operands[0].type & OT_WORD)) {
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[0].type & OT_MEMORY) {
if (!op->operands[0].explicit_size) {
if (op->operands[0].type & OT_GPREG) {
((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size;
} else {
return -1;
}
}
int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT);
int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT);
int offset = op->operands[0].offset * op->operands[0].offset_sign;
bool use_aso = false;
if (reg_bits < a->bits) {
use_aso = true;
}
bool use_oso = false;
if (dest_bits == 16) {
use_oso = true;
}
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int rex = 1 << 6;
bool use_rex = false;
if (dest_bits == 64) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
int opcode;
if (dest_bits == 8) {
opcode = 0xc6;
} else {
opcode = 0xc7;
}
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (reg_bits == 16) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
if (rm == 5 && mod == 0) {
mod = 1;
}
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
if (use_aso) {
data[l++] = 0x67;
}
if (use_oso) {
data[l++] = 0x66;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
if (mod == 1) {
data[l++] = offset;
} else if (reg_bits == 16 && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
int byte;
for (byte = 0; byte < dest_bits && byte < 32; byte += 8) {
data[l++] = (immediate >> byte);
}
}
} else if (op->operands[1].type & OT_REGALL &&
!(op->operands[1].type & OT_MEMORY)) {
if (op->operands[0].type & OT_CONSTANT) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG &&
op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) {
if (!((op->operands[0].type & ALL_SIZE) &
(op->operands[1].type & ALL_SIZE))) {
return -1;
}
}
if (a->bits == 64) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
if (op->operands[1].type & OT_QWORD) {
if (!(op->operands[0].type & OT_QWORD)) {
data[l++] = 0x67;
data[l++] = 0x48;
}
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48 | rex;
}
if (op->operands[1].type & OT_DWORD &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0x40 | rex;
}
} else if (op->operands[0].extended && op->operands[1].extended) {
data[l++] = 0x45;
}
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
data[l++] = 0x8c;
} else {
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
}
data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89;
}
if (op->operands[0].scale[0] > 1) {
data[l++] = op->operands[1].reg << 3 | 4;
data[l++] = getsib (op->operands[0].scale[0]) << 6 |
op->operands[0].regs[0] << 3 | 5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].reg == X86R_UNDEFINED ||
op->operands[1].reg == X86R_UNDEFINED) {
return -1;
}
mod = 0x3;
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg;
} else if (op->operands[0].regs[0] == X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x4;
data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0];
return l;
}
if (offset) {
mod = (offset > 128 || offset < -129) ? 0x2 : 0x1;
}
if (op->operands[0].regs[0] == X86R_EBP) {
mod = 0x2;
}
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset) {
data[l++] = offset;
}
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
} else if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = 0x48;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xa0;
} else {
data[l++] = 0xa1;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
if (a->bits == 64) {
data[l++] = offset >> 32;
data[l++] = offset >> 40;
data[l++] = offset >> 48;
data[l++] = offset >> 54;
}
return l;
}
if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) {
if (op->operands[1].regs[0] >= X86R_R8 &&
op->operands[0].reg < 4) {
data[l++] = 0x41;
data[l++] = 0x8a;
data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8);
return l;
}
return -1;
}
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
if (op->operands[1].scale[0] == 0) {
return -1;
}
data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0]];
data[l++] = 0x8b;
data[l++] = op->operands[0].reg << 3 | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD) {
if (!(op->operands[1].type & OT_QWORD)) {
if (op->operands[1].regs[0] != -1) {
data[l++] = 0x67;
}
data[l++] = 0x48;
}
} else if (op->operands[1].type & OT_DWORD) {
data[l++] = 0x44;
} else if (!(op->operands[1].type & OT_QWORD)) {
data[l++] = 0x67;
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
}
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b;
} else {
data[l++] = (op->operands[1].type & OT_BYTE ||
op->operands[0].type & OT_BYTE) ?
0x8a : 0x8b;
}
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = 0x25;
} else {
data[l++] = op->operands[0].reg << 3 | 0x5;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[1].scale[0] > 1) {
data[l++] = op->operands[0].reg << 3 | 4;
if (op->operands[1].scale[0] >= 2) {
base = 5;
}
if (base) {
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base;
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0];
}
if (offset || base) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
if (offset || op->operands[1].regs[0] == X86R_EBP) {
mod = 0x2;
if (op->operands[1].offset > 127) {
mod = 0x4;
}
}
if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) {
if (op->operands[1].regs[0] == X86R_RIP) {
data[l++] = 0x5;
} else {
if (op->operands[1].offset > 127) {
data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0x40 | op->operands[1].regs[0];
}
}
if (op->operands[1].offset > 127) {
mod = 0x1;
}
} else {
if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) {
data[l++] = 0x0d;
} else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) {
data[l++] = 0x05;
} else {
data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod >= 0x2) {
data[l++] = offset;
if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) {
data[l++] = offset;
if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
}
return l;
}
Commit Message: Fix #12242 - Crash in x86.nz assembler (#12266)
CWE ID: CWE-125 | static int opmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st64 offset = 0;
int mod = 0;
int base = 0;
int rex = 0;
ut64 immediate = 0;
if (op->operands[1].type & OT_CONSTANT) {
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[1].immediate == -1) {
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) {
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) {
data[l++] = 0x49;
} else {
data[l++] = 0x48;
}
} else if (op->operands[0].extended) {
data[l++] = 0x41;
}
if (op->operands[0].type & OT_WORD) {
if (a->bits > 16) {
data[l++] = 0x66;
}
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xb0 | op->operands[0].reg;
data[l++] = immediate;
} else {
if (a->bits == 64 &&
((op->operands[0].type & OT_QWORD) |
(op->operands[1].type & OT_QWORD)) &&
immediate < UT32_MAX) {
data[l++] = 0xc7;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
data[l++] = 0xb8 | op->operands[0].reg;
}
data[l++] = immediate;
data[l++] = immediate >> 8;
if (!(op->operands[0].type & OT_WORD)) {
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[0].type & OT_MEMORY) {
if (!op->operands[0].explicit_size) {
if (op->operands[0].type & OT_GPREG) {
((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size;
} else {
return -1;
}
}
int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT);
int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT);
int offset = op->operands[0].offset * op->operands[0].offset_sign;
bool use_aso = false;
if (reg_bits < a->bits) {
use_aso = true;
}
bool use_oso = false;
if (dest_bits == 16) {
use_oso = true;
}
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int rex = 1 << 6;
bool use_rex = false;
if (dest_bits == 64) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
int opcode;
if (dest_bits == 8) {
opcode = 0xc6;
} else {
opcode = 0xc7;
}
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (reg_bits == 16) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
if (rm == 5 && mod == 0) {
mod = 1;
}
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
if (use_aso) {
data[l++] = 0x67;
}
if (use_oso) {
data[l++] = 0x66;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
if (mod == 1) {
data[l++] = offset;
} else if (reg_bits == 16 && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
int byte;
for (byte = 0; byte < dest_bits && byte < 32; byte += 8) {
data[l++] = (immediate >> byte);
}
}
} else if (op->operands[1].type & OT_REGALL &&
!(op->operands[1].type & OT_MEMORY)) {
if (op->operands[0].type & OT_CONSTANT) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG &&
op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) {
if (!((op->operands[0].type & ALL_SIZE) &
(op->operands[1].type & ALL_SIZE))) {
return -1;
}
}
if (a->bits == 64) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
if (op->operands[1].type & OT_QWORD) {
if (!(op->operands[0].type & OT_QWORD)) {
data[l++] = 0x67;
data[l++] = 0x48;
}
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48 | rex;
}
if (op->operands[1].type & OT_DWORD &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0x40 | rex;
}
} else if (op->operands[0].extended && op->operands[1].extended) {
data[l++] = 0x45;
}
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
data[l++] = 0x8c;
} else {
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
}
data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89;
}
if (op->operands[0].scale[0] > 1) {
data[l++] = op->operands[1].reg << 3 | 4;
data[l++] = getsib (op->operands[0].scale[0]) << 6 |
op->operands[0].regs[0] << 3 | 5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].reg == X86R_UNDEFINED ||
op->operands[1].reg == X86R_UNDEFINED) {
return -1;
}
mod = 0x3;
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg;
} else if (op->operands[0].regs[0] == X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x4;
data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0];
return l;
}
if (offset) {
mod = (offset > 128 || offset < -129) ? 0x2 : 0x1;
}
if (op->operands[0].regs[0] == X86R_EBP) {
mod = 0x2;
}
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset) {
data[l++] = offset;
}
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
} else if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = 0x48;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xa0;
} else {
data[l++] = 0xa1;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
if (a->bits == 64) {
data[l++] = offset >> 32;
data[l++] = offset >> 40;
data[l++] = offset >> 48;
data[l++] = offset >> 54;
}
return l;
}
if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) {
if (op->operands[1].regs[0] >= X86R_R8 &&
op->operands[0].reg < 4) {
data[l++] = 0x41;
data[l++] = 0x8a;
data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8);
return l;
}
return -1;
}
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
if (op->operands[1].scale[0] == 0) {
return -1;
}
data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0] % 6];
data[l++] = 0x8b;
data[l++] = (((ut32)op->operands[0].reg) << 3) | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD) {
if (!(op->operands[1].type & OT_QWORD)) {
if (op->operands[1].regs[0] != -1) {
data[l++] = 0x67;
}
data[l++] = 0x48;
}
} else if (op->operands[1].type & OT_DWORD) {
data[l++] = 0x44;
} else if (!(op->operands[1].type & OT_QWORD)) {
data[l++] = 0x67;
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
}
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b;
} else {
data[l++] = (op->operands[1].type & OT_BYTE ||
op->operands[0].type & OT_BYTE) ?
0x8a : 0x8b;
}
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = 0x25;
} else {
data[l++] = op->operands[0].reg << 3 | 0x5;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[1].scale[0] > 1) {
data[l++] = op->operands[0].reg << 3 | 4;
if (op->operands[1].scale[0] >= 2) {
base = 5;
}
if (base) {
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base;
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0];
}
if (offset || base) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
if (offset || op->operands[1].regs[0] == X86R_EBP) {
mod = 0x2;
if (op->operands[1].offset > 127) {
mod = 0x4;
}
}
if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) {
if (op->operands[1].regs[0] == X86R_RIP) {
data[l++] = 0x5;
} else {
if (op->operands[1].offset > 127) {
data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0x40 | op->operands[1].regs[0];
}
}
if (op->operands[1].offset > 127) {
mod = 0x1;
}
} else {
if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) {
data[l++] = 0x0d;
} else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) {
data[l++] = 0x05;
} else {
data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod >= 0x2) {
data[l++] = offset;
if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) {
data[l++] = offset;
if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
}
return l;
}
| 168,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContextualSearchParams()
: version(-1),
start(base::string16::npos),
end(base::string16::npos),
now_on_tap_version(0) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | ContextualSearchParams()
: version(-1),
start(base::string16::npos),
end(base::string16::npos),
| 171,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PrintPreviewUI::~PrintPreviewUI() {
print_preview_data_service()->RemoveEntry(preview_ui_addr_str_);
g_print_preview_request_id_map.Get().Erase(preview_ui_addr_str_);
}
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 | PrintPreviewUI::~PrintPreviewUI() {
print_preview_data_service()->RemoveEntry(id_);
g_print_preview_request_id_map.Get().Erase(id_);
g_print_preview_ui_id_map.Get().Remove(id_);
}
| 170,844 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CueTimeline::UpdateActiveCues(double movie_time) {
if (IgnoreUpdateRequests())
return;
HTMLMediaElement& media_element = MediaElement();
if (media_element.GetDocument().IsDetached())
return;
CueList current_cues;
if (media_element.getReadyState() != HTMLMediaElement::kHaveNothing &&
media_element.GetWebMediaPlayer())
current_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(movie_time, movie_time));
CueList previous_cues;
CueList missed_cues;
previous_cues = currently_active_cues_;
double last_time = last_update_time_;
double last_seek_time = media_element.LastSeekTime();
if (last_time >= 0 && last_seek_time < movie_time) {
CueList potentially_skipped_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(last_time, movie_time));
for (CueInterval cue : potentially_skipped_cues) {
if (cue.Low() > std::max(last_seek_time, last_time) &&
cue.High() < movie_time)
missed_cues.push_back(cue);
}
}
last_update_time_ = movie_time;
if (!media_element.seeking() && last_seek_time < last_time)
media_element.ScheduleTimeupdateEvent(true);
size_t missed_cues_size = missed_cues.size();
size_t previous_cues_size = previous_cues.size();
bool active_set_changed = missed_cues_size;
for (size_t i = 0; !active_set_changed && i < previous_cues_size; ++i) {
if (!current_cues.Contains(previous_cues[i]) &&
previous_cues[i].Data()->IsActive())
active_set_changed = true;
}
for (CueInterval current_cue : current_cues) {
if (current_cue.Data()->IsActive())
current_cue.Data()->UpdatePastAndFutureNodes(movie_time);
else
active_set_changed = true;
}
if (!active_set_changed)
return;
for (size_t i = 0; !media_element.paused() && i < previous_cues_size; ++i) {
if (previous_cues[i].Data()->pauseOnExit() &&
previous_cues[i].Data()->IsActive() &&
!current_cues.Contains(previous_cues[i]))
media_element.pause();
}
for (size_t i = 0; !media_element.paused() && i < missed_cues_size; ++i) {
if (missed_cues[i].Data()->pauseOnExit())
media_element.pause();
}
HeapVector<std::pair<double, Member<TextTrackCue>>> event_tasks;
HeapVector<Member<TextTrack>> affected_tracks;
for (const auto& missed_cue : missed_cues) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->startTime(), missed_cue.Data()));
if (missed_cue.Data()->startTime() < missed_cue.Data()->endTime()) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->endTime(), missed_cue.Data()));
}
}
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
event_tasks.push_back(
std::make_pair(previous_cue.Data()->endTime(), previous_cue.Data()));
}
}
for (const auto& current_cue : current_cues) {
if (!previous_cues.Contains(current_cue)) {
event_tasks.push_back(
std::make_pair(current_cue.Data()->startTime(), current_cue.Data()));
}
}
NonCopyingSort(event_tasks.begin(), event_tasks.end(), EventTimeCueCompare);
for (const auto& task : event_tasks) {
if (!affected_tracks.Contains(task.second->track()))
affected_tracks.push_back(task.second->track());
if (task.second->startTime() >= task.second->endTime()) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::enter, task.second.Get()));
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::exit, task.second.Get()));
} else {
bool is_enter_event = task.first == task.second->startTime();
AtomicString event_name =
is_enter_event ? EventTypeNames::enter : EventTypeNames::exit;
media_element.ScheduleEvent(
CreateEventWithTarget(event_name, task.second.Get()));
}
}
NonCopyingSort(affected_tracks.begin(), affected_tracks.end(),
TrackIndexCompare);
for (const auto& track : affected_tracks) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track.Get()));
if (track->TrackType() == TextTrack::kTrackElement) {
HTMLTrackElement* track_element =
ToLoadableTextTrack(track.Get())->TrackElement();
DCHECK(track_element);
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track_element));
}
}
for (const auto& cue : current_cues)
cue.Data()->SetIsActive(true);
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
TextTrackCue* cue = previous_cue.Data();
cue->SetIsActive(false);
cue->RemoveDisplayTree();
}
}
currently_active_cues_ = current_cues;
media_element.UpdateTextTrackDisplay();
}
Commit Message: Support negative timestamps of TextTrackCue
Ensure proper behaviour for negative timestamps of TextTrackCue.
1. Cues with negative startTime should become active from 0s.
2. Cues with negative startTime and endTime should never be active.
Bug: 314032
Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d
Reviewed-on: https://chromium-review.googlesource.com/863270
Commit-Queue: srirama chandra sekhar <[email protected]>
Reviewed-by: Fredrik Söderquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529012}
CWE ID: | void CueTimeline::UpdateActiveCues(double movie_time) {
if (IgnoreUpdateRequests())
return;
HTMLMediaElement& media_element = MediaElement();
if (media_element.GetDocument().IsDetached())
return;
CueList current_cues;
if (media_element.getReadyState() != HTMLMediaElement::kHaveNothing &&
media_element.GetWebMediaPlayer()) {
current_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(movie_time, movie_time));
}
CueList previous_cues;
CueList missed_cues;
previous_cues = currently_active_cues_;
double last_time = last_update_time_;
double last_seek_time = media_element.LastSeekTime();
if (last_time >= 0 && last_seek_time < movie_time) {
CueList potentially_skipped_cues =
cue_tree_.AllOverlaps(cue_tree_.CreateInterval(last_time, movie_time));
for (CueInterval cue : potentially_skipped_cues) {
if (cue.Low() > std::max(last_seek_time, last_time) &&
cue.High() < movie_time)
missed_cues.push_back(cue);
}
}
last_update_time_ = movie_time;
if (!media_element.seeking() && last_seek_time < last_time)
media_element.ScheduleTimeupdateEvent(true);
size_t missed_cues_size = missed_cues.size();
size_t previous_cues_size = previous_cues.size();
bool active_set_changed = missed_cues_size;
for (size_t i = 0; !active_set_changed && i < previous_cues_size; ++i) {
if (!current_cues.Contains(previous_cues[i]) &&
previous_cues[i].Data()->IsActive())
active_set_changed = true;
}
for (CueInterval current_cue : current_cues) {
if (current_cue.Data()->IsActive())
current_cue.Data()->UpdatePastAndFutureNodes(movie_time);
else
active_set_changed = true;
}
if (!active_set_changed)
return;
for (size_t i = 0; !media_element.paused() && i < previous_cues_size; ++i) {
if (previous_cues[i].Data()->pauseOnExit() &&
previous_cues[i].Data()->IsActive() &&
!current_cues.Contains(previous_cues[i]))
media_element.pause();
}
for (size_t i = 0; !media_element.paused() && i < missed_cues_size; ++i) {
if (missed_cues[i].Data()->pauseOnExit())
media_element.pause();
}
HeapVector<std::pair<double, Member<TextTrackCue>>> event_tasks;
HeapVector<Member<TextTrack>> affected_tracks;
for (const auto& missed_cue : missed_cues) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->startTime(), missed_cue.Data()));
if (missed_cue.Data()->startTime() < missed_cue.Data()->endTime()) {
event_tasks.push_back(
std::make_pair(missed_cue.Data()->endTime(), missed_cue.Data()));
}
}
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
event_tasks.push_back(
std::make_pair(previous_cue.Data()->endTime(), previous_cue.Data()));
}
}
for (const auto& current_cue : current_cues) {
if (!previous_cues.Contains(current_cue)) {
event_tasks.push_back(
std::make_pair(current_cue.Data()->startTime(), current_cue.Data()));
}
}
NonCopyingSort(event_tasks.begin(), event_tasks.end(), EventTimeCueCompare);
for (const auto& task : event_tasks) {
if (!affected_tracks.Contains(task.second->track()))
affected_tracks.push_back(task.second->track());
if (task.second->startTime() >= task.second->endTime()) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::enter, task.second.Get()));
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::exit, task.second.Get()));
} else {
bool is_enter_event = task.first == task.second->startTime();
AtomicString event_name =
is_enter_event ? EventTypeNames::enter : EventTypeNames::exit;
media_element.ScheduleEvent(
CreateEventWithTarget(event_name, task.second.Get()));
}
}
NonCopyingSort(affected_tracks.begin(), affected_tracks.end(),
TrackIndexCompare);
for (const auto& track : affected_tracks) {
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track.Get()));
if (track->TrackType() == TextTrack::kTrackElement) {
HTMLTrackElement* track_element =
ToLoadableTextTrack(track.Get())->TrackElement();
DCHECK(track_element);
media_element.ScheduleEvent(
CreateEventWithTarget(EventTypeNames::cuechange, track_element));
}
}
for (const auto& cue : current_cues)
cue.Data()->SetIsActive(true);
for (const auto& previous_cue : previous_cues) {
if (!current_cues.Contains(previous_cue)) {
TextTrackCue* cue = previous_cue.Data();
cue->SetIsActive(false);
cue->RemoveDisplayTree();
}
}
currently_active_cues_ = current_cues;
media_element.UpdateTextTrackDisplay();
}
| 171,767 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url,
const FilePath& virtual_path,
const FilePath& platform_path) {
FilePath::StringType extension = virtual_path.Extension();
if (!extension.empty())
extension = extension.substr(1); // Strip leading ".".
scoped_refptr<webkit_blob::ShareableFileReference> shareable_file =
webkit_blob::ShareableFileReference::Get(platform_path);
if (shareable_file &&
!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
process_id_, platform_path)) {
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
process_id_, platform_path);
shareable_file->AddFinalReleaseCallback(
base::Bind(&RevokeFilePermission, process_id_));
}
std::string mime_type;
net::GetWellKnownMimeTypeFromExtension(extension, &mime_type);
BlobData::Item item;
item.SetToFilePathRange(platform_path, 0, -1, base::Time());
BlobStorageController* controller = blob_storage_context_->controller();
controller->StartBuildingBlob(blob_url);
controller->AppendBlobDataItem(blob_url, item);
controller->FinishBuildingBlob(blob_url, mime_type);
blob_urls_.insert(blob_url.spec());
}
Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files
We also need to check the read permission and call GrantReadFile() for
sandboxed files for CreateSnapshotFile().
BUG=162114
TEST=manual
Review URL: https://codereview.chromium.org/11280231
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url,
const FileSystemURL& url,
const FilePath& platform_path) {
FilePath::StringType extension = url.path().Extension();
if (!extension.empty())
extension = extension.substr(1); // Strip leading ".".
scoped_refptr<webkit_blob::ShareableFileReference> shareable_file =
webkit_blob::ShareableFileReference::Get(platform_path);
if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
process_id_, platform_path)) {
// If the underlying file system implementation is returning a new
// (likely temporary) snapshot file or the file is for sandboxed
// filesystems it's ok to grant permission here.
// (Note that we have also already checked if the renderer has the
// read permission for this file in OnCreateSnapshotFile.)
DCHECK(shareable_file ||
fileapi::SandboxMountPointProvider::CanHandleType(url.type()));
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
process_id_, platform_path);
if (shareable_file) {
// This will revoke all permissions for the file when the last ref
// of the file is dropped (assuming it's ok).
shareable_file->AddFinalReleaseCallback(
base::Bind(&RevokeFilePermission, process_id_));
}
}
std::string mime_type;
net::GetWellKnownMimeTypeFromExtension(extension, &mime_type);
BlobData::Item item;
item.SetToFilePathRange(platform_path, 0, -1, base::Time());
BlobStorageController* controller = blob_storage_context_->controller();
controller->StartBuildingBlob(blob_url);
controller->AppendBlobDataItem(blob_url, item);
controller->FinishBuildingBlob(blob_url, mime_type);
blob_urls_.insert(blob_url.spec());
}
| 171,587 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId) + drdynvc_cblen_to_bytes(Sp))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
| 168,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserChildProcessHostImpl::ShareMetricsAllocatorToProcess() {
if (metrics_allocator_) {
HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>(
GetHost(),
mojo::WrapSharedMemoryHandle(
metrics_allocator_->shared_memory()->handle().Duplicate(),
metrics_allocator_->shared_memory()->mapped_size(), false));
} else {
HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>(
GetHost(), mojo::ScopedSharedBufferHandle());
}
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | void BrowserChildProcessHostImpl::ShareMetricsAllocatorToProcess() {
if (metrics_allocator_) {
HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>(
GetHost(),
mojo::WrapSharedMemoryHandle(
metrics_allocator_->shared_memory()->handle().Duplicate(),
metrics_allocator_->shared_memory()->mapped_size(),
mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite));
} else {
HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>(
GetHost(), mojo::ScopedSharedBufferHandle());
}
}
| 172,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: vrrp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len,
register const u_char *bp2, int ttl)
{
int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */
const char *type_s;
ND_TCHECK(bp[0]);
version = (bp[0] & 0xf0) >> 4;
type = bp[0] & 0x0f;
type_s = tok2str(type2str, "unknown type (%u)", type);
ND_PRINT((ndo, "VRRPv%u, %s", version, type_s));
if (ttl != 255)
ND_PRINT((ndo, ", (ttl %u)", ttl));
if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)
return;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2]));
ND_TCHECK(bp[5]);
if (version == 2) {
auth_type = bp[4];
ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type)));
ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len));
} else { /* version == 3 */
uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];
ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len));
}
if (ndo->ndo_vflag) {
int naddrs = bp[3];
int i;
char c;
if (version == 2 && ND_TTEST2(bp[0], len)) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
if (in_cksum(vec, 1))
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
if (version == 3 && ND_TTEST2(bp[0], len)) {
uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,
len, len, IPPROTO_VRRP);
if (cksum)
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
ND_PRINT((ndo, ", addrs"));
if (naddrs > 1)
ND_PRINT((ndo, "(%d)", naddrs));
ND_PRINT((ndo, ":"));
c = ' ';
bp += 8;
for (i = 0; i < naddrs; i++) {
ND_TCHECK(bp[3]);
ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp)));
c = ',';
bp += 4;
}
if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */
ND_TCHECK(bp[7]);
ND_PRINT((ndo, " auth \""));
if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
}
}
return;
trunc:
ND_PRINT((ndo, "[|vrrp]"));
}
Commit Message: (for 4.9.3) CVE-2018-14463/VRRP: Add a missing bounds check
In vrrp_print().
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | vrrp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len,
register const u_char *bp2, int ttl)
{
int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */
const char *type_s;
ND_TCHECK(bp[0]);
version = (bp[0] & 0xf0) >> 4;
type = bp[0] & 0x0f;
type_s = tok2str(type2str, "unknown type (%u)", type);
ND_PRINT((ndo, "VRRPv%u, %s", version, type_s));
if (ttl != 255)
ND_PRINT((ndo, ", (ttl %u)", ttl));
if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)
return;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2]));
ND_TCHECK(bp[5]);
if (version == 2) {
auth_type = bp[4];
ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type)));
ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len));
} else { /* version == 3 */
uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];
ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len));
}
if (ndo->ndo_vflag) {
int naddrs = bp[3];
int i;
char c;
if (version == 2 && ND_TTEST2(bp[0], len)) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
if (in_cksum(vec, 1)) {
ND_TCHECK_16BITS(&bp[6]);
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
}
if (version == 3 && ND_TTEST2(bp[0], len)) {
uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,
len, len, IPPROTO_VRRP);
if (cksum)
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
ND_PRINT((ndo, ", addrs"));
if (naddrs > 1)
ND_PRINT((ndo, "(%d)", naddrs));
ND_PRINT((ndo, ":"));
c = ' ';
bp += 8;
for (i = 0; i < naddrs; i++) {
ND_TCHECK(bp[3]);
ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp)));
c = ',';
bp += 4;
}
if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */
ND_TCHECK(bp[7]);
ND_PRINT((ndo, " auth \""));
if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
}
}
return;
trunc:
ND_PRINT((ndo, "[|vrrp]"));
}
| 169,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
Commit Message:
CWE ID: | static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 164,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
ext2_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
if (sbi->s_mb_cache) {
ext2_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
| 169,974 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftVorbis::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.vorbis",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioVorbis:
{
const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(const OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftVorbis::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.vorbis",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioVorbis:
{
const OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams =
(const OMX_AUDIO_PARAM_VORBISTYPE *)params;
if (!isValidOMXParam(vorbisParams)) {
return OMX_ErrorBadParameter;
}
if (vorbisParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int gs_lib_ctx_init( gs_memory_t *mem )
{
gs_lib_ctx_t *pio = 0;
/* Check the non gc allocator is being passed in */
if (mem == 0 || mem != mem->non_gc_memory)
return_error(gs_error_Fatal);
#ifndef GS_THREADSAFE
mem_err_print = mem;
#endif
if (mem->gs_lib_ctx) /* one time initialization */
return 0;
pio = (gs_lib_ctx_t*)gs_alloc_bytes_immovable(mem,
sizeof(gs_lib_ctx_t),
"gs_lib_ctx_init");
if( pio == 0 )
return -1;
/* Wholesale blanking is cheaper than retail, and scales better when new
* fields are added. */
memset(pio, 0, sizeof(*pio));
/* Now set the non zero/false/NULL things */
pio->memory = mem;
gs_lib_ctx_get_real_stdio(&pio->fstdin, &pio->fstdout, &pio->fstderr );
pio->stdin_is_interactive = true;
/* id's 1 through 4 are reserved for Device color spaces; see gscspace.h */
pio->gs_next_id = 5; /* this implies that each thread has its own complete state */
/* Need to set this before calling gs_lib_ctx_set_icc_directory. */
mem->gs_lib_ctx = pio;
/* Initialize our default ICCProfilesDir */
pio->profiledir = NULL;
pio->profiledir_len = 0;
gs_lib_ctx_set_icc_directory(mem, DEFAULT_DIR_ICC, strlen(DEFAULT_DIR_ICC));
if (gs_lib_ctx_set_default_device_list(mem, gs_dev_defaults,
strlen(gs_dev_defaults)) < 0) {
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
}
/* Initialise the underlying CMS. */
if (gscms_create(mem)) {
Failure:
gs_free_object(mem, mem->gs_lib_ctx->default_device_list,
"gs_lib_ctx_fin");
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
return -1;
}
/* Initialise any lock required for the jpx codec */
if (sjpxd_create(mem)) {
gscms_destroy(mem);
goto Failure;
}
gp_get_realtime(pio->real_time_0);
/* Set scanconverter to 1 (default) */
pio->scanconverter = GS_SCANCONVERTER_DEFAULT;
return 0;
}
Commit Message:
CWE ID: CWE-20 | int gs_lib_ctx_init( gs_memory_t *mem )
{
gs_lib_ctx_t *pio = 0;
/* Check the non gc allocator is being passed in */
if (mem == 0 || mem != mem->non_gc_memory)
return_error(gs_error_Fatal);
#ifndef GS_THREADSAFE
mem_err_print = mem;
#endif
if (mem->gs_lib_ctx) /* one time initialization */
return 0;
pio = (gs_lib_ctx_t*)gs_alloc_bytes_immovable(mem,
sizeof(gs_lib_ctx_t),
"gs_lib_ctx_init");
if( pio == 0 )
return -1;
/* Wholesale blanking is cheaper than retail, and scales better when new
* fields are added. */
memset(pio, 0, sizeof(*pio));
/* Now set the non zero/false/NULL things */
pio->memory = mem;
gs_lib_ctx_get_real_stdio(&pio->fstdin, &pio->fstdout, &pio->fstderr );
pio->stdin_is_interactive = true;
/* id's 1 through 4 are reserved for Device color spaces; see gscspace.h */
pio->gs_next_id = 5; /* this implies that each thread has its own complete state */
/* Need to set this before calling gs_lib_ctx_set_icc_directory. */
mem->gs_lib_ctx = pio;
/* Initialize our default ICCProfilesDir */
pio->profiledir = NULL;
pio->profiledir_len = 0;
gs_lib_ctx_set_icc_directory(mem, DEFAULT_DIR_ICC, strlen(DEFAULT_DIR_ICC));
if (gs_lib_ctx_set_default_device_list(mem, gs_dev_defaults,
strlen(gs_dev_defaults)) < 0) {
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
}
/* Initialise the underlying CMS. */
if (gscms_create(mem)) {
Failure:
gs_free_object(mem, mem->gs_lib_ctx->default_device_list,
"gs_lib_ctx_fin");
gs_free_object(mem, pio, "gs_lib_ctx_init");
mem->gs_lib_ctx = NULL;
return -1;
}
/* Initialise any lock required for the jpx codec */
if (sjpxd_create(mem)) {
gscms_destroy(mem);
goto Failure;
}
pio->client_check_file_permission = NULL;
gp_get_realtime(pio->real_time_0);
/* Set scanconverter to 1 (default) */
pio->scanconverter = GS_SCANCONVERTER_DEFAULT;
return 0;
}
| 165,266 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FragmentPaintPropertyTreeBuilder::UpdatePerspective() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (NeedsPerspective(object_)) {
const ComputedStyle& style = object_.StyleRef();
TransformPaintPropertyNode::State state;
state.matrix.ApplyPerspective(style.Perspective());
state.origin = PerspectiveOrigin(ToLayoutBox(object_)) +
ToLayoutSize(context_.current.paint_offset);
state.flattens_inherited_transform =
context_.current.should_flatten_inherited_transform;
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
state.rendering_context_id = context_.current.rendering_context_id;
OnUpdate(properties_->UpdatePerspective(context_.current.transform,
std::move(state)));
} else {
OnClear(properties_->ClearPerspective());
}
}
if (properties_->Perspective()) {
context_.current.transform = properties_->Perspective();
context_.current.should_flatten_inherited_transform = false;
}
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void FragmentPaintPropertyTreeBuilder::UpdatePerspective() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (NeedsPerspective(object_)) {
const ComputedStyle& style = object_.StyleRef();
TransformPaintPropertyNode::State state;
state.matrix.ApplyPerspective(style.Perspective());
state.origin = PerspectiveOrigin(ToLayoutBox(object_)) +
ToLayoutSize(context_.current.paint_offset);
state.flattens_inherited_transform =
context_.current.should_flatten_inherited_transform;
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
state.rendering_context_id = context_.current.rendering_context_id;
OnUpdate(properties_->UpdatePerspective(*context_.current.transform,
std::move(state)));
} else {
OnClear(properties_->ClearPerspective());
}
}
if (properties_->Perspective()) {
context_.current.transform = properties_->Perspective();
context_.current.should_flatten_inherited_transform = false;
}
}
| 171,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Track::Info::Copy(Info& dst) const
{
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0)
{
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | int Track::Info::Copy(Info& dst) const
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
// We now copy the string member variables from src to dst.
// This involves memory allocation so in principle the operation
// can fail (indeed, that's why we have Info::Copy), so we must
// report this to the caller. An error return from this function
// therefore implies that the copy was only partially successful.
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
const BlockEntry* Track::GetEOS() const { return &m_eos; }
long Track::GetType() const { return m_info.type; }
long Track::GetNumber() const { return m_info.number; }
unsigned long long Track::GetUid() const { return m_info.uid; }
const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; }
const char* Track::GetLanguage() const { return m_info.language; }
const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }
const char* Track::GetCodecId() const { return m_info.codecId; }
const unsigned char* Track::GetCodecPrivate(size_t& size) const {
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
bool Track::GetLacing() const { return m_info.lacing; }
unsigned long long Track::GetDefaultDuration() const {
return m_info.defaultDuration;
}
unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }
unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; }
long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0;;) {
if (pCluster == NULL) {
pBlockEntry = GetEOS();
return 1;
}
| 174,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct key *key_get_instantiation_authkey(key_serial_t target_id)
{
char description[16];
struct keyring_search_context ctx = {
.index_key.type = &key_type_request_key_auth,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = user_match,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
};
struct key *authkey;
key_ref_t authkey_ref;
sprintf(description, "%x", target_id);
authkey_ref = search_process_keyrings(&ctx);
if (IS_ERR(authkey_ref)) {
authkey = ERR_CAST(authkey_ref);
if (authkey == ERR_PTR(-EAGAIN))
authkey = ERR_PTR(-ENOKEY);
goto error;
}
authkey = key_ref_to_ptr(authkey_ref);
if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) {
key_put(authkey);
authkey = ERR_PTR(-EKEYREVOKED);
}
error:
return authkey;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476 | struct key *key_get_instantiation_authkey(key_serial_t target_id)
{
char description[16];
struct keyring_search_context ctx = {
.index_key.type = &key_type_request_key_auth,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
};
struct key *authkey;
key_ref_t authkey_ref;
sprintf(description, "%x", target_id);
authkey_ref = search_process_keyrings(&ctx);
if (IS_ERR(authkey_ref)) {
authkey = ERR_CAST(authkey_ref);
if (authkey == ERR_PTR(-EAGAIN))
authkey = ERR_PTR(-ENOKEY);
goto error;
}
authkey = key_ref_to_ptr(authkey_ref);
if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) {
key_put(authkey);
authkey = ERR_PTR(-EKEYREVOKED);
}
error:
return authkey;
}
| 168,442 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
}
| 167,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->abort) return FALSE;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
Commit Message:
CWE ID: CWE-20 | static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
| 165,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
const KURL& overriding_url) {
if (state_ != kProvisional)
return;
if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
SetHistoryItemStateForCommit(
GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_,
HistoryNavigationType::kDifferentDocument);
}
DCHECK_EQ(state_, kProvisional);
GetFrameLoader().CommitProvisionalLoad();
if (!frame_)
return;
const AtomicString& encoding = GetResponse().TextEncodingName();
Document* owner_document = nullptr;
if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
Frame* owner_frame = frame_->Tree().Parent();
if (!owner_frame)
owner_frame = frame_->Loader().Opener();
if (owner_frame && owner_frame->IsLocalFrame())
owner_document = ToLocalFrame(owner_frame)->GetDocument();
}
DCHECK(frame_->GetPage());
ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing;
if (!Document::ThreadedParsingEnabledForTesting())
parsing_policy = kForceSynchronousParsing;
InstallNewDocument(Url(), owner_document,
frame_->ShouldReuseDefaultView(Url())
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew,
mime_type, encoding, InstallNewDocumentReason::kNavigation,
parsing_policy, overriding_url);
parser_->SetDocumentWasLoadedAsPartOfNavigation();
if (request_.WasDiscarded())
frame_->GetDocument()->SetWasDiscarded(true);
frame_->GetDocument()->MaybeHandleHttpRefresh(
response_.HttpHeaderField(HTTPNames::Refresh),
Document::kHttpRefreshFromHeader);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285 | void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
const KURL& overriding_url) {
if (state_ != kProvisional)
return;
if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
SetHistoryItemStateForCommit(
GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_,
HistoryNavigationType::kDifferentDocument);
}
DCHECK_EQ(state_, kProvisional);
GetFrameLoader().CommitProvisionalLoad();
if (!frame_)
return;
const AtomicString& encoding = GetResponse().TextEncodingName();
Document* owner_document = nullptr;
if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
Frame* owner_frame = frame_->Tree().Parent();
if (!owner_frame)
owner_frame = frame_->Loader().Opener();
if (owner_frame && owner_frame->IsLocalFrame())
owner_document = ToLocalFrame(owner_frame)->GetDocument();
}
DCHECK(frame_->GetPage());
ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing;
if (!Document::ThreadedParsingEnabledForTesting())
parsing_policy = kForceSynchronousParsing;
InstallNewDocument(
Url(), owner_document,
frame_->ShouldReuseDefaultView(Url(), GetContentSecurityPolicy())
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew,
mime_type, encoding, InstallNewDocumentReason::kNavigation,
parsing_policy, overriding_url);
parser_->SetDocumentWasLoadedAsPartOfNavigation();
if (request_.WasDiscarded())
frame_->GetDocument()->SetWasDiscarded(true);
frame_->GetDocument()->MaybeHandleHttpRefresh(
response_.HttpHeaderField(HTTPNames::Refresh),
Document::kHttpRefreshFromHeader);
}
| 173,197 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() {
scoped_refptr<RenderFrameDevToolsAgentHost> protect(this);
if (IsAttached())
RevokePolicy();
ForceDetachAllClients();
frame_host_ = nullptr;
agent_ptr_.reset();
SetFrameTreeNode(nullptr);
Release();
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | void RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() {
scoped_refptr<RenderFrameDevToolsAgentHost> protect(this);
if (IsAttached())
RevokePolicy();
ForceDetachAllSessions();
frame_host_ = nullptr;
agent_ptr_.reset();
SetFrameTreeNode(nullptr);
Release();
}
| 173,249 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TouchEventHandler::doFatFingers(Platform::TouchPoint& point)
{
m_lastScreenPoint = point.m_screenPos;
m_lastFatFingersResult.reset(); // Theoretically this shouldn't be required. Keep it just in case states get mangled.
IntPoint contentPos(m_webPage->mapFromViewportToContents(point.m_pos));
m_webPage->postponeDocumentStyleRecalc();
m_lastFatFingersResult = FatFingers(m_webPage, contentPos, FatFingers::ClickableElement).findBestPoint();
m_webPage->resumeDocumentStyleRecalc();
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void TouchEventHandler::doFatFingers(Platform::TouchPoint& point)
void TouchEventHandler::doFatFingers(const Platform::TouchPoint& point)
{
m_lastScreenPoint = point.screenPosition();
m_lastFatFingersResult.reset(); // Theoretically this shouldn't be required. Keep it just in case states get mangled.
m_webPage->postponeDocumentStyleRecalc();
m_lastFatFingersResult = FatFingers(m_webPage, point.documentContentPosition(), FatFingers::ClickableElement).findBestPoint();
m_webPage->resumeDocumentStyleRecalc();
}
| 170,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
wpc->version_five = 1; // just having this block signals version 5.0
wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
if (bytecnt) {
wpc->file_format = *byteptr++;
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
bytecnt -= 2;
if (bytecnt) {
int nchans, i;
wpc->channel_layout = (int32_t) *byteptr++ << 16;
bytecnt--;
if (bytecnt) {
wpc->channel_layout += nchans = *byteptr++;
bytecnt--;
if (bytecnt) {
if (bytecnt > nchans)
return FALSE;
wpc->channel_reordering = malloc (nchans);
if (wpc->channel_reordering) {
for (i = 0; i < nchans; ++i)
if (bytecnt) {
wpc->channel_reordering [i] = *byteptr++;
bytecnt--;
}
else
wpc->channel_reordering [i] = i;
}
}
}
else
wpc->channel_layout += wpc->config.num_channels;
}
}
return TRUE;
}
Commit Message: fixes for 4 fuzz failures posted to SourceForge mailing list
CWE ID: CWE-125 | static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
wpc->version_five = 1; // just having this block signals version 5.0
wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
if (bytecnt >= 2) {
wpc->file_format = *byteptr++;
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
bytecnt -= 2;
if (bytecnt) {
int nchans, i;
wpc->channel_layout = (int32_t) *byteptr++ << 16;
bytecnt--;
if (bytecnt) {
wpc->channel_layout += nchans = *byteptr++;
bytecnt--;
if (bytecnt) {
if (bytecnt > nchans)
return FALSE;
wpc->channel_reordering = malloc (nchans);
if (wpc->channel_reordering) {
for (i = 0; i < nchans; ++i)
if (bytecnt) {
wpc->channel_reordering [i] = *byteptr++;
if (wpc->channel_reordering [i] >= nchans) // make sure index is in range
wpc->channel_reordering [i] = 0;
bytecnt--;
}
else
wpc->channel_reordering [i] = i;
}
}
}
else
wpc->channel_layout += wpc->config.num_channels;
}
}
return TRUE;
}
| 168,507 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %u port %u unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%u",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %u", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %u", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
if (ND_TTEST2(*bp, plen)) {
uint16_t sum;
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
uint16_t icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
ndo->ndo_snaplen = ndo->ndo_snapend - bp;
snapend_save = ndo->ndo_snapend;
ND_TCHECK_16BITS(&ip->ip_len);
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
Commit Message: (for 4.9.3) CVE-2018-14462/ICMP: Add a missing bounds check
In icmp_print().
This fixes a buffer over-read discovered by Bhargava Shastry.
Add two tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %u port %u unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%u",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %u", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %u", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
if (ND_TTEST2(*bp, plen)) {
uint16_t sum;
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
ND_TCHECK_16BITS(&dp->icmp_cksum);
uint16_t icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
ndo->ndo_snaplen = ndo->ndo_snapend - bp;
snapend_save = ndo->ndo_snapend;
ND_TCHECK_16BITS(&ip->ip_len);
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
| 169,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
nal_header_t *ps_nal)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i, j;
WORD32 sps_id;
pps_t *ps_pps;
sps_t *ps_sps;
slice_header_t *ps_slice_hdr;
WORD32 disable_deblocking_filter_flag;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 idr_pic_flag;
WORD32 pps_id;
WORD32 first_slice_in_pic_flag;
WORD32 no_output_of_prior_pics_flag = 0;
WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
WORD32 num_poc_total_curr = 0;
WORD32 slice_address;
if(ps_codec->i4_slice_error == 1)
return ret;
idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
(NAL_IDR_N_LP == i1_nal_unit_type);
BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
}
UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);
/* Get the current PPS structure */
ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
if(0 == ps_pps->i1_pps_valid)
{
pps_t *ps_pps_ref = ps_codec->ps_pps_base;
while(0 == ps_pps_ref->i1_pps_valid)
{
ps_pps_ref++;
if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
return IHEVCD_INVALID_HEADER;
}
ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
}
/* Get SPS id for the current PPS */
sps_id = ps_pps->i1_sps_id;
/* Get the current SPS structure */
ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;
/* When the current slice is the first in a pic,
* check whether the previous frame is complete
* If the previous frame is incomplete -
* treat the remaining CTBs as skip */
if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
first_slice_in_pic_flag)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
if(first_slice_in_pic_flag)
{
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
else
{
/* If the current slice is not the first slice in the pic,
* but the first one to be parsed, set the current slice indx to 1
* Treat the first slice to be missing and copy the current slice header
* to the first one */
if(0 == ps_codec->i4_pic_present)
ps_codec->s_parse.i4_cur_slice_idx = 1;
}
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
if((ps_pps->i1_dependent_slice_enabled_flag) &&
(!first_slice_in_pic_flag))
{
BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);
/* If dependendent slice, copy slice header from previous slice */
if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
{
ihevcd_copy_slice_hdr(ps_codec,
(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
}
ps_slice_hdr->i1_dependent_slice_flag = value;
}
else
{
ps_slice_hdr->i1_dependent_slice_flag = 0;
}
ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
ps_slice_hdr->i1_pps_id = pps_id;
ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;
ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
}
ps_slice_hdr->i1_pps_id = pps_id;
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
WORD32 num_bits;
/* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);
slice_address = value;
/* If slice address is greater than the number of CTBs in a picture,
* ignore the slice */
if(value >= ps_sps->i4_pic_size_in_ctb)
return IHEVCD_IGNORE_SLICE;
}
else
{
slice_address = 0;
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i1_pic_output_flag = 1;
ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
ps_slice_hdr->i1_num_long_term_sps = 0;
ps_slice_hdr->i1_num_long_term_pics = 0;
for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
{
BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
}
UEV_PARSE("slice_type", value, ps_bitstrm);
ps_slice_hdr->i1_slice_type = value;
/* If the picture is IRAP, slice type must be equal to ISLICE */
if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
(ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
ps_slice_hdr->i1_slice_type = ISLICE;
if((ps_slice_hdr->i1_slice_type < 0) ||
(ps_slice_hdr->i1_slice_type > 2))
return IHEVCD_IGNORE_SLICE;
if(ps_pps->i1_output_flag_present_flag)
{
BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_pic_output_flag = value;
}
ps_slice_hdr->i1_colour_plane_id = 0;
if(1 == ps_sps->i1_separate_colour_plane_flag)
{
BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
ps_slice_hdr->i1_colour_plane_id = value;
}
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;
if(!idr_pic_flag)
{
WORD32 st_rps_idx;
WORD32 num_neg_pics;
WORD32 num_pos_pics;
WORD8 *pi1_used;
BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->i4_pic_order_cnt_lsb = value;
BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;
if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
{
WORD32 numbits;
ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
{
numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
}
st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
}
else
{
ihevcd_short_term_ref_pic_set(ps_bitstrm,
&ps_sps->as_stref_picset[0],
ps_sps->i1_num_short_term_ref_pic_sets,
ps_sps->i1_num_short_term_ref_pic_sets,
&ps_slice_hdr->s_stref_picset);
st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
}
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
{
UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_sps = value;
ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
}
UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_pics = value;
ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
ps_slice_hdr->i1_num_long_term_sps);
for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
ps_slice_hdr->i1_num_long_term_pics); i++)
{
if(i < ps_slice_hdr->i1_num_long_term_sps)
{
/* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
if (ps_sps->i1_num_long_term_ref_pics_sps > 1)
{
WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps - 1);
BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
}
else
{
value = 0;
}
ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->au2_lt_ref_pic_poc_lsb_sps[value];
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];
}
else
{
BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->ai4_poc_lsb_lt[i] = value;
BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;
}
BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
{
UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
}
if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
{
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
}
}
}
for(i = 0; i < num_neg_pics + num_pos_pics; i++)
{
if(pi1_used[i])
{
num_poc_total_curr++;
}
}
for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
{
if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
{
num_poc_total_curr++;
}
}
if(ps_sps->i1_sps_temporal_mvp_enable_flag)
{
BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
}
}
ps_slice_hdr->i1_slice_sao_luma_flag = 0;
ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
{
BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_luma_flag = value;
BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_chroma_flag = value;
}
ps_slice_hdr->i1_max_num_merge_cand = 1;
ps_slice_hdr->i1_cabac_init_flag = 0;
ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
ps_slice_hdr->i1_slice_cb_qp_offset = 0;
ps_slice_hdr->i1_slice_cr_qp_offset = 0;
if((PSLICE == ps_slice_hdr->i1_slice_type) ||
(BSLICE == ps_slice_hdr->i1_slice_type))
{
BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;
if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
{
UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
}
}
else
{
ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
}
}
ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);
if(0 == num_poc_total_curr)
return IHEVCD_IGNORE_SLICE;
if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
{
ihevcd_ref_pic_list_modification(ps_bitstrm,
ps_slice_hdr, num_poc_total_curr);
}
else
{
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
}
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_mvd_l1_zero_flag = value;
}
ps_slice_hdr->i1_cabac_init_flag = 0;
if(ps_pps->i1_cabac_init_present_flag)
{
BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_cabac_init_flag = value;
}
ps_slice_hdr->i1_collocated_from_l0_flag = 1;
ps_slice_hdr->i1_collocated_ref_idx = 0;
if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
{
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_collocated_from_l0_flag = value;
}
if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
(!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
{
UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
ps_slice_hdr->i1_collocated_ref_idx = value;
}
}
ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);
if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
(ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type)))
{
ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
}
UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
ps_slice_hdr->i1_max_num_merge_cand = 5 - value;
}
ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
ps_slice_hdr->i1_slice_qp_delta = value;
if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
{
SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cb_qp_offset = value;
SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cr_qp_offset = value;
}
ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;
disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
if(ps_pps->i1_deblocking_filter_override_enabled_flag)
{
BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_deblocking_filter_override_flag = value;
}
if(ps_slice_hdr->i1_deblocking_filter_override_flag)
{
BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;
if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_beta_offset_div2 = value;
SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_tc_offset_div2 = value;
}
}
}
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
if(ps_pps->i1_loop_filter_across_slices_enabled_flag &&
(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag))
{
BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
}
}
/* Check sanity of slice */
if((!first_slice_in_pic_flag) &&
(ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;
/* According to the standard, the above conditions must be satisfied - But for error resilience,
* only the following conditions are checked */
if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
(ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(0 == ps_codec->i4_pic_present)
{
ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
}
else
{
ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
}
if(!first_slice_in_pic_flag)
{
/* Check if the current slice belongs to the same pic (Pic being parsed) */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
{
/* If the Next CTB's index is less than the slice address,
* the previous slice is incomplete.
* Indicate slice error, and treat the remaining CTBs as skip */
if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr_next->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
return ret;
}
else
{
return IHEVCD_IGNORE_SLICE;
}
}
/* If the slice address is less than the next CTB's index,
* extra CTBs have been decoded in the previous slice.
* Ignore the current slice. Treat it as incomplete */
else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
{
return IHEVCD_IGNORE_SLICE;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
/* The current slice does not belong to the pic that is being parsed */
else
{
/* The previous pic is incomplete.
* Treat the remaining CTBs as skip */
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
/* If the previous pic is complete,
* return if the current slice is dependant
* otherwise, update the parse context's POC */
else
{
if(ps_slice_hdr->i1_dependent_slice_flag)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
}
}
/* If the slice is the first slice in the pic, update the parse context's POC */
else
{
/* If the first slice is repeated, ignore the second occurrence
* If any other slice is repeated, the CTB addr will be greater than the slice addr,
* and hence the second occurrence is ignored */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
ps_slice_hdr->i4_num_entry_point_offsets = 0;
if((ps_pps->i1_tiles_enabled_flag) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
ps_slice_hdr->i4_num_entry_point_offsets = value;
{
WORD32 max_num_entry_point_offsets;
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
}
else if(ps_pps->i1_tiles_enabled_flag)
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
}
else
{
max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
}
ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
0, max_num_entry_point_offsets);
}
if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
{
UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_offset_len = value + 1;
for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
{
BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);
/* TODO: pu4_entry_point_offset needs to be initialized */
}
}
}
if(ps_pps->i1_slice_header_extension_present_flag)
{
UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
ps_slice_hdr->i2_slice_header_extension_length = value;
for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
{
BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
}
}
ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);
if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
return IHEVCD_INVALID_PARAMETER;
{
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
WORD32 r_idx;
if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(0 == ps_codec->u4_pic_cnt))
{
for(i = 0; i < MAX_DPB_BUFS; i++)
{
if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
{
pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
mv_buf_t *ps_mv_buf;
/* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
/* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
for(j = 0; j < ps_codec->i4_max_dpb_size; j++)
{
if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
{
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, j, BUF_MGR_REF);
break;
}
ps_mv_buf++;
}
}
}
/* Initialize the reference lists to NULL
* This is done to take care of the cases where the first pic is not IDR
* but the reference list is not created for the first pic because
* pic count is zero leaving the reference list uninitialised */
for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
}
}
else
{
ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
if ((WORD32)IHEVCD_SUCCESS != ret)
{
return ret;
}
}
}
/* Fill the remaining entries of the reference lists with the nearest POC
* This is done to handle cases where there is a corruption in the reference index */
if(ps_codec->i4_pic_present)
{
pic_buf_t *ps_pic_buf_ref;
mv_buf_t *ps_mv_buf_ref;
WORD32 r_idx;
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;
ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
if(NULL == ps_pic_buf_ref)
{
ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
}
else
{
ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
/* Update slice address in the header */
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
}
}
else
{
ps_slice_hdr->i2_ctb_x = 0;
ps_slice_hdr->i2_ctb_y = 0;
ps_slice_hdr->i2_independent_ctb_x = 0;
ps_slice_hdr->i2_independent_ctb_y = 0;
}
/* If the first slice in the pic is missing, copy the current slice header to
* the first slice's header */
if((!first_slice_in_pic_flag) &&
(0 == ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));
ps_codec->i4_slice_error = 1;
ps_slice_hdr_prev->i2_ctb_x = 0;
ps_slice_hdr_prev->i2_ctb_y = 0;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = 0;
ps_codec->s_parse.i4_cur_slice_idx = 0;
if((ps_slice_hdr->i2_ctb_x == 0) &&
(ps_slice_hdr->i2_ctb_y == 0))
{
ps_slice_hdr->i2_ctb_x++;
}
}
{
/* If skip B is enabled,
* ignore pictures that are non-reference
* TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
* sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/
if((i1_nal_unit_type < NAL_BLA_W_LP) &&
(i1_nal_unit_type % 2 == 0))
{
if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
return IHEVCD_IGNORE_SLICE;
}
/* If skip PB is enabled,
* decode only I slices */
if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
(ISLICE != ps_slice_hdr->i1_slice_type))
{
return IHEVCD_IGNORE_SLICE;
}
}
return ret;
}
Commit Message: Fix prev slice incomplete check
Bug: 64552185
Bug: 65034175
Move the decision to signal missing ctbs as skipped ctbs of
previous slice to the end of current slice hdr parsing to
ensure no error in slice hdr parsing.
Change-Id: Ia33b4be31dad6225b04e7b20b9000059c87941c4
(cherry picked from commit 74f35f191022c06863dacd33a3651a33be3ef08d)
(cherry picked from commit 9c24714e25d6ba713549a573df1d496479dce2b1)
CWE ID: CWE-200 | IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
nal_header_t *ps_nal)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i, j;
WORD32 sps_id;
pps_t *ps_pps;
sps_t *ps_sps;
slice_header_t *ps_slice_hdr;
WORD32 disable_deblocking_filter_flag;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 idr_pic_flag;
WORD32 pps_id;
WORD32 first_slice_in_pic_flag;
WORD32 no_output_of_prior_pics_flag = 0;
WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
WORD32 num_poc_total_curr = 0;
WORD32 slice_address;
WORD32 prev_slice_incomplete_flag = 0;
if(ps_codec->i4_slice_error == 1)
return ret;
idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
(NAL_IDR_N_LP == i1_nal_unit_type);
BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
}
UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);
/* Get the current PPS structure */
ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
if(0 == ps_pps->i1_pps_valid)
{
pps_t *ps_pps_ref = ps_codec->ps_pps_base;
while(0 == ps_pps_ref->i1_pps_valid)
{
ps_pps_ref++;
if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
return IHEVCD_INVALID_HEADER;
}
ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
}
/* Get SPS id for the current PPS */
sps_id = ps_pps->i1_sps_id;
/* Get the current SPS structure */
ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;
/* When the current slice is the first in a pic,
* check whether the previous frame is complete
* If the previous frame is incomplete -
* treat the remaining CTBs as skip */
if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
first_slice_in_pic_flag)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
if(first_slice_in_pic_flag)
{
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
else
{
/* If the current slice is not the first slice in the pic,
* but the first one to be parsed, set the current slice indx to 1
* Treat the first slice to be missing and copy the current slice header
* to the first one */
if(0 == ps_codec->i4_pic_present)
ps_codec->s_parse.i4_cur_slice_idx = 1;
}
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
if((ps_pps->i1_dependent_slice_enabled_flag) &&
(!first_slice_in_pic_flag))
{
BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);
/* If dependendent slice, copy slice header from previous slice */
if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
{
ihevcd_copy_slice_hdr(ps_codec,
(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
}
ps_slice_hdr->i1_dependent_slice_flag = value;
}
else
{
ps_slice_hdr->i1_dependent_slice_flag = 0;
}
ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
ps_slice_hdr->i1_pps_id = pps_id;
ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;
ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
}
ps_slice_hdr->i1_pps_id = pps_id;
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
WORD32 num_bits;
/* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);
slice_address = value;
/* If slice address is greater than the number of CTBs in a picture,
* ignore the slice */
if(value >= ps_sps->i4_pic_size_in_ctb)
return IHEVCD_IGNORE_SLICE;
}
else
{
slice_address = 0;
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i1_pic_output_flag = 1;
ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
ps_slice_hdr->i1_num_long_term_sps = 0;
ps_slice_hdr->i1_num_long_term_pics = 0;
for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
{
BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
}
UEV_PARSE("slice_type", value, ps_bitstrm);
ps_slice_hdr->i1_slice_type = value;
/* If the picture is IRAP, slice type must be equal to ISLICE */
if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
(ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
ps_slice_hdr->i1_slice_type = ISLICE;
if((ps_slice_hdr->i1_slice_type < 0) ||
(ps_slice_hdr->i1_slice_type > 2))
return IHEVCD_IGNORE_SLICE;
if(ps_pps->i1_output_flag_present_flag)
{
BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_pic_output_flag = value;
}
ps_slice_hdr->i1_colour_plane_id = 0;
if(1 == ps_sps->i1_separate_colour_plane_flag)
{
BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
ps_slice_hdr->i1_colour_plane_id = value;
}
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;
if(!idr_pic_flag)
{
WORD32 st_rps_idx;
WORD32 num_neg_pics;
WORD32 num_pos_pics;
WORD8 *pi1_used;
BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->i4_pic_order_cnt_lsb = value;
BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;
if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
{
WORD32 numbits;
ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
{
numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
}
st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
}
else
{
ihevcd_short_term_ref_pic_set(ps_bitstrm,
&ps_sps->as_stref_picset[0],
ps_sps->i1_num_short_term_ref_pic_sets,
ps_sps->i1_num_short_term_ref_pic_sets,
&ps_slice_hdr->s_stref_picset);
st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
}
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
{
UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_sps = value;
ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
}
UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_pics = value;
ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
ps_slice_hdr->i1_num_long_term_sps);
for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
ps_slice_hdr->i1_num_long_term_pics); i++)
{
if(i < ps_slice_hdr->i1_num_long_term_sps)
{
/* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
if (ps_sps->i1_num_long_term_ref_pics_sps > 1)
{
WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps - 1);
BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
}
else
{
value = 0;
}
ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->au2_lt_ref_pic_poc_lsb_sps[value];
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];
}
else
{
BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->ai4_poc_lsb_lt[i] = value;
BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;
}
BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
{
UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
}
if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
{
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
}
}
}
for(i = 0; i < num_neg_pics + num_pos_pics; i++)
{
if(pi1_used[i])
{
num_poc_total_curr++;
}
}
for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
{
if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
{
num_poc_total_curr++;
}
}
if(ps_sps->i1_sps_temporal_mvp_enable_flag)
{
BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
}
}
ps_slice_hdr->i1_slice_sao_luma_flag = 0;
ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
{
BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_luma_flag = value;
BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_chroma_flag = value;
}
ps_slice_hdr->i1_max_num_merge_cand = 1;
ps_slice_hdr->i1_cabac_init_flag = 0;
ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
ps_slice_hdr->i1_slice_cb_qp_offset = 0;
ps_slice_hdr->i1_slice_cr_qp_offset = 0;
if((PSLICE == ps_slice_hdr->i1_slice_type) ||
(BSLICE == ps_slice_hdr->i1_slice_type))
{
BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;
if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
{
UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
}
}
else
{
ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
}
}
ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);
if(0 == num_poc_total_curr)
return IHEVCD_IGNORE_SLICE;
if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
{
ihevcd_ref_pic_list_modification(ps_bitstrm,
ps_slice_hdr, num_poc_total_curr);
}
else
{
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
}
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_mvd_l1_zero_flag = value;
}
ps_slice_hdr->i1_cabac_init_flag = 0;
if(ps_pps->i1_cabac_init_present_flag)
{
BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_cabac_init_flag = value;
}
ps_slice_hdr->i1_collocated_from_l0_flag = 1;
ps_slice_hdr->i1_collocated_ref_idx = 0;
if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
{
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_collocated_from_l0_flag = value;
}
if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
(!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
{
UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
ps_slice_hdr->i1_collocated_ref_idx = value;
}
}
ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);
if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
(ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type)))
{
ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
}
UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
ps_slice_hdr->i1_max_num_merge_cand = 5 - value;
}
ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
ps_slice_hdr->i1_slice_qp_delta = value;
if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
{
SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cb_qp_offset = value;
SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cr_qp_offset = value;
}
ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;
disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
if(ps_pps->i1_deblocking_filter_override_enabled_flag)
{
BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_deblocking_filter_override_flag = value;
}
if(ps_slice_hdr->i1_deblocking_filter_override_flag)
{
BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;
if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_beta_offset_div2 = value;
SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_tc_offset_div2 = value;
}
}
}
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
if(ps_pps->i1_loop_filter_across_slices_enabled_flag &&
(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag))
{
BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
}
}
/* Check sanity of slice */
if((!first_slice_in_pic_flag) &&
(ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;
/* According to the standard, the above conditions must be satisfied - But for error resilience,
* only the following conditions are checked */
if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
(ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(0 == ps_codec->i4_pic_present)
{
ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
}
else
{
ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
}
if(!first_slice_in_pic_flag)
{
/* Check if the current slice belongs to the same pic (Pic being parsed) */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
{
/* If the Next CTB's index is less than the slice address,
* the previous slice is incomplete.
* Indicate slice error, and treat the remaining CTBs as skip */
if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)
{
if(ps_codec->i4_pic_present)
{
prev_slice_incomplete_flag = 1;
}
else
{
return IHEVCD_IGNORE_SLICE;
}
}
/* If the slice address is less than the next CTB's index,
* extra CTBs have been decoded in the previous slice.
* Ignore the current slice. Treat it as incomplete */
else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
{
return IHEVCD_IGNORE_SLICE;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
/* The current slice does not belong to the pic that is being parsed */
else
{
/* The previous pic is incomplete.
* Treat the remaining CTBs as skip */
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
/* If the previous pic is complete,
* return if the current slice is dependant
* otherwise, update the parse context's POC */
else
{
if(ps_slice_hdr->i1_dependent_slice_flag)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
}
}
/* If the slice is the first slice in the pic, update the parse context's POC */
else
{
/* If the first slice is repeated, ignore the second occurrence
* If any other slice is repeated, the CTB addr will be greater than the slice addr,
* and hence the second occurrence is ignored */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
ps_slice_hdr->i4_num_entry_point_offsets = 0;
if((ps_pps->i1_tiles_enabled_flag) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
ps_slice_hdr->i4_num_entry_point_offsets = value;
{
WORD32 max_num_entry_point_offsets;
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
}
else if(ps_pps->i1_tiles_enabled_flag)
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
}
else
{
max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
}
ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
0, max_num_entry_point_offsets);
}
if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
{
UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_offset_len = value + 1;
for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
{
BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);
/* TODO: pu4_entry_point_offset needs to be initialized */
}
}
}
if(ps_pps->i1_slice_header_extension_present_flag)
{
UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
ps_slice_hdr->i2_slice_header_extension_length = value;
for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
{
BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
}
}
ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);
if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
return IHEVCD_INVALID_PARAMETER;
{
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
WORD32 r_idx;
if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(0 == ps_codec->u4_pic_cnt))
{
for(i = 0; i < MAX_DPB_BUFS; i++)
{
if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
{
pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
mv_buf_t *ps_mv_buf;
/* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
/* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
for(j = 0; j < ps_codec->i4_max_dpb_size; j++)
{
if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
{
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, j, BUF_MGR_REF);
break;
}
ps_mv_buf++;
}
}
}
/* Initialize the reference lists to NULL
* This is done to take care of the cases where the first pic is not IDR
* but the reference list is not created for the first pic because
* pic count is zero leaving the reference list uninitialised */
for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
}
}
else
{
ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
if ((WORD32)IHEVCD_SUCCESS != ret)
{
return ret;
}
}
}
/* Fill the remaining entries of the reference lists with the nearest POC
* This is done to handle cases where there is a corruption in the reference index */
if(ps_codec->i4_pic_present)
{
pic_buf_t *ps_pic_buf_ref;
mv_buf_t *ps_mv_buf_ref;
WORD32 r_idx;
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;
ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
if(NULL == ps_pic_buf_ref)
{
ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
}
else
{
ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
/* Update slice address in the header */
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
}
}
else
{
ps_slice_hdr->i2_ctb_x = 0;
ps_slice_hdr->i2_ctb_y = 0;
ps_slice_hdr->i2_independent_ctb_x = 0;
ps_slice_hdr->i2_independent_ctb_y = 0;
}
/* If the first slice in the pic is missing, copy the current slice header to
* the first slice's header */
if((!first_slice_in_pic_flag) &&
(0 == ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));
prev_slice_incomplete_flag = 1;
ASSERT(ps_codec->s_parse.i4_cur_slice_idx == 1);
ps_slice_hdr_prev->i2_ctb_x = 0;
ps_slice_hdr_prev->i2_ctb_y = 0;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = 0;
ps_codec->s_parse.i4_cur_slice_idx = 0;
if((ps_slice_hdr->i2_ctb_x == 0) &&
(ps_slice_hdr->i2_ctb_y == 0))
{
ps_slice_hdr->i2_ctb_x++;
}
}
{
/* If skip B is enabled,
* ignore pictures that are non-reference
* TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
* sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/
if((i1_nal_unit_type < NAL_BLA_W_LP) &&
(i1_nal_unit_type % 2 == 0))
{
if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
return IHEVCD_IGNORE_SLICE;
}
/* If skip PB is enabled,
* decode only I slices */
if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
(ISLICE != ps_slice_hdr->i1_slice_type))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(prev_slice_incomplete_flag)
{
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
return ret;
}
| 174,115 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> enabledAtRuntimeMethod1Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.enabledAtRuntimeMethod1");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->enabledAtRuntimeMethod1(intArg);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> enabledAtRuntimeMethod1Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.enabledAtRuntimeMethod1");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->enabledAtRuntimeMethod1(intArg);
return v8::Handle<v8::Value>();
}
| 171,082 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void addArgumentToVtab(Parse *pParse){
if( pParse->sArg.z && pParse->pNewTable ){
const char *z = (const char*)pParse->sArg.z;
int n = pParse->sArg.n;
sqlite3 *db = pParse->db;
addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
}
}
Commit Message: sqlite: backport bugfixes for dbfuzz2
Bug: 952406
Change-Id: Icbec429742048d6674828726c96d8e265c41b595
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152
Reviewed-by: Chris Mumford <[email protected]>
Commit-Queue: Darwin Huang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#651030}
CWE ID: CWE-190 | static void addArgumentToVtab(Parse *pParse){
if( pParse->sArg.z && pParse->pNewTable ){
const char *z = (const char*)pParse->sArg.z;
int n = pParse->sArg.n;
sqlite3 *db = pParse->db;
addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
}
}
| 173,013 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *cee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx, i, err = -EMSGSIZE;
u8 value;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
goto nla_put_failure;
cee = nla_nest_start(skb, DCB_ATTR_CEE);
if (!cee)
goto nla_put_failure;
/* local pg */
if (ops->getpgtccfgtx && ops->getpgbwgcfgtx) {
err = dcbnl_cee_pg_fill(skb, netdev, 1);
if (err)
goto nla_put_failure;
}
if (ops->getpgtccfgrx && ops->getpgbwgcfgrx) {
err = dcbnl_cee_pg_fill(skb, netdev, 0);
if (err)
goto nla_put_failure;
}
/* local pfc */
if (ops->getpfccfg) {
struct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC);
if (!pfc_nest)
goto nla_put_failure;
for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) {
ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value);
if (nla_put_u8(skb, i, value))
goto nla_put_failure;
}
nla_nest_end(skb, pfc_nest);
}
/* local app */
spin_lock(&dcb_lock);
app = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE);
if (!app)
goto dcb_unlock;
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
struct nlattr *app_nest = nla_nest_start(skb,
DCB_ATTR_APP);
if (!app_nest)
goto dcb_unlock;
err = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE,
itr->app.selector);
if (err)
goto dcb_unlock;
err = nla_put_u16(skb, DCB_APP_ATTR_ID,
itr->app.protocol);
if (err)
goto dcb_unlock;
err = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY,
itr->app.priority);
if (err)
goto dcb_unlock;
nla_nest_end(skb, app_nest);
}
}
nla_nest_end(skb, app);
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
/* features flags */
if (ops->getfeatcfg) {
struct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT);
if (!feat)
goto nla_put_failure;
for (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX;
i++)
if (!ops->getfeatcfg(netdev, i, &value) &&
nla_put_u8(skb, i, value))
goto nla_put_failure;
nla_nest_end(skb, feat);
}
/* peer info if available */
if (ops->cee_peer_getpg) {
struct cee_pg pg;
err = ops->cee_peer_getpg(netdev, &pg);
if (!err &&
nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg))
goto nla_put_failure;
}
if (ops->cee_peer_getpfc) {
struct cee_pfc pfc;
err = ops->cee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc))
goto nla_put_failure;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_CEE_PEER_APP_TABLE,
DCB_ATTR_CEE_PEER_APP_INFO,
DCB_ATTR_CEE_PEER_APP);
if (err)
goto nla_put_failure;
}
nla_nest_end(skb, cee);
/* DCBX state */
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
goto nla_put_failure;
}
return 0;
dcb_unlock:
spin_unlock(&dcb_lock);
nla_put_failure:
return err;
}
Commit Message: dcbnl: fix various netlink info leaks
The dcb netlink interface leaks stack memory in various places:
* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but
copied completely,
* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,
so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes
for ieee_pfc structs, etc.,
* the same is true for CEE -- no in-kernel driver fills the whole
struct,
Prevent all of the above stack info leaks by properly initializing the
buffers/structures involved.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *cee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx, i, err = -EMSGSIZE;
u8 value;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
goto nla_put_failure;
cee = nla_nest_start(skb, DCB_ATTR_CEE);
if (!cee)
goto nla_put_failure;
/* local pg */
if (ops->getpgtccfgtx && ops->getpgbwgcfgtx) {
err = dcbnl_cee_pg_fill(skb, netdev, 1);
if (err)
goto nla_put_failure;
}
if (ops->getpgtccfgrx && ops->getpgbwgcfgrx) {
err = dcbnl_cee_pg_fill(skb, netdev, 0);
if (err)
goto nla_put_failure;
}
/* local pfc */
if (ops->getpfccfg) {
struct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC);
if (!pfc_nest)
goto nla_put_failure;
for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) {
ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value);
if (nla_put_u8(skb, i, value))
goto nla_put_failure;
}
nla_nest_end(skb, pfc_nest);
}
/* local app */
spin_lock(&dcb_lock);
app = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE);
if (!app)
goto dcb_unlock;
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
struct nlattr *app_nest = nla_nest_start(skb,
DCB_ATTR_APP);
if (!app_nest)
goto dcb_unlock;
err = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE,
itr->app.selector);
if (err)
goto dcb_unlock;
err = nla_put_u16(skb, DCB_APP_ATTR_ID,
itr->app.protocol);
if (err)
goto dcb_unlock;
err = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY,
itr->app.priority);
if (err)
goto dcb_unlock;
nla_nest_end(skb, app_nest);
}
}
nla_nest_end(skb, app);
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
/* features flags */
if (ops->getfeatcfg) {
struct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT);
if (!feat)
goto nla_put_failure;
for (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX;
i++)
if (!ops->getfeatcfg(netdev, i, &value) &&
nla_put_u8(skb, i, value))
goto nla_put_failure;
nla_nest_end(skb, feat);
}
/* peer info if available */
if (ops->cee_peer_getpg) {
struct cee_pg pg;
memset(&pg, 0, sizeof(pg));
err = ops->cee_peer_getpg(netdev, &pg);
if (!err &&
nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg))
goto nla_put_failure;
}
if (ops->cee_peer_getpfc) {
struct cee_pfc pfc;
memset(&pfc, 0, sizeof(pfc));
err = ops->cee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc))
goto nla_put_failure;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_CEE_PEER_APP_TABLE,
DCB_ATTR_CEE_PEER_APP_INFO,
DCB_ATTR_CEE_PEER_APP);
if (err)
goto nla_put_failure;
}
nla_nest_end(skb, cee);
/* DCBX state */
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
goto nla_put_failure;
}
return 0;
dcb_unlock:
spin_unlock(&dcb_lock);
nla_put_failure:
return err;
}
| 166,057 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: normalize_color_encoding(color_encoding *encoding)
{
PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y +
encoding->blue.Y;
if (whiteY != 1)
{
encoding->red.X /= whiteY;
encoding->red.Y /= whiteY;
encoding->red.Z /= whiteY;
encoding->green.X /= whiteY;
encoding->green.Y /= whiteY;
encoding->green.Z /= whiteY;
encoding->blue.X /= whiteY;
encoding->blue.Y /= whiteY;
encoding->blue.Z /= whiteY;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | normalize_color_encoding(color_encoding *encoding)
{
const double whiteY = encoding->red.Y + encoding->green.Y +
encoding->blue.Y;
if (whiteY != 1)
{
encoding->red.X /= whiteY;
encoding->red.Y /= whiteY;
encoding->red.Z /= whiteY;
encoding->green.X /= whiteY;
encoding->green.Y /= whiteY;
encoding->green.Z /= whiteY;
encoding->blue.X /= whiteY;
encoding->blue.Y /= whiteY;
encoding->blue.Z /= whiteY;
}
}
| 173,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
Commit Message: Bail out on partial reads, from Alexander Cherepanov
CWE ID: CWE-20 | dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
| 166,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColorAlpha(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),
gdTrueColorGetAlpha(c)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
Commit Message: Fix bug #72730 - imagegammacorrect allows arbitrary write access
CWE ID: CWE-787 | PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
if ( input <= 0.0 || output <= 0.0 ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Gamma values should be positive");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColorAlpha(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),
gdTrueColorGetAlpha(c)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
| 166,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119 | void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
| 174,606 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaStreamManager::OpenDevice(int render_process_id,
int render_frame_id,
int page_request_id,
const std::string& device_id,
MediaStreamType type,
MediaDeviceSaltAndOrigin salt_and_origin,
OpenDeviceCallback open_device_cb,
DeviceStoppedCallback device_stopped_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
StreamControls controls;
if (IsAudioInputMediaType(type)) {
controls.audio.requested = true;
controls.audio.stream_type = type;
controls.audio.device_id = device_id;
} else if (IsVideoInputMediaType(type)) {
controls.video.requested = true;
controls.video.stream_type = type;
controls.video.device_id = device_id;
} else {
NOTREACHED();
}
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_OPEN_DEVICE_PEPPER_ONLY, controls,
std::move(salt_and_origin), std::move(device_stopped_cb));
const std::string& label = AddRequest(request);
request->open_device_cb = std::move(open_device_cb);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
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 MediaStreamManager::OpenDevice(int render_process_id,
int render_frame_id,
int requester_id,
int page_request_id,
const std::string& device_id,
MediaStreamType type,
MediaDeviceSaltAndOrigin salt_and_origin,
OpenDeviceCallback open_device_cb,
DeviceStoppedCallback device_stopped_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
StreamControls controls;
if (IsAudioInputMediaType(type)) {
controls.audio.requested = true;
controls.audio.stream_type = type;
controls.audio.device_id = device_id;
} else if (IsVideoInputMediaType(type)) {
controls.video.requested = true;
controls.video.stream_type = type;
controls.video.device_id = device_id;
} else {
NOTREACHED();
}
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
false /* user gesture */, MEDIA_OPEN_DEVICE_PEPPER_ONLY, controls,
std::move(salt_and_origin), std::move(device_stopped_cb));
const std::string& label = AddRequest(request);
request->open_device_cb = std::move(open_device_cb);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
| 173,105 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int FindStartOffsetOfFileInZipFile(const char* zip_file, const char* filename) {
FileDescriptor fd;
if (!fd.OpenReadOnly(zip_file)) {
LOG_ERRNO("%s: open failed trying to open zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
struct stat stat_buf;
if (stat(zip_file, &stat_buf) == -1) {
LOG_ERRNO("%s: stat failed trying to stat zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
if (stat_buf.st_size > kMaxZipFileLength) {
LOG("%s: The size %ld of %s is too large to map\n",
__FUNCTION__, stat_buf.st_size, zip_file);
return CRAZY_OFFSET_FAILED;
}
void* mem = fd.Map(NULL, stat_buf.st_size, PROT_READ, MAP_PRIVATE, 0);
if (mem == MAP_FAILED) {
LOG_ERRNO("%s: mmap failed trying to mmap zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
ScopedMMap scoped_mmap(mem, stat_buf.st_size);
uint8_t* mem_bytes = static_cast<uint8_t*>(mem);
int off;
for (off = stat_buf.st_size - sizeof(kEndOfCentralDirectoryMarker);
off >= 0; --off) {
if (ReadUInt32(mem_bytes, off) == kEndOfCentralDirectoryMarker) {
break;
}
}
if (off == -1) {
LOG("%s: Failed to find end of central directory in %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t length_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfCentralDirLengthInEndOfCentralDirectory);
uint32_t start_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfStartOfCentralDirInEndOfCentralDirectory);
if (start_of_central_dir > off) {
LOG("%s: Found out of range offset %u for start of directory in %s\n",
__FUNCTION__, start_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t end_of_central_dir = start_of_central_dir + length_of_central_dir;
if (end_of_central_dir > off) {
LOG("%s: Found out of range offset %u for end of directory in %s\n",
__FUNCTION__, end_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t num_entries = ReadUInt16(
mem_bytes, off + kOffsetNumOfEntriesInEndOfCentralDirectory);
off = start_of_central_dir;
const int target_len = strlen(filename);
int n = 0;
for (; n < num_entries && off < end_of_central_dir; ++n) {
uint32_t marker = ReadUInt32(mem_bytes, off);
if (marker != kCentralDirHeaderMarker) {
LOG("%s: Failed to find central directory header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kCentralDirHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(mem_bytes, off + kOffsetFilenameLengthInCentralDirectory);
uint32_t extra_field_length =
ReadUInt16(mem_bytes, off + kOffsetExtraFieldLengthInCentralDirectory);
uint32_t comment_field_length =
ReadUInt16(mem_bytes, off + kOffsetCommentLengthInCentralDirectory);
uint32_t header_length = kOffsetFilenameInCentralDirectory +
file_name_length + extra_field_length + comment_field_length;
uint32_t local_header_offset =
ReadUInt32(mem_bytes, off + kOffsetLocalHeaderOffsetInCentralDirectory);
uint8_t* filename_bytes =
mem_bytes + off + kOffsetFilenameInCentralDirectory;
if (file_name_length == target_len &&
memcmp(filename_bytes, filename, target_len) == 0) {
uint32_t marker = ReadUInt32(mem_bytes, local_header_offset);
if (marker != kLocalHeaderMarker) {
LOG("%s: Failed to find local file header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kLocalHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t compression_method =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetCompressionMethodInLocalHeader);
if (compression_method != kCompressionMethodStored) {
LOG("%s: %s is compressed within %s. "
"Found compression method %u but expected %u\n", __FUNCTION__,
filename, zip_file, compression_method, kCompressionMethodStored);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetFilenameLengthInLocalHeader);
uint32_t extra_field_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetExtraFieldLengthInLocalHeader);
uint32_t header_length =
kOffsetFilenameInLocalHeader + file_name_length + extra_field_length;
return local_header_offset + header_length;
}
off += header_length;
}
if (n < num_entries) {
LOG("%s: Did not find all the expected entries in the central directory. "
"Found %d but expected %d\n", __FUNCTION__, n, num_entries);
}
if (off < end_of_central_dir) {
LOG("%s: There are %d extra bytes at the end of the central directory.\n",
__FUNCTION__, end_of_central_dir - off);
}
LOG("%s: Did not find %s in %s\n", __FUNCTION__, filename, zip_file);
return CRAZY_OFFSET_FAILED;
}
Commit Message: crazy linker: Alter search for zip EOCD start
When loading directly from APK, begin searching backwards
for the zip EOCD record signature at size of EOCD record
bytes before the end of the file.
BUG=537205
[email protected]
Review URL: https://codereview.chromium.org/1390553002 .
Cr-Commit-Position: refs/heads/master@{#352577}
CWE ID: CWE-20 | int FindStartOffsetOfFileInZipFile(const char* zip_file, const char* filename) {
FileDescriptor fd;
if (!fd.OpenReadOnly(zip_file)) {
LOG_ERRNO("%s: open failed trying to open zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
struct stat stat_buf;
if (stat(zip_file, &stat_buf) == -1) {
LOG_ERRNO("%s: stat failed trying to stat zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
if (stat_buf.st_size > kMaxZipFileLength) {
LOG("%s: The size %ld of %s is too large to map\n",
__FUNCTION__, stat_buf.st_size, zip_file);
return CRAZY_OFFSET_FAILED;
}
void* mem = fd.Map(NULL, stat_buf.st_size, PROT_READ, MAP_PRIVATE, 0);
if (mem == MAP_FAILED) {
LOG_ERRNO("%s: mmap failed trying to mmap zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
ScopedMMap scoped_mmap(mem, stat_buf.st_size);
// central directory marker. The earliest occurrence we accept is
// size of end of central directory bytes back from from the end of the
// file.
uint8_t* mem_bytes = static_cast<uint8_t*>(mem);
int off = stat_buf.st_size - kEndOfCentralDirectoryRecordSize;
for (; off >= 0; --off) {
if (ReadUInt32(mem_bytes, off) == kEndOfCentralDirectoryMarker) {
break;
}
}
if (off == -1) {
LOG("%s: Failed to find end of central directory in %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t length_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfCentralDirLengthInEndOfCentralDirectory);
uint32_t start_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfStartOfCentralDirInEndOfCentralDirectory);
if (start_of_central_dir > off) {
LOG("%s: Found out of range offset %u for start of directory in %s\n",
__FUNCTION__, start_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t end_of_central_dir = start_of_central_dir + length_of_central_dir;
if (end_of_central_dir > off) {
LOG("%s: Found out of range offset %u for end of directory in %s\n",
__FUNCTION__, end_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t num_entries = ReadUInt16(
mem_bytes, off + kOffsetNumOfEntriesInEndOfCentralDirectory);
off = start_of_central_dir;
const int target_len = strlen(filename);
int n = 0;
for (; n < num_entries && off < end_of_central_dir; ++n) {
uint32_t marker = ReadUInt32(mem_bytes, off);
if (marker != kCentralDirHeaderMarker) {
LOG("%s: Failed to find central directory header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kCentralDirHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(mem_bytes, off + kOffsetFilenameLengthInCentralDirectory);
uint32_t extra_field_length =
ReadUInt16(mem_bytes, off + kOffsetExtraFieldLengthInCentralDirectory);
uint32_t comment_field_length =
ReadUInt16(mem_bytes, off + kOffsetCommentLengthInCentralDirectory);
uint32_t header_length = kOffsetFilenameInCentralDirectory +
file_name_length + extra_field_length + comment_field_length;
uint32_t local_header_offset =
ReadUInt32(mem_bytes, off + kOffsetLocalHeaderOffsetInCentralDirectory);
uint8_t* filename_bytes =
mem_bytes + off + kOffsetFilenameInCentralDirectory;
if (file_name_length == target_len &&
memcmp(filename_bytes, filename, target_len) == 0) {
uint32_t marker = ReadUInt32(mem_bytes, local_header_offset);
if (marker != kLocalHeaderMarker) {
LOG("%s: Failed to find local file header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kLocalHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t compression_method =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetCompressionMethodInLocalHeader);
if (compression_method != kCompressionMethodStored) {
LOG("%s: %s is compressed within %s. "
"Found compression method %u but expected %u\n", __FUNCTION__,
filename, zip_file, compression_method, kCompressionMethodStored);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetFilenameLengthInLocalHeader);
uint32_t extra_field_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetExtraFieldLengthInLocalHeader);
uint32_t header_length =
kOffsetFilenameInLocalHeader + file_name_length + extra_field_length;
return local_header_offset + header_length;
}
off += header_length;
}
if (n < num_entries) {
LOG("%s: Did not find all the expected entries in the central directory. "
"Found %d but expected %d\n", __FUNCTION__, n, num_entries);
}
if (off < end_of_central_dir) {
LOG("%s: There are %d extra bytes at the end of the central directory.\n",
__FUNCTION__, end_of_central_dir - off);
}
LOG("%s: Did not find %s in %s\n", __FUNCTION__, filename, zip_file);
return CRAZY_OFFSET_FAILED;
}
| 171,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Block::GetTrackNumber() const
{
return m_track;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Block::GetTrackNumber() const
bool Block::IsKey() const {
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
}
| 174,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs)
{
gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern;
gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace;
int code;
uchar k, num_comps;
pinst->saved->overprint_mode = pgs->overprint_mode;
pinst->saved->overprint = pgs->overprint;
num_comps = pgs->device->color_info.num_components;
for (k = 0; k < num_comps; k++) {
pgs->color_component_map.color_map[k] =
pinst->saved->color_component_map.color_map[k];
}
code = pcs->type->set_overprint(pcs, pgs);
return code;
}
Commit Message:
CWE ID: CWE-704 | gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs)
{
gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern;
gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace;
int code;
uchar k, num_comps;
pinst->saved->overprint_mode = pgs->overprint_mode;
pinst->saved->overprint = pgs->overprint;
num_comps = pgs->device->color_info.num_components;
for (k = 0; k < num_comps; k++) {
pgs->color_component_map.color_map[k] =
pinst->saved->color_component_map.color_map[k];
}
code = pcs->type->set_overprint(pcs, pgs);
return code;
}
| 164,647 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service) {
file_info_.is_directory = true;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectory::GDataDirectory(GDataDirectoryService* directory_service)
: GDataEntry(directory_service) {
file_info_.is_directory = true;
}
| 171,489 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp,
tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) {
tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT;
uint8_t u8, pdu, *p;
uint16_t u16;
tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor;
pdu = *(p_vendor->p_vendor_data);
p_rc_rsp->pdu = pdu;
*p_ctype = AVRC_RSP_REJ;
/* Check to ansure a valid minimum meta data length */
if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) {
/* reject it */
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__,
p_vendor->vendor_len);
return 0;
}
/* Metadata messages only use PANEL sub-unit type */
if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) {
APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__);
/* reject it */
evt = 0;
p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL;
p_vendor->vendor_len = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
} else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) {
APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu,
p_vendor->hdr.ctype);
/* reject invalid message without reporting to app */
evt = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD;
} else {
switch (pdu) {
case AVRC_PDU_GET_CAPABILITIES:
/* process GetCapabilities command without reporting the event to app */
evt = 0;
u8 = *(p_vendor->p_vendor_data + 4);
p = p_vendor->p_vendor_data + 2;
p_rc_rsp->get_caps.capability_id = u8;
BE_STREAM_TO_UINT16(u16, p);
if ((u16 != 1) || (p_vendor->vendor_len != 5)) {
p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
} else {
p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR;
if (u8 == AVRC_CAP_COMPANY_ID) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids;
memcpy(p_rc_rsp->get_caps.param.company_id,
p_bta_av_cfg->p_meta_co_ids,
(p_bta_av_cfg->num_co_ids << 2));
} else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids;
memcpy(p_rc_rsp->get_caps.param.event_id,
p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids);
} else {
APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8);
/* reject - unknown capability ID */
p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM;
}
}
break;
case AVRC_PDU_REGISTER_NOTIFICATION:
/* make sure the event_id is implemented */
p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor);
if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0;
break;
}
}
return evt;
}
Commit Message: Check packet length in bta_av_proc_meta_cmd
Bug: 111893951
Test: manual - connect A2DP
Change-Id: Ibbf347863dfd29ea3385312e9dde1082bc90d2f3
(cherry picked from commit ed51887f921263219bcd2fbf6650ead5ec8d334e)
CWE ID: CWE-125 | tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp,
tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) {
tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT;
uint8_t u8, pdu, *p;
uint16_t u16;
tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor;
pdu = *(p_vendor->p_vendor_data);
p_rc_rsp->pdu = pdu;
*p_ctype = AVRC_RSP_REJ;
/* Check to ansure a valid minimum meta data length */
if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) {
/* reject it */
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__,
p_vendor->vendor_len);
return 0;
}
/* Metadata messages only use PANEL sub-unit type */
if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) {
APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__);
/* reject it */
evt = 0;
p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL;
p_vendor->vendor_len = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
} else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) {
APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu,
p_vendor->hdr.ctype);
/* reject invalid message without reporting to app */
evt = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD;
} else {
switch (pdu) {
case AVRC_PDU_GET_CAPABILITIES:
/* process GetCapabilities command without reporting the event to app */
evt = 0;
if (p_vendor->vendor_len != 5) {
android_errorWriteLog(0x534e4554, "111893951");
p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
break;
}
u8 = *(p_vendor->p_vendor_data + 4);
p = p_vendor->p_vendor_data + 2;
p_rc_rsp->get_caps.capability_id = u8;
BE_STREAM_TO_UINT16(u16, p);
if (u16 != 1) {
p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
} else {
p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR;
if (u8 == AVRC_CAP_COMPANY_ID) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids;
memcpy(p_rc_rsp->get_caps.param.company_id,
p_bta_av_cfg->p_meta_co_ids,
(p_bta_av_cfg->num_co_ids << 2));
} else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids;
memcpy(p_rc_rsp->get_caps.param.event_id,
p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids);
} else {
APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8);
/* reject - unknown capability ID */
p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM;
}
}
break;
case AVRC_PDU_REGISTER_NOTIFICATION:
/* make sure the event_id is implemented */
p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor);
if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0;
break;
}
}
return evt;
}
| 174,078 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs4_opendata *opendata;
opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, NULL);
if (opendata == NULL)
return ERR_PTR(-ENOMEM);
opendata->state = state;
atomic_inc(&state->count);
return opendata;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs4_opendata *opendata;
opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, 0, NULL);
if (opendata == NULL)
return ERR_PTR(-ENOMEM);
opendata->state = state;
atomic_inc(&state->count);
return opendata;
}
| 165,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void swizzleImageData(unsigned char* srcAddr,
size_t height,
size_t bytesPerRow,
bool flipY) {
if (flipY) {
for (size_t i = 0; i < height / 2; i++) {
size_t topRowStartPosition = i * bytesPerRow;
size_t bottomRowStartPosition = (height - 1 - i) * bytesPerRow;
if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle
for (size_t j = 0; j < bytesPerRow; j += 4) {
std::swap(srcAddr[topRowStartPosition + j],
srcAddr[bottomRowStartPosition + j + 2]);
std::swap(srcAddr[topRowStartPosition + j + 1],
srcAddr[bottomRowStartPosition + j + 1]);
std::swap(srcAddr[topRowStartPosition + j + 2],
srcAddr[bottomRowStartPosition + j]);
std::swap(srcAddr[topRowStartPosition + j + 3],
srcAddr[bottomRowStartPosition + j + 3]);
}
} else {
std::swap_ranges(srcAddr + topRowStartPosition,
srcAddr + topRowStartPosition + bytesPerRow,
srcAddr + bottomRowStartPosition);
}
}
} else {
if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle
for (size_t i = 0; i < height * bytesPerRow; i += 4)
std::swap(srcAddr[i], srcAddr[i + 2]);
}
}
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 void swizzleImageData(unsigned char* srcAddr,
unsigned height,
unsigned bytesPerRow,
bool flipY) {
if (flipY) {
for (unsigned i = 0; i < height / 2; i++) {
unsigned topRowStartPosition = i * bytesPerRow;
unsigned bottomRowStartPosition = (height - 1 - i) * bytesPerRow;
if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle
for (unsigned j = 0; j < bytesPerRow; j += 4) {
std::swap(srcAddr[topRowStartPosition + j],
srcAddr[bottomRowStartPosition + j + 2]);
std::swap(srcAddr[topRowStartPosition + j + 1],
srcAddr[bottomRowStartPosition + j + 1]);
std::swap(srcAddr[topRowStartPosition + j + 2],
srcAddr[bottomRowStartPosition + j]);
std::swap(srcAddr[topRowStartPosition + j + 3],
srcAddr[bottomRowStartPosition + j + 3]);
}
} else {
std::swap_ranges(srcAddr + topRowStartPosition,
srcAddr + topRowStartPosition + bytesPerRow,
srcAddr + bottomRowStartPosition);
}
}
} else {
if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle
for (unsigned i = 0; i < height * bytesPerRow; i += 4)
std::swap(srcAddr[i], srcAddr[i + 2]);
}
}
| 172,506 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if (*string++ == XK_minus)
stringdashes--;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
Commit Message:
CWE ID: CWE-125 | PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if ((t = *string++) == XK_minus)
stringdashes--;
if (!t)
return 0;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
| 164,693 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string ContextualSearchDelegate::BuildRequestUrl(std::string selection) {
if (!template_url_service_ ||
!template_url_service_->GetDefaultSearchProvider()) {
return std::string();
}
std::string selected_text(net::EscapeQueryParamValue(selection, true));
TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider();
TemplateURLRef::SearchTermsArgs search_terms_args =
TemplateURLRef::SearchTermsArgs(base::string16());
int now_on_tap_version =
field_trial_->IsNowOnTapBarIntegrationEnabled() ? kNowOnTapVersion : 0;
TemplateURLRef::SearchTermsArgs::ContextualSearchParams params(
kContextualSearchRequestVersion, selected_text, std::string(),
now_on_tap_version);
search_terms_args.contextual_search_params = params;
std::string request(
template_url->contextual_search_url_ref().ReplaceSearchTerms(
search_terms_args,
template_url_service_->search_terms_data(),
NULL));
std::string replacement_url = field_trial_->GetResolverURLPrefix();
if (!replacement_url.empty()) {
size_t pos = request.find(kContextualSearchServerEndpoint);
if (pos != std::string::npos) {
request.replace(0, pos + strlen(kContextualSearchServerEndpoint),
replacement_url);
}
}
return request;
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | std::string ContextualSearchDelegate::BuildRequestUrl(std::string selection) {
if (!template_url_service_ ||
!template_url_service_->GetDefaultSearchProvider()) {
return std::string();
}
std::string selected_text(net::EscapeQueryParamValue(selection, true));
TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider();
TemplateURLRef::SearchTermsArgs search_terms_args =
TemplateURLRef::SearchTermsArgs(base::string16());
int contextual_cards_version =
field_trial_->IsContextualCardsBarIntegrationEnabled()
? kContextualCardsVersion : 0;
TemplateURLRef::SearchTermsArgs::ContextualSearchParams params(
kContextualSearchRequestVersion, selected_text, std::string(),
contextual_cards_version);
search_terms_args.contextual_search_params = params;
std::string request(
template_url->contextual_search_url_ref().ReplaceSearchTerms(
search_terms_args,
template_url_service_->search_terms_data(),
NULL));
std::string replacement_url = field_trial_->GetResolverURLPrefix();
if (!replacement_url.empty()) {
size_t pos = request.find(kContextualSearchServerEndpoint);
if (pos != std::string::npos) {
request.replace(0, pos + strlen(kContextualSearchServerEndpoint),
replacement_url);
}
}
return request;
}
| 171,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Handle<v8::Value> V8WebKitMutationObserver::observeCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebKitMutationObserver.observe");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
WebKitMutationObserver* imp = V8WebKitMutationObserver::toNative(args.Holder());
EXCEPTION_BLOCK(Node*, target, V8Node::HasInstance(args[0]) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0);
if (!args[1]->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
Dictionary optionsObject(args[1]);
unsigned options = 0;
HashSet<AtomicString> attributeFilter;
bool option;
if (optionsObject.get("childList", option) && option)
options |= WebKitMutationObserver::ChildList;
if (optionsObject.get("attributes", option) && option)
options |= WebKitMutationObserver::Attributes;
if (optionsObject.get("attributeFilter", attributeFilter))
options |= WebKitMutationObserver::AttributeFilter;
if (optionsObject.get("characterData", option) && option)
options |= WebKitMutationObserver::CharacterData;
if (optionsObject.get("subtree", option) && option)
options |= WebKitMutationObserver::Subtree;
if (optionsObject.get("attributeOldValue", option) && option)
options |= WebKitMutationObserver::AttributeOldValue;
if (optionsObject.get("characterDataOldValue", option) && option)
options |= WebKitMutationObserver::CharacterDataOldValue;
ExceptionCode ec = 0;
imp->observe(target, options, attributeFilter, ec);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | v8::Handle<v8::Value> V8WebKitMutationObserver::observeCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebKitMutationObserver.observe");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
WebKitMutationObserver* imp = V8WebKitMutationObserver::toNative(args.Holder());
EXCEPTION_BLOCK(Node*, target, V8Node::HasInstance(args[0]) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0);
if (!args[1]->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
Dictionary optionsObject(args[1]);
unsigned options = 0;
HashSet<AtomicString> attributeFilter;
bool option;
if (optionsObject.get("childList", option) && option)
options |= WebKitMutationObserver::ChildList;
if (optionsObject.get("attributes", option) && option)
options |= WebKitMutationObserver::Attributes;
if (optionsObject.get("attributeFilter", attributeFilter))
options |= WebKitMutationObserver::AttributeFilter;
if (optionsObject.get("characterData", option) && option)
options |= WebKitMutationObserver::CharacterData;
if (optionsObject.get("subtree", option) && option)
options |= WebKitMutationObserver::Subtree;
if (optionsObject.get("attributeOldValue", option) && option)
options |= WebKitMutationObserver::AttributeOldValue;
if (optionsObject.get("characterDataOldValue", option) && option)
options |= WebKitMutationObserver::CharacterDataOldValue;
ExceptionCode ec = 0;
imp->observe(target, options, attributeFilter, ec);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
| 171,132 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: elm_main(int argc, char *argv[])
{
int args = 1;
unsigned char quitOption = 0;
Browser_Window *window;
Ecore_Getopt_Value values[] = {
ECORE_GETOPT_VALUE_STR(evas_engine_name),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(frame_flattening_enabled),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_NONE
};
if (!ewk_init())
return EXIT_FAILURE;
ewk_view_smart_class_set(miniBrowserViewSmartClass());
ecore_app_args_set(argc, (const char **) argv);
args = ecore_getopt_parse(&options, values, argc, argv);
if (args < 0)
return quit(EINA_FALSE, "ERROR: could not parse options.\n");
if (quitOption)
return quit(EINA_TRUE, NULL);
if (evas_engine_name)
elm_config_preferred_engine_set(evas_engine_name);
#if defined(WTF_USE_ACCELERATED_COMPOSITING) && defined(HAVE_ECORE_X)
else {
evas_engine_name = "opengl_x11";
elm_config_preferred_engine_set(evas_engine_name);
}
#endif
Ewk_Context *context = ewk_context_default_get();
ewk_context_favicon_database_directory_set(context, NULL);
if (args < argc) {
char *url = url_from_user_input(argv[args]);
window = window_create(url);
free(url);
} else
window = window_create(DEFAULT_URL);
if (!window)
return quit(EINA_FALSE, "ERROR: could not create browser window.\n");
windows = eina_list_append(windows, window);
elm_run();
return quit(EINA_TRUE, NULL);
}
Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser
https://bugs.webkit.org/show_bug.cgi?id=100942
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05
Reviewed by Kenneth Rohde Christiansen.
Added window-size (-s) command line option to EFL MiniBrowser.
* MiniBrowser/efl/main.c:
(window_create):
(parse_window_size):
(elm_main):
git-svn-id: svn://svn.chromium.org/blink/trunk@133450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | elm_main(int argc, char *argv[])
{
int args = 1;
unsigned char quitOption = 0;
Browser_Window *window;
char *window_size_string = NULL;
Ecore_Getopt_Value values[] = {
ECORE_GETOPT_VALUE_STR(evas_engine_name),
ECORE_GETOPT_VALUE_STR(window_size_string),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(frame_flattening_enabled),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_BOOL(quitOption),
ECORE_GETOPT_VALUE_NONE
};
if (!ewk_init())
return EXIT_FAILURE;
ewk_view_smart_class_set(miniBrowserViewSmartClass());
ecore_app_args_set(argc, (const char **) argv);
args = ecore_getopt_parse(&options, values, argc, argv);
if (args < 0)
return quit(EINA_FALSE, "ERROR: could not parse options.\n");
if (quitOption)
return quit(EINA_TRUE, NULL);
if (evas_engine_name)
elm_config_preferred_engine_set(evas_engine_name);
#if defined(WTF_USE_ACCELERATED_COMPOSITING) && defined(HAVE_ECORE_X)
else {
evas_engine_name = "opengl_x11";
elm_config_preferred_engine_set(evas_engine_name);
}
#endif
Ewk_Context *context = ewk_context_default_get();
ewk_context_favicon_database_directory_set(context, NULL);
if (window_size_string)
parse_window_size(window_size_string, &window_width, &window_height);
if (args < argc) {
char *url = url_from_user_input(argv[args]);
window = window_create(url);
free(url);
} else
window = window_create(DEFAULT_URL);
if (!window)
return quit(EINA_FALSE, "ERROR: could not create browser window.\n");
windows = eina_list_append(windows, window);
elm_run();
return quit(EINA_TRUE, NULL);
}
| 170,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DocumentWriter::setDecoder(TextResourceDecoder* decoder)
{
m_decoder = decoder;
}
Commit Message: Remove DocumentWriter::setDecoder as a grep of WebKit shows no callers
https://bugs.webkit.org/show_bug.cgi?id=67803
Reviewed by Adam Barth.
Smells like dead code.
* loader/DocumentWriter.cpp:
* loader/DocumentWriter.h:
git-svn-id: svn://svn.chromium.org/blink/trunk@94800 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void DocumentWriter::setDecoder(TextResourceDecoder* decoder)
| 170,318 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval *rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && (*p)[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 554 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 884 "ext/standard/var_unserializer.re"
{ return 0; }
#line 580 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 878 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 629 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych != ':') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 733 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
zend_long elements;
char *str;
zend_string *class_name;
zend_class_entry *ce;
int incomplete_class = 0;
int custom_object = 0;
zval user_func;
zval retval;
zval args[1];
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = zend_string_init(str, len, 0);
do {
if(!unserialize_allowed_class(class_name, classes)) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Try to find class directly */
BG(serialize_lock)++;
ce = zend_lookup_class(class_name);
if (ce) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
ZVAL_STRING(&user_func, PG(unserialize_callback_func));
ZVAL_STR_COPY(&args[0], class_name);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
}
BG(serialize_lock)--;
zval_ptr_dtor(&retval);
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
/* The callback function may have defined the class */
if ((ce = zend_lookup_class(class_name)) == NULL) {
php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 804 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 726 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 836 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 702 "ext/standard/var_unserializer.re"
{
zend_long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
array_init_size(rval, elements);
if (elements) {
/* we can't convert from packed to hash during unserialization, because
reference to some zvals might be keept in var_hash (to support references) */
zend_hash_real_init(Z_ARRVAL_P(rval), 0);
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 881 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 668 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
zend_string *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
zend_string_free(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STR(rval, str);
return 1;
}
#line 936 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 636 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STRINGL(rval, str, len);
return 1;
}
#line 989 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 627 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
use_double:
#endif
*p = YYCURSOR;
ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1086 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 611 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
if (!strncmp((char*)start + 2, "NAN", 3)) {
ZVAL_DOUBLE(rval, php_get_nan());
} else if (!strncmp((char*)start + 2, "INF", 3)) {
ZVAL_DOUBLE(rval, php_get_inf());
} else if (!strncmp((char*)start + 2, "-INF", 4)) {
ZVAL_DOUBLE(rval, -php_get_inf());
} else {
ZVAL_NULL(rval);
}
return 1;
}
#line 1161 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large zend_long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
ZVAL_LONG(rval, parse_iv(start + 2));
return 1;
}
#line 1214 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 579 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_BOOL(rval, parse_iv(start + 2));
return 1;
}
#line 1228 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 573 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_NULL(rval);
return 1;
}
#line 1237 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 548 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
if (rval_ref == rval) {
return 0;
}
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
ZVAL_COPY(rval, rval_ref);
return 1;
}
#line 1285 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 522 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
zval_ptr_dtor(rval);
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
if (Z_ISREF_P(rval_ref)) {
ZVAL_COPY(rval, rval_ref);
} else {
ZVAL_NEW_REF(rval_ref, rval_ref);
ZVAL_COPY(rval, rval_ref);
}
return 1;
}
#line 1334 "ext/standard/var_unserializer.c"
}
#line 886 "ext/standard/var_unserializer.re"
return 0;
}
Commit Message: Fix bug #72663 - destroy broken object when unserializing
(cherry picked from commit 448c9be157f4147e121f1a2a524536c75c9c6059)
CWE ID: CWE-502 | static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval *rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && (*p)[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 554 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 884 "ext/standard/var_unserializer.re"
{ return 0; }
#line 580 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 878 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 629 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 733 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
zend_long elements;
char *str;
zend_string *class_name;
zend_class_entry *ce;
int incomplete_class = 0;
int custom_object = 0;
zval user_func;
zval retval;
zval args[1];
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = zend_string_init(str, len, 0);
do {
if(!unserialize_allowed_class(class_name, classes)) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Try to find class directly */
BG(serialize_lock)++;
ce = zend_lookup_class(class_name);
if (ce) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
ZVAL_STRING(&user_func, PG(unserialize_callback_func));
ZVAL_STR_COPY(&args[0], class_name);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
}
BG(serialize_lock)--;
zval_ptr_dtor(&retval);
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
/* The callback function may have defined the class */
if ((ce = zend_lookup_class(class_name)) == NULL) {
php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 805 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 726 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 837 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 702 "ext/standard/var_unserializer.re"
{
zend_long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
array_init_size(rval, elements);
if (elements) {
/* we can't convert from packed to hash during unserialization, because
reference to some zvals might be keept in var_hash (to support references) */
zend_hash_real_init(Z_ARRVAL_P(rval), 0);
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 882 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 668 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
zend_string *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
zend_string_free(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STR(rval, str);
return 1;
}
#line 937 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 636 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STRINGL(rval, str, len);
return 1;
}
#line 990 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 627 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
use_double:
#endif
*p = YYCURSOR;
ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1087 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 611 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
if (!strncmp((char*)start + 2, "NAN", 3)) {
ZVAL_DOUBLE(rval, php_get_nan());
} else if (!strncmp((char*)start + 2, "INF", 3)) {
ZVAL_DOUBLE(rval, php_get_inf());
} else if (!strncmp((char*)start + 2, "-INF", 4)) {
ZVAL_DOUBLE(rval, -php_get_inf());
} else {
ZVAL_NULL(rval);
}
return 1;
}
#line 1162 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large zend_long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
ZVAL_LONG(rval, parse_iv(start + 2));
return 1;
}
#line 1215 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 579 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_BOOL(rval, parse_iv(start + 2));
return 1;
}
#line 1229 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 573 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_NULL(rval);
return 1;
}
#line 1238 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 548 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
if (rval_ref == rval) {
return 0;
}
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
ZVAL_COPY(rval, rval_ref);
return 1;
}
#line 1286 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 522 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
zval_ptr_dtor(rval);
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
if (Z_ISREF_P(rval_ref)) {
ZVAL_COPY(rval, rval_ref);
} else {
ZVAL_NEW_REF(rval_ref, rval_ref);
ZVAL_COPY(rval, rval_ref);
}
return 1;
}
#line 1335 "ext/standard/var_unserializer.c"
}
#line 886 "ext/standard/var_unserializer.re"
return 0;
}
| 166,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FT_Bitmap_Copy( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target)
{
FT_Memory memory = library->memory;
FT_Error error = FT_Err_Ok;
FT_Int pitch = source->pitch;
FT_ULong size;
if ( source == target )
return FT_Err_Ok;
if ( source->buffer == NULL )
{
*target = *source;
return FT_Err_Ok;
}
if ( pitch < 0 )
pitch = -pitch;
size = (FT_ULong)( pitch * source->rows );
if ( target->buffer )
{
FT_Int target_pitch = target->pitch;
FT_ULong target_size;
if ( target_pitch < 0 )
target_pitch = -target_pitch;
target_size = (FT_ULong)( target_pitch * target->rows );
if ( target_size != size )
(void)FT_QREALLOC( target->buffer, target_size, size );
}
else
(void)FT_QALLOC( target->buffer, size );
if ( !error )
{
unsigned char *p;
p = target->buffer;
*target = *source;
target->buffer = p;
FT_MEM_COPY( target->buffer, source->buffer, size );
}
return error;
}
Commit Message:
CWE ID: CWE-119 | FT_Bitmap_Copy( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target)
{
FT_Memory memory = library->memory;
FT_Error error = FT_Err_Ok;
FT_Int pitch = source->pitch;
FT_ULong size;
if ( source == target )
return FT_Err_Ok;
if ( source->buffer == NULL )
{
*target = *source;
return FT_Err_Ok;
}
if ( pitch < 0 )
pitch = -pitch;
size = (FT_ULong)pitch * source->rows;
if ( target->buffer )
{
FT_Int target_pitch = target->pitch;
FT_ULong target_size;
if ( target_pitch < 0 )
target_pitch = -target_pitch;
target_size = (FT_ULong)target_pitch * target->rows;
if ( target_size != size )
(void)FT_QREALLOC( target->buffer, target_size, size );
}
else
(void)FT_QALLOC( target->buffer, size );
if ( !error )
{
unsigned char *p;
p = target->buffer;
*target = *source;
target->buffer = p;
FT_MEM_COPY( target->buffer, source->buffer, size );
}
return error;
}
| 164,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
Commit Message:
CWE ID: CWE-416 | add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
| 164,579 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int su3000_power_ctrl(struct dvb_usb_device *d, int i)
{
struct dw2102_state *state = (struct dw2102_state *)d->priv;
u8 obuf[] = {0xde, 0};
info("%s: %d, initialized %d", __func__, i, state->initialized);
if (i && !state->initialized) {
state->initialized = 1;
/* reset board */
return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0);
}
return 0;
}
Commit Message: [media] dw2102: don't do DMA on stack
On Kernel 4.9, WARNINGs about doing DMA on stack are hit at
the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach().
Both were due to the use of buffers on the stack as parameters to
dvb_usb_generic_rw() and the resulting attempt to do DMA with them.
The device was non-functional as a result.
So, switch this driver over to use a buffer within the device state
structure, as has been done with other DVB-USB drivers.
Tested with TechnoTrend TT-connect S2-4600.
[[email protected]: fixed a warning at su3000_i2c_transfer() that
state var were dereferenced before check 'd']
Signed-off-by: Jonathan McDowell <[email protected]>
Cc: <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int su3000_power_ctrl(struct dvb_usb_device *d, int i)
{
struct dw2102_state *state = (struct dw2102_state *)d->priv;
int ret = 0;
info("%s: %d, initialized %d", __func__, i, state->initialized);
if (i && !state->initialized) {
mutex_lock(&d->data_mutex);
state->data[0] = 0xde;
state->data[1] = 0;
state->initialized = 1;
/* reset board */
ret = dvb_usb_generic_rw(d, state->data, 2, NULL, 0, 0);
mutex_unlock(&d->data_mutex);
}
return ret;
}
| 168,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pte_t *page_table, pmd_t *pmd,
unsigned int flags, pte_t orig_pte)
{
pgoff_t pgoff = (((address & PAGE_MASK)
- vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
pte_unmap(page_table);
if (!(flags & FAULT_FLAG_WRITE))
return do_read_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
if (!(vma->vm_flags & VM_SHARED))
return do_cow_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
}
Commit Message: mm: avoid setting up anonymous pages into file mapping
Reading page fault handler code I've noticed that under right
circumstances kernel would map anonymous pages into file mappings: if
the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated
on ->mmap(), kernel would handle page fault to not populated pte with
do_anonymous_page().
Let's change page fault handler to use do_anonymous_page() only on
anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not
shared.
For file mappings without vm_ops->fault() or shred VMA without vm_ops,
page fault on pte_none() entry would lead to SIGBUS.
Signed-off-by: Kirill A. Shutemov <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | static int do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pte_t *page_table, pmd_t *pmd,
unsigned int flags, pte_t orig_pte)
{
pgoff_t pgoff = (((address & PAGE_MASK)
- vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
pte_unmap(page_table);
/* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
if (!vma->vm_ops->fault)
return VM_FAULT_SIGBUS;
if (!(flags & FAULT_FLAG_WRITE))
return do_read_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
if (!(vma->vm_flags & VM_SHARED))
return do_cow_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
}
| 167,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DataReductionProxySettings::IsDataSaverEnabledByUser() const {
//// static
if (params::ShouldForceEnableDataReductionProxy())
return true;
if (spdy_proxy_auth_enabled_.GetPrefName().empty())
return false;
return spdy_proxy_auth_enabled_.GetValue();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | bool DataReductionProxySettings::IsDataSaverEnabledByUser() const {
//// static
bool DataReductionProxySettings::IsDataSaverEnabledByUser(PrefService* prefs) {
if (params::ShouldForceEnableDataReductionProxy())
return true;
return prefs && prefs->GetBoolean(prefs::kDataSaverEnabled);
}
| 172,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> getObjectParameter(const v8::Arguments& args, ObjectType objectType)
{
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned target = toInt32(args[0]);
unsigned pname = toInt32(args[1]);
WebGLGetInfo info;
switch (objectType) {
case kBuffer:
info = context->getBufferParameter(target, pname, ec);
break;
case kRenderbuffer:
info = context->getRenderbufferParameter(target, pname, ec);
break;
case kTexture:
info = context->getTexParameter(target, pname, ec);
break;
case kVertexAttrib:
info = context->getVertexAttrib(target, pname, ec);
break;
default:
notImplemented();
break;
}
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> getObjectParameter(const v8::Arguments& args, ObjectType objectType)
{
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned target = toInt32(args[0]);
unsigned pname = toInt32(args[1]);
WebGLGetInfo info;
switch (objectType) {
case kBuffer:
info = context->getBufferParameter(target, pname, ec);
break;
case kRenderbuffer:
info = context->getRenderbufferParameter(target, pname, ec);
break;
case kTexture:
info = context->getTexParameter(target, pname, ec);
break;
case kVertexAttrib:
info = context->getVertexAttrib(target, pname, ec);
break;
default:
notImplemented();
break;
}
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
| 171,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
#ifdef __ANDROID__
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
#endif
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
Commit Message: Decoder: Fixed incorrect use of mmco parameters.
Added extra structure to read mmco values and copied only once per
picture.
Bug: 65735716
Change-Id: I25b08a37bc78342042c52957774b089abce1a54b
(cherry picked from commit 3c70b9a190875938fc57164d9295a3ec791554df)
CWE ID: CWE-20 | WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = &(ps_dec->s_dpb_cmds_scratch);
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
#ifdef __ANDROID__
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
#endif
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
| 174,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Cluster::~Cluster()
{
if (m_entries_count <= 0)
return;
BlockEntry** i = m_entries;
BlockEntry** const j = m_entries + m_entries_count;
while (i != j)
{
BlockEntry* p = *i++;
assert(p);
delete p;
}
delete[] m_entries;
}
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 | Cluster::~Cluster()
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
pos = block_stop; // consume block-part of block group
assert(pos <= payload_stop);
}
assert(pos == payload_stop);
status = CreateBlock(0x20, // BlockGroup ID
payload_start, payload_size, discard_padding);
if (status != 0)
return status;
m_pos = payload_stop;
return 0; // success
}
| 174,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/553
CWE ID: CWE-772 | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
quantum_info=(QuantumInfo *) NULL;
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=(ImageInfo *) NULL;
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
{
MATLAB_KO:
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))
goto MATLAB_KO;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
clone_info=CloneImageInfo(image_info);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
| 167,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: kg_unseal(minor_status, context_handle, input_token_buffer,
message_buffer, conf_state, qop_state, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_token_buffer;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
unsigned int bodysize;
int err;
int toktype2;
int vfyflags = 0;
OM_uint32 ret;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* parse the token, leave the data in message_buffer, setting conf_state */
/* verify the header */
ptr = (unsigned char *) input_token_buffer->value;
err = g_verify_token_header(ctx->mech_used,
&bodysize, &ptr, -1,
input_token_buffer->length,
vfyflags);
if (err) {
*minor_status = err;
return GSS_S_DEFECTIVE_TOKEN;
}
if (bodysize < 2) {
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
return GSS_S_DEFECTIVE_TOKEN;
}
toktype2 = load_16_be(ptr);
ptr += 2;
bodysize -= 2;
switch (toktype2) {
case KG2_TOK_MIC_MSG:
case KG2_TOK_WRAP_MSG:
case KG2_TOK_DEL_CTX:
ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,
ptr, bodysize, message_buffer,
conf_state, qop_state, toktype);
break;
case KG_TOK_MIC_MSG:
case KG_TOK_WRAP_MSG:
case KG_TOK_DEL_CTX:
ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,
message_buffer, conf_state, qop_state,
toktype);
break;
default:
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
ret = GSS_S_DEFECTIVE_TOKEN;
break;
}
if (ret != 0)
save_error_info (*minor_status, ctx->k5_context);
return ret;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | kg_unseal(minor_status, context_handle, input_token_buffer,
message_buffer, conf_state, qop_state, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_token_buffer;
gss_buffer_t message_buffer;
int *conf_state;
gss_qop_t *qop_state;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
unsigned char *ptr;
unsigned int bodysize;
int err;
int toktype2;
int vfyflags = 0;
OM_uint32 ret;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* parse the token, leave the data in message_buffer, setting conf_state */
/* verify the header */
ptr = (unsigned char *) input_token_buffer->value;
err = g_verify_token_header(ctx->mech_used,
&bodysize, &ptr, -1,
input_token_buffer->length,
vfyflags);
if (err) {
*minor_status = err;
return GSS_S_DEFECTIVE_TOKEN;
}
if (bodysize < 2) {
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
return GSS_S_DEFECTIVE_TOKEN;
}
toktype2 = load_16_be(ptr);
ptr += 2;
bodysize -= 2;
switch (toktype2) {
case KG2_TOK_MIC_MSG:
case KG2_TOK_WRAP_MSG:
case KG2_TOK_DEL_CTX:
ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,
ptr, bodysize, message_buffer,
conf_state, qop_state, toktype);
break;
case KG_TOK_MIC_MSG:
case KG_TOK_WRAP_MSG:
case KG_TOK_DEL_CTX:
ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,
message_buffer, conf_state, qop_state,
toktype);
break;
default:
*minor_status = (OM_uint32)G_BAD_TOK_HEADER;
ret = GSS_S_DEFECTIVE_TOKEN;
break;
}
if (ret != 0)
save_error_info (*minor_status, ctx->k5_context);
return ret;
}
| 166,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: vrrp_tfile_end_handler(void)
{
vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);
struct stat statb;
FILE *tf;
int ret;
if (!tfile->file_path) {
report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname);
free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);
return;
}
if (track_file_init == TRACK_FILE_NO_INIT)
return;
ret = stat(tfile->file_path, &statb);
if (!ret) {
if (track_file_init == TRACK_FILE_CREATE) {
/* The file exists */
return;
}
if ((statb.st_mode & S_IFMT) != S_IFREG) {
/* It is not a regular file */
report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname);
return;
}
/* Don't overwrite a file on reload */
if (reload)
return;
}
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
/* Write the value to the file */
if ((tf = fopen(tfile->file_path, "w"))) {
fprintf(tf, "%d\n", track_file_init_value);
fclose(tf);
}
else
report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname);
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | vrrp_tfile_end_handler(void)
{
vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);
struct stat statb;
FILE *tf;
int ret;
if (!tfile->file_path) {
report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname);
free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);
return;
}
if (track_file_init == TRACK_FILE_NO_INIT)
return;
ret = stat(tfile->file_path, &statb);
if (!ret) {
if (track_file_init == TRACK_FILE_CREATE) {
/* The file exists */
return;
}
if ((statb.st_mode & S_IFMT) != S_IFREG) {
/* It is not a regular file */
report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname);
return;
}
/* Don't overwrite a file on reload */
if (reload)
return;
}
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
/* Write the value to the file */
if ((tf = fopen_safe(tfile->file_path, "w"))) {
fprintf(tf, "%d\n", track_file_init_value);
fclose(tf);
}
else
report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname);
}
}
| 168,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
bool is_new_navigation) {
DocumentState* document_state =
DocumentState::FromDataSource(frame->dataSource());
NavigationState* navigation_state = document_state->navigation_state();
if (document_state->commit_load_time().is_null())
document_state->set_commit_load_time(Time::Now());
if (is_new_navigation) {
UpdateSessionHistory(frame);
page_id_ = next_page_id_++;
if (GetLoadingUrl(frame) != GURL("about:swappedout")) {
history_list_offset_++;
if (history_list_offset_ >= content::kMaxSessionHistoryEntries)
history_list_offset_ = content::kMaxSessionHistoryEntries - 1;
history_list_length_ = history_list_offset_ + 1;
history_page_ids_.resize(history_list_length_, -1);
history_page_ids_[history_list_offset_] = page_id_;
}
} else {
if (navigation_state->pending_page_id() != -1 &&
navigation_state->pending_page_id() != page_id_ &&
!navigation_state->request_committed()) {
UpdateSessionHistory(frame);
page_id_ = navigation_state->pending_page_id();
history_list_offset_ = navigation_state->pending_history_list_offset();
DCHECK(history_list_length_ <= 0 ||
history_list_offset_ < 0 ||
history_list_offset_ >= history_list_length_ ||
history_page_ids_[history_list_offset_] == page_id_);
}
}
FOR_EACH_OBSERVER(RenderViewObserver, observers_,
DidCommitProvisionalLoad(frame, is_new_navigation));
navigation_state->set_request_committed(true);
UpdateURL(frame);
completed_client_redirect_src_ = Referrer();
UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
bool is_new_navigation) {
DocumentState* document_state =
DocumentState::FromDataSource(frame->dataSource());
NavigationState* navigation_state = document_state->navigation_state();
if (document_state->commit_load_time().is_null())
document_state->set_commit_load_time(Time::Now());
if (is_new_navigation) {
UpdateSessionHistory(frame);
page_id_ = next_page_id_++;
// Don't update history_page_ids_ (etc) for chrome::kSwappedOutURL, since
// we don't want to forget the entry that was there, and since we will
// never come back to chrome::kSwappedOutURL. Note that we have to call
if (GetLoadingUrl(frame) != GURL(chrome::kSwappedOutURL)) {
history_list_offset_++;
if (history_list_offset_ >= content::kMaxSessionHistoryEntries)
history_list_offset_ = content::kMaxSessionHistoryEntries - 1;
history_list_length_ = history_list_offset_ + 1;
history_page_ids_.resize(history_list_length_, -1);
history_page_ids_[history_list_offset_] = page_id_;
}
} else {
if (navigation_state->pending_page_id() != -1 &&
navigation_state->pending_page_id() != page_id_ &&
!navigation_state->request_committed()) {
UpdateSessionHistory(frame);
page_id_ = navigation_state->pending_page_id();
history_list_offset_ = navigation_state->pending_history_list_offset();
DCHECK(history_list_length_ <= 0 ||
history_list_offset_ < 0 ||
history_list_offset_ >= history_list_length_ ||
history_page_ids_[history_list_offset_] == page_id_);
}
}
FOR_EACH_OBSERVER(RenderViewObserver, observers_,
DidCommitProvisionalLoad(frame, is_new_navigation));
navigation_state->set_request_committed(true);
UpdateURL(frame);
completed_client_redirect_src_ = Referrer();
UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}
| 171,033 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group_count;
ext4_group_t flex_group;
int groups_per_flex = 0;
size_t size;
int i;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex < 2) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
/* We allocate both existing and potentially added groups */
flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +
((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) <<
EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex;
size = flex_group_count * sizeof(struct flex_groups);
sbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (sbi->s_flex_groups == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory for %u flex groups",
flex_group_count);
goto failed;
}
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info()
Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by
zero when trying to mount a corrupted file system") fixes CVE-2009-4307
by performing a sanity check on s_log_groups_per_flex, since it can be
set to a bogus value by an attacker.
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex < 2) { ... }
This patch fixes two potential issues in the previous commit.
1) The sanity check might only work on architectures like PowerPC.
On x86, 5 bits are used for the shifting amount. That means, given a
large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36
is essentially 1 << 4 = 16, rather than 0. This will bypass the check,
leaving s_log_groups_per_flex and groups_per_flex inconsistent.
2) The sanity check relies on undefined behavior, i.e., oversized shift.
A standard-confirming C compiler could rewrite the check in unexpected
ways. Consider the following equivalent form, assuming groups_per_flex
is unsigned for simplicity.
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex == 0 || groups_per_flex == 1) {
We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will
completely optimize away the check groups_per_flex == 0, leaving the
patched code as vulnerable as the original. GCC keeps the check, but
there is no guarantee that future versions will do the same.
Signed-off-by: Xi Wang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-189 | static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group_count;
ext4_group_t flex_group;
unsigned int groups_per_flex = 0;
size_t size;
int i;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
/* We allocate both existing and potentially added groups */
flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +
((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) <<
EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex;
size = flex_group_count * sizeof(struct flex_groups);
sbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (sbi->s_flex_groups == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory for %u flex groups",
flex_group_count);
goto failed;
}
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
| 165,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
size_t imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
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> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
unsigned imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
| 172,503 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
Commit Message: avcodec/idctdsp: Transmit studio_profile to init instead of using AVCodecContext profile
These 2 fields are not always the same, it is simpler to always use the same field
for detecting studio profile
Fixes: null pointer dereference
Fixes: ffmpeg_crash_3.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (c->mpeg4_studio_profile)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
| 169,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ext4_xattr_destroy_cache(struct mb_cache *cache)
{
if (cache)
mb_cache_destroy(cache);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | void ext4_xattr_destroy_cache(struct mb_cache *cache)
void ext4_xattr_destroy_cache(struct mb2_cache *cache)
{
if (cache)
mb2_cache_destroy(cache);
}
| 169,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::RequestPasskey(
const dbus::ObjectPath& device_path,
const PasskeyCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestPasskey";
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_REQUEST_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(passkey_callback_.is_null());
passkey_callback_ = callback;
pairing_delegate_->RequestPasskey(this);
pairing_delegate_used_ = true;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::RequestPasskey(
| 171,236 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ObjectBackedNativeHandler::RouteFunction(
const std::string& name,
const std::string& feature_name,
const HandlerFunction& handler_function) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context_->v8_context());
v8::Local<v8::Object> data = v8::Object::New(isolate);
SetPrivate(data, kHandlerFunction,
v8::External::New(isolate, new HandlerFunction(handler_function)));
SetPrivate(data, kFeatureName,
v8_helpers::ToV8StringUnsafe(isolate, feature_name));
v8::Local<v8::FunctionTemplate> function_template =
v8::FunctionTemplate::New(isolate, Router, data);
v8::Local<v8::ObjectTemplate>::New(isolate, object_template_)
->Set(isolate, name.c_str(), function_template);
router_data_.Append(data);
}
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: | void ObjectBackedNativeHandler::RouteFunction(
const std::string& name,
const std::string& feature_name,
const HandlerFunction& handler_function) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context_->v8_context());
v8::Local<v8::Object> data = v8::Object::New(isolate);
SetPrivate(data, kHandlerFunction,
v8::External::New(isolate, new HandlerFunction(handler_function)));
DCHECK(feature_name.empty() ||
ExtensionAPI::GetSharedInstance()->GetFeatureDependency(feature_name))
<< feature_name;
SetPrivate(data, kFeatureName,
v8_helpers::ToV8StringUnsafe(isolate, feature_name));
v8::Local<v8::FunctionTemplate> function_template =
v8::FunctionTemplate::New(isolate, Router, data);
v8::Local<v8::ObjectTemplate>::New(isolate, object_template_)
->Set(isolate, name.c_str(), function_template);
router_data_.Append(data);
}
| 173,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: float AudioParam::finalValue()
{
float value;
calculateFinalValues(&value, 1, false);
return value;
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | float AudioParam::finalValue()
{
float value = m_value;
calculateFinalValues(&value, 1, false);
return value;
}
| 171,659 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
struct user_namespace *user_ns)
{
mm->mmap = NULL;
mm->mm_rb = RB_ROOT;
mm->vmacache_seqnum = 0;
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->core_state = NULL;
atomic_long_set(&mm->nr_ptes, 0);
mm_nr_pmds_init(mm);
mm->map_count = 0;
mm->locked_vm = 0;
mm->pinned_vm = 0;
memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
spin_lock_init(&mm->page_table_lock);
mm_init_cpumask(mm);
mm_init_aio(mm);
mm_init_owner(mm, p);
mmu_notifier_mm_init(mm);
init_tlb_flush_pending(mm);
#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
mm->pmd_huge_pte = NULL;
#endif
if (current->mm) {
mm->flags = current->mm->flags & MMF_INIT_MASK;
mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
} else {
mm->flags = default_dump_filter;
mm->def_flags = 0;
}
if (mm_alloc_pgd(mm))
goto fail_nopgd;
if (init_new_context(p, mm))
goto fail_nocontext;
mm->user_ns = get_user_ns(user_ns);
return mm;
fail_nocontext:
mm_free_pgd(mm);
fail_nopgd:
free_mm(mm);
return NULL;
}
Commit Message: fork: fix incorrect fput of ->exe_file causing use-after-free
Commit 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for
write killable") made it possible to kill a forking task while it is
waiting to acquire its ->mmap_sem for write, in dup_mmap().
However, it was overlooked that this introduced an new error path before
a reference is taken on the mm_struct's ->exe_file. Since the
->exe_file of the new mm_struct was already set to the old ->exe_file by
the memcpy() in dup_mm(), it was possible for the mmput() in the error
path of dup_mm() to drop a reference to ->exe_file which was never
taken.
This caused the struct file to later be freed prematurely.
Fix it by updating mm_init() to NULL out the ->exe_file, in the same
place it clears other things like the list of mmaps.
This bug was found by syzkaller. It can be reproduced using the
following C program:
#define _GNU_SOURCE
#include <pthread.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
static void *mmap_thread(void *_arg)
{
for (;;) {
mmap(NULL, 0x1000000, PROT_READ,
MAP_POPULATE|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
}
}
static void *fork_thread(void *_arg)
{
usleep(rand() % 10000);
fork();
}
int main(void)
{
fork();
fork();
fork();
for (;;) {
if (fork() == 0) {
pthread_t t;
pthread_create(&t, NULL, mmap_thread, NULL);
pthread_create(&t, NULL, fork_thread, NULL);
usleep(rand() % 10000);
syscall(__NR_exit_group, 0);
}
wait(NULL);
}
}
No special kernel config options are needed. It usually causes a NULL
pointer dereference in __remove_shared_vm_struct() during exit, or in
dup_mmap() (which is usually inlined into copy_process()) during fork.
Both are due to a vm_area_struct's ->vm_file being used after it's
already been freed.
Google Bug Id: 64772007
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 7c051267931a ("mm, fork: make dup_mmap wait for mmap_sem for write killable")
Signed-off-by: Eric Biggers <[email protected]>
Tested-by: Mark Rutland <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Konstantin Khlebnikov <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: <[email protected]> [v4.7+]
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
struct user_namespace *user_ns)
{
mm->mmap = NULL;
mm->mm_rb = RB_ROOT;
mm->vmacache_seqnum = 0;
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->core_state = NULL;
atomic_long_set(&mm->nr_ptes, 0);
mm_nr_pmds_init(mm);
mm->map_count = 0;
mm->locked_vm = 0;
mm->pinned_vm = 0;
memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
spin_lock_init(&mm->page_table_lock);
mm_init_cpumask(mm);
mm_init_aio(mm);
mm_init_owner(mm, p);
RCU_INIT_POINTER(mm->exe_file, NULL);
mmu_notifier_mm_init(mm);
init_tlb_flush_pending(mm);
#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
mm->pmd_huge_pte = NULL;
#endif
if (current->mm) {
mm->flags = current->mm->flags & MMF_INIT_MASK;
mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
} else {
mm->flags = default_dump_filter;
mm->def_flags = 0;
}
if (mm_alloc_pgd(mm))
goto fail_nopgd;
if (init_new_context(p, mm))
goto fail_nocontext;
mm->user_ns = get_user_ns(user_ns);
return mm;
fail_nocontext:
mm_free_pgd(mm);
fail_nopgd:
free_mm(mm);
return NULL;
}
| 167,656 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetUpCacheMetadata() {
metadata_.reset(new GDataCacheMetadataMap(
NULL, base::SequencedWorkerPool::SequenceToken()));
metadata_->Initialize(cache_paths_);
}
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 SetUpCacheMetadata() {
metadata_.reset(new GDataCacheMetadataMap(
NULL, base::SequencedWorkerPool::SequenceToken()));
| 170,871 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
return crypto_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
| 170,622 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigCompileInfo* ci, OnigErrorInfo* einfo)
{
int r;
UChar *cpat, *cpat_end;
if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;
if (ci->pattern_enc != ci->target_enc) {
r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end,
&cpat, &cpat_end);
if (r != 0) return r;
}
else {
cpat = (UChar* )pattern;
cpat_end = (UChar* )pattern_end;
}
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) {
r = ONIGERR_MEMORY;
goto err2;
}
r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,
ci->syntax);
if (r != 0) goto err;
r = onig_compile(*reg, cpat, cpat_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
err2:
if (cpat != pattern) xfree(cpat);
return r;
}
Commit Message: Fix CVE-2019-13224: don't allow different encodings for onig_new_deluxe()
CWE ID: CWE-416 | onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigCompileInfo* ci, OnigErrorInfo* einfo)
{
int r;
UChar *cpat, *cpat_end;
if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;
if (ci->pattern_enc != ci->target_enc) {
return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION;
}
else {
cpat = (UChar* )pattern;
cpat_end = (UChar* )pattern_end;
}
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) {
r = ONIGERR_MEMORY;
goto err2;
}
r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,
ci->syntax);
if (r != 0) goto err;
r = onig_compile(*reg, cpat, cpat_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
err2:
if (cpat != pattern) xfree(cpat);
return r;
}
| 169,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AcpiNsTerminate (
void)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsTerminate);
#ifdef ACPI_EXEC_APP
{
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
/* Delete any module-level code blocks */
Next = AcpiGbl_ModuleCodeList;
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */
AcpiUtRemoveReference (Prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);
/* Delete any objects attached to the root node */
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_VOID;
}
AcpiNsDeleteNode (AcpiGbl_RootNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
Commit Message: Namespace: fix operand cache leak
I found some ACPI operand cache leaks in ACPI early abort cases.
Boot log of ACPI operand cache leak is as follows:
>[ 0.174332] ACPI: Added _OSI(Module Device)
>[ 0.175504] ACPI: Added _OSI(Processor Device)
>[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.178284] ACPI: SCI (IRQ16705) allocation failed
>[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install
System Control Interrupt handler (20160930/evevent-131)
>[ 0.180008] ACPI: Unable to start the ACPI Interpreter
>[ 0.181125] ACPI Error: Could not remove SCI handler
(20160930/evmisc-281)
>[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has
objects
>[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2
>[ 0.186820] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS
VirtualBox 12/01/2006
>[ 0.188000] Call Trace:
>[ 0.188000] ? dump_stack+0x5c/0x7d
>[ 0.188000] ? kmem_cache_destroy+0x224/0x230
>[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22
>[ 0.188000] ? acpi_os_delete_cache+0xa/0xd
>[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.188000] ? acpi_terminate+0x5/0xf
>[ 0.188000] ? acpi_init+0x288/0x32e
>[ 0.188000] ? __class_create+0x4c/0x80
>[ 0.188000] ? video_setup+0x7a/0x7a
>[ 0.188000] ? do_one_initcall+0x4e/0x1b0
>[ 0.188000] ? kernel_init_freeable+0x194/0x21a
>[ 0.188000] ? rest_init+0x80/0x80
>[ 0.188000] ? kernel_init+0xa/0x100
>[ 0.188000] ? ret_from_fork+0x25/0x30
When early abort is occurred due to invalid ACPI information, Linux kernel
terminates ACPI by calling AcpiTerminate() function. The function calls
AcpiNsTerminate() function to delete namespace data and ACPI operand cache
(AcpiGbl_ModuleCodeList).
But the deletion code in AcpiNsTerminate() function is wrapped in
ACPI_EXEC_APP definition, therefore the code is only executed when the
definition exists. If the define doesn't exist, ACPI operand cache
(AcpiGbl_ModuleCodeList) is leaked, and stack dump is shown in kernel log.
This causes a security threat because the old kernel (<= 4.9) shows memory
locations of kernel functions in stack dump, therefore kernel ASLR can be
neutralized.
To fix ACPI operand leak for enhancing security, I made a patch which
removes the ACPI_EXEC_APP define in AcpiNsTerminate() function for
executing the deletion code unconditionally.
Signed-off-by: Seunghun Han <[email protected]>
Signed-off-by: Lv Zheng <[email protected]>
CWE ID: CWE-755 | AcpiNsTerminate (
void)
{
ACPI_STATUS Status;
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
ACPI_FUNCTION_TRACE (NsTerminate);
/* Delete any module-level code blocks */
Next = AcpiGbl_ModuleCodeList;
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */
AcpiUtRemoveReference (Prev);
}
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);
/* Delete any objects attached to the root node */
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_VOID;
}
AcpiNsDeleteNode (AcpiGbl_RootNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
| 170,039 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
Commit Message:
CWE ID: | int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
if (sanitize_paths) {
sanitize_path(buf, buf, "", 0, SP_DEFAULT);
len = strlen(buf);
}
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
| 164,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioSystemImplTest()
: use_audio_thread_(GetParam()), audio_thread_("AudioSystemThread") {
if (use_audio_thread_) {
audio_thread_.StartAndWaitForTesting();
audio_manager_.reset(
new media::MockAudioManager(audio_thread_.task_runner()));
} else {
audio_manager_.reset(new media::MockAudioManager(
base::ThreadTaskRunnerHandle::Get().get()));
}
audio_manager_->SetInputStreamParameters(
media::AudioParameters::UnavailableDeviceParams());
audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get());
EXPECT_EQ(AudioSystem::Get(), audio_system_.get());
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioSystemImplTest()
: use_audio_thread_(GetParam()),
audio_thread_("AudioSystemThread"),
input_params_(AudioParameters::AUDIO_PCM_LINEAR,
CHANNEL_LAYOUT_MONO,
AudioParameters::kTelephoneSampleRate,
16,
AudioParameters::kTelephoneSampleRate / 10),
output_params_(AudioParameters::AUDIO_PCM_LINEAR,
CHANNEL_LAYOUT_MONO,
AudioParameters::kTelephoneSampleRate,
16,
AudioParameters::kTelephoneSampleRate / 20),
default_output_params_(AudioParameters::AUDIO_PCM_LINEAR,
CHANNEL_LAYOUT_MONO,
AudioParameters::kTelephoneSampleRate,
16,
AudioParameters::kTelephoneSampleRate / 30) {
if (use_audio_thread_) {
audio_thread_.StartAndWaitForTesting();
audio_manager_.reset(
new media::MockAudioManager(audio_thread_.task_runner()));
} else {
audio_manager_.reset(new media::MockAudioManager(
base::ThreadTaskRunnerHandle::Get().get()));
}
audio_manager_->SetInputStreamParameters(input_params_);
audio_manager_->SetOutputStreamParameters(output_params_);
audio_manager_->SetDefaultOutputStreamParameters(default_output_params_);
audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get());
EXPECT_EQ(AudioSystem::Get(), audio_system_.get());
}
| 171,989 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderPassthroughImpl::DoEndQueryEXT(GLenum target,
uint32_t submit_count) {
if (IsEmulatedQueryTarget(target)) {
auto active_query_iter = active_queries_.find(target);
if (active_query_iter == active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "No active query on target.");
return error::kNoError;
}
if (target == GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM &&
!pending_read_pixels_.empty()) {
GLuint query_service_id = active_query_iter->second.service_id;
pending_read_pixels_.back().waiting_async_pack_queries.insert(
query_service_id);
}
} else {
CheckErrorCallbackState();
api()->glEndQueryFn(target);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
DCHECK(active_queries_.find(target) != active_queries_.end());
ActiveQuery active_query = std::move(active_queries_[target]);
active_queries_.erase(target);
PendingQuery pending_query;
pending_query.target = target;
pending_query.service_id = active_query.service_id;
pending_query.shm = std::move(active_query.shm);
pending_query.sync = active_query.sync;
pending_query.submit_count = submit_count;
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
pending_query.commands_completed_fence = gl::GLFence::Create();
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
pending_query.buffer_shadow_update_fence = gl::GLFence::Create();
pending_query.buffer_shadow_updates = std::move(buffer_shadow_updates_);
buffer_shadow_updates_.clear();
break;
default:
break;
}
pending_queries_.push_back(std::move(pending_query));
return ProcessQueries(false);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::DoEndQueryEXT(GLenum target,
uint32_t submit_count) {
if (IsEmulatedQueryTarget(target)) {
auto active_query_iter = active_queries_.find(target);
if (active_query_iter == active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "No active query on target.");
return error::kNoError;
}
if (target == GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM &&
!pending_read_pixels_.empty()) {
GLuint query_service_id = active_query_iter->second.service_id;
pending_read_pixels_.back().waiting_async_pack_queries.insert(
query_service_id);
}
} else {
CheckErrorCallbackState();
api()->glEndQueryFn(target);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
DCHECK(active_queries_.find(target) != active_queries_.end());
ActiveQuery active_query = std::move(active_queries_[target]);
active_queries_.erase(target);
PendingQuery pending_query;
pending_query.target = target;
pending_query.service_id = active_query.service_id;
pending_query.shm = std::move(active_query.shm);
pending_query.sync = active_query.sync;
pending_query.submit_count = submit_count;
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
pending_query.commands_completed_fence = gl::GLFence::Create();
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
pending_query.buffer_shadow_update_fence = gl::GLFence::Create();
pending_query.buffer_shadow_updates = std::move(buffer_shadow_updates_);
buffer_shadow_updates_.clear();
break;
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
pending_query.program_service_id = linking_program_service_id_;
break;
default:
break;
}
pending_queries_.push_back(std::move(pending_query));
return ProcessQueries(false);
}
| 172,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125 | void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
LogParam(p.info(), l);
}
| 172,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PaintArtifactCompositor::MightOverlap(const PendingLayer& layer_a,
const PendingLayer& layer_b) {
PropertyTreeState root_property_tree_state(TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root(),
EffectPaintPropertyNode::Root());
FloatClipRect bounds_a(layer_a.bounds);
GeometryMapper::LocalToAncestorVisualRect(layer_a.property_tree_state,
root_property_tree_state, bounds_a);
FloatClipRect bounds_b(layer_b.bounds);
GeometryMapper::LocalToAncestorVisualRect(layer_b.property_tree_state,
root_property_tree_state, bounds_b);
return bounds_a.Rect().Intersects(bounds_b.Rect());
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | bool PaintArtifactCompositor::MightOverlap(const PendingLayer& layer_a,
const PendingLayer& layer_b) {
FloatClipRect bounds_a(layer_a.bounds);
GeometryMapper::LocalToAncestorVisualRect(
layer_a.property_tree_state, PropertyTreeState::Root(), bounds_a);
FloatClipRect bounds_b(layer_b.bounds);
GeometryMapper::LocalToAncestorVisualRect(
layer_b.property_tree_state, PropertyTreeState::Root(), bounds_b);
return bounds_a.Rect().Intersects(bounds_b.Rect());
}
| 171,814 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void StopCast() {
CastConfigDelegate* cast_config =
Shell::GetInstance()->system_tray_delegate()->GetCastConfigDelegate();
if (cast_config && cast_config->HasCastExtension()) {
cast_config->GetReceiversAndActivities(
base::Bind(&StopCastCallback, cast_config));
}
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79 | void StopCast() {
| 171,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
static u32 __ipv6_select_ident(struct net *net,
const struct in6_addr *dst,
const struct in6_addr *src)
{
const struct {
struct in6_addr dst;
struct in6_addr src;
} __aligned(SIPHASH_ALIGNMENT) combined = {
.dst = *dst,
.src = *src,
};
u32 hash, id;
/* Note the following code is not safe, but this is okay. */
if (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))
get_random_bytes(&net->ipv4.ip_id_key,
sizeof(net->ipv4.ip_id_key));
hash = siphash(&combined, sizeof(combined), &net->ipv4.ip_id_key);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
| 169,717 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
const double rollover_check = m_duration * m_timecodeScale;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int X509_verify(X509 *a, EVP_PKEY *r)
{
return(ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF),a->sig_alg,
a->signature,a->cert_info,r));
}
Commit Message: Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
CVE-2014-8275
Reviewed-by: Emilia Käsper <[email protected]>
CWE ID: CWE-310 | int X509_verify(X509 *a, EVP_PKEY *r)
{
if (X509_ALGOR_cmp(a->sig_alg, a->cert_info->signature))
return 0;
return(ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF),a->sig_alg,
a->signature,a->cert_info,r));
}
| 169,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::FrameNavigationHelper(
RenderFrameHost* plugin_rfh,
int32_t guest_instance_id,
int32_t element_instance_id,
bool is_full_page_plugin,
ExtensionsGuestViewMessageFilter* filter)
: content::WebContentsObserver(
content::WebContents::FromRenderFrameHost(plugin_rfh)),
frame_tree_node_id_(plugin_rfh->GetFrameTreeNodeId()),
guest_instance_id_(guest_instance_id),
element_instance_id_(element_instance_id),
is_full_page_plugin_(is_full_page_plugin),
filter_(filter),
parent_site_instance_(plugin_rfh->GetParent()->GetSiteInstance()),
weak_factory_(this) {
DCHECK(GetGuestView());
NavigateToAboutBlank();
base::PostDelayedTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&ExtensionsGuestViewMessageFilter::FrameNavigationHelper::
CancelPendingTask,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kAttachFailureDelayMS));
}
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::FrameNavigationHelper::FrameNavigationHelper(
| 173,041 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FormAssociatedElement::formRemovedFromTree(const Node* formRoot)
{
ASSERT(m_form);
if (toHTMLElement(this)->highestAncestor() != formRoot)
setForm(0);
}
Commit Message: Fix a crash when a form control is in a past naems map of a demoted form element.
Note that we wanted to add the protector in FormAssociatedElement::setForm(),
but we couldn't do it because it is called from the constructor.
BUG=326854
TEST=automated.
Review URL: https://codereview.chromium.org/105693013
git-svn-id: svn://svn.chromium.org/blink/trunk@163680 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-287 | void FormAssociatedElement::formRemovedFromTree(const Node* formRoot)
{
ASSERT(m_form);
if (toHTMLElement(this)->highestAncestor() == formRoot)
return;
RefPtr<HTMLElement> protector(toHTMLElement(this));
setForm(0);
}
| 171,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g %g %g %g %g %g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_image=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(draw_info->dash_pattern[0] != 0.0) &&
((scale*draw_info->stroke_width) >= MagickEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
Commit Message: Prevent buffer overflow in magick/draw.c
CWE ID: CWE-119 | MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g %g %g %g %g %g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_image=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(draw_info->dash_pattern[0] != 0.0) &&
((scale*draw_info->stroke_width) >= MagickEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
| 167,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_read_finish_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif /* PNG_READ_INTERLACING_SUPPORTED */
png_debug(1, "in png_read_finish_row");
png_ptr->row_number++;
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
png_memset_check(png_ptr, png_ptr->prev_row, 0,
png_ptr->rowbytes + 1);
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (!(png_ptr->num_rows))
continue;
}
else /* if (png_ptr->transformations & PNG_INTERLACE) */
break;
} while (png_ptr->iwidth == 0);
if (png_ptr->pass < 7)
return;
}
#endif /* PNG_READ_INTERLACING_SUPPORTED */
if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IDAT;
#endif
char extra;
int ret;
png_ptr->zstream.next_out = (Byte *)&extra;
png_ptr->zstream.avail_out = (uInt)1;
for (;;)
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_byte chunk_length[4];
png_crc_finish(png_ptr, 0);
png_read_data(png_ptr, chunk_length, 4);
png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression Error");
if (!(png_ptr->zstream.avail_out))
{
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
}
png_ptr->zstream.avail_out = 0;
}
if (png_ptr->idat_size || png_ptr->zstream.avail_in)
png_warning(png_ptr, "Extra compression data.");
inflateReset(&png_ptr->zstream);
png_ptr->mode |= PNG_AFTER_IDAT;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_read_finish_row(png_structp png_ptr)
{
#ifdef PNG_READ_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif /* PNG_READ_INTERLACING_SUPPORTED */
png_debug(1, "in png_read_finish_row");
png_ptr->row_number++;
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
png_memset_check(png_ptr, png_ptr->prev_row, 0,
png_ptr->rowbytes + 1);
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->iwidth = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (!(png_ptr->num_rows))
continue;
}
else /* if (png_ptr->transformations & PNG_INTERLACE) */
break;
} while (png_ptr->iwidth == 0);
if (png_ptr->pass < 7)
return;
}
#endif /* PNG_READ_INTERLACING_SUPPORTED */
if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IDAT;
#endif
char extra;
int ret;
png_ptr->zstream.next_out = (Byte *)&extra;
png_ptr->zstream.avail_out = (uInt)1;
for (;;)
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_byte chunk_length[4];
png_crc_finish(png_ptr, 0);
png_read_data(png_ptr, chunk_length, 4);
png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression Error");
if (!(png_ptr->zstream.avail_out))
{
png_warning(png_ptr, "Extra compressed data.");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
}
png_ptr->zstream.avail_out = 0;
}
if (png_ptr->idat_size || png_ptr->zstream.avail_in)
png_warning(png_ptr, "Extra compression data.");
inflateReset(&png_ptr->zstream);
png_ptr->mode |= PNG_AFTER_IDAT;
}
| 172,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code)
return code;
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617 | kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code) {
*status = "DECODE_PA_S4U_X509_USER";
return code;
}
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
| 168,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, true);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
| 173,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WebPage::touchEvent(const Platform::TouchEvent& event)
{
#if DEBUG_TOUCH_EVENTS
BBLOG(LogLevelCritical, "%s", event.toString().c_str());
#endif
#if ENABLE(TOUCH_EVENTS)
if (!d->m_mainFrame)
return false;
if (d->m_page->defersLoading())
return false;
PluginView* pluginView = d->m_fullScreenPluginView.get();
if (pluginView)
return d->dispatchTouchEventToFullScreenPlugin(pluginView, event);
Platform::TouchEvent tEvent = event;
for (unsigned i = 0; i < event.m_points.size(); i++) {
tEvent.m_points[i].m_pos = d->mapFromTransformed(tEvent.m_points[i].m_pos);
tEvent.m_points[i].m_screenPos = tEvent.m_points[i].m_screenPos;
}
if (event.isSingleTap())
d->m_pluginMayOpenNewTab = true;
else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel)
d->m_pluginMayOpenNewTab = false;
if (tEvent.m_type == Platform::TouchEvent::TouchStart) {
d->clearCachedHitTestResult();
d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]);
Element* elementUnderFatFinger = d->m_touchEventHandler->lastFatFingersResult().nodeAsElementIfApplicable();
if (elementUnderFatFinger)
d->m_touchEventHandler->drawTapHighlight();
}
bool handled = false;
if (!event.m_type != Platform::TouchEvent::TouchInjected)
handled = d->m_mainFrame->eventHandler()->handleTouchEvent(PlatformTouchEvent(&tEvent));
if (d->m_preventDefaultOnTouchStart) {
if (tEvent.m_type == Platform::TouchEvent::TouchEnd || tEvent.m_type == Platform::TouchEvent::TouchCancel)
d->m_preventDefaultOnTouchStart = false;
return true;
}
if (handled) {
if (tEvent.m_type == Platform::TouchEvent::TouchStart)
d->m_preventDefaultOnTouchStart = true;
return true;
}
if (event.isTouchHold())
d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]);
#endif
return false;
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | bool WebPage::touchEvent(const Platform::TouchEvent& event)
{
#if DEBUG_TOUCH_EVENTS
BBLOG(LogLevelCritical, "%s", event.toString().c_str());
#endif
#if ENABLE(TOUCH_EVENTS)
if (!d->m_mainFrame)
return false;
if (d->m_page->defersLoading())
return false;
PluginView* pluginView = d->m_fullScreenPluginView.get();
if (pluginView)
return d->dispatchTouchEventToFullScreenPlugin(pluginView, event);
Platform::TouchEvent tEvent = event;
if (event.isSingleTap())
d->m_pluginMayOpenNewTab = true;
else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel)
d->m_pluginMayOpenNewTab = false;
if (tEvent.m_type == Platform::TouchEvent::TouchStart) {
d->clearCachedHitTestResult();
d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]);
Element* elementUnderFatFinger = d->m_touchEventHandler->lastFatFingersResult().nodeAsElementIfApplicable();
if (elementUnderFatFinger)
d->m_touchEventHandler->drawTapHighlight();
}
bool handled = false;
if (!event.m_type != Platform::TouchEvent::TouchInjected)
handled = d->m_mainFrame->eventHandler()->handleTouchEvent(PlatformTouchEvent(&tEvent));
if (d->m_preventDefaultOnTouchStart) {
if (tEvent.m_type == Platform::TouchEvent::TouchEnd || tEvent.m_type == Platform::TouchEvent::TouchCancel)
d->m_preventDefaultOnTouchStart = false;
return true;
}
if (handled) {
if (tEvent.m_type == Platform::TouchEvent::TouchStart)
d->m_preventDefaultOnTouchStart = true;
return true;
}
if (event.isTouchHold())
d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]);
#endif
return false;
}
| 170,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> acceptTransferListCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestSerializedScriptValueInterface.acceptTransferList");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder());
MessagePortArray messagePortArrayTransferList;
ArrayBufferArray arrayBufferArrayTransferList;
if (args.Length() > 1) {
if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList))
return V8Proxy::throwTypeError("Could not extract transferables");
}
bool dataDidThrow = false;
RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate());
if (dataDidThrow)
return v8::Undefined();
if (args.Length() <= 1) {
imp->acceptTransferList(data);
return v8::Handle<v8::Value>();
}
imp->acceptTransferList(data, messagePortArrayTransferList);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> acceptTransferListCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestSerializedScriptValueInterface.acceptTransferList");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder());
MessagePortArray messagePortArrayTransferList;
ArrayBufferArray arrayBufferArrayTransferList;
if (args.Length() > 1) {
if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList))
return V8Proxy::throwTypeError("Could not extract transferables");
}
bool dataDidThrow = false;
RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate());
if (dataDidThrow)
return v8::Undefined();
if (args.Length() <= 1) {
imp->acceptTransferList(data);
return v8::Handle<v8::Value>();
}
imp->acceptTransferList(data, messagePortArrayTransferList);
return v8::Handle<v8::Value>();
}
| 171,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^
(FT_Offset)(char*)&decoder ^
(FT_Offset)(char*)&charstring_base ) &
FT_ULONG_MAX );
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip >= limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %d", value ));
else
FT_TRACE4(( " %d", value / 65536 ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) )
goto Fail;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
break;
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = (FT_Int)num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
(FT_UInt)idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
(FT_UInt)builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
error = hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
if ( error )
goto Fail;
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; i++ )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
top++;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( decoder->subrs_hash )
{
size_t* val = ft_hash_num_lookup( idx,
decoder->subrs_hash );
if ( val )
idx = *val;
else
idx = -1;
}
if ( idx < 0 || idx >= decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
Commit Message:
CWE ID: CWE-787 | t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^
(FT_Offset)(char*)&decoder ^
(FT_Offset)(char*)&charstring_base ) &
FT_ULONG_MAX );
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip >= limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %d", value ));
else
FT_TRACE4(( " %d", value / 65536 ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) )
goto Fail;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
{
/* in malformed fonts it is possible to have other */
/* opcodes in the middle of a flex (which don't */
/* increase `num_flex_vectors'); we thus have to */
/* check whether we can add a point */
if ( FT_SET_ERROR( t1_builder_check_points( builder, 1 ) ) )
goto Syntax_Error;
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
}
break;
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = (FT_Int)num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
(FT_UInt)idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
(FT_UInt)builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
error = hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
if ( error )
goto Fail;
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; i++ )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
top++;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( decoder->subrs_hash )
{
size_t* val = ft_hash_num_lookup( idx,
decoder->subrs_hash );
if ( val )
idx = *val;
else
idx = -1;
}
if ( idx < 0 || idx >= decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
| 164,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
return hardware_frame_.Pass();
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw(
const gfx::Size& surface_size,
const gfx::Transform& transform,
const gfx::Rect& viewport,
const gfx::Rect& clip,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
return hardware_frame_.Pass();
}
| 171,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.