instruction
stringclasses 1
value | input
stringlengths 222
112k
| output
stringlengths 21
113k
| __index_level_0__
int64 15
30k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
efree(buf);
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
Commit Message:
CWE ID: CWE-754 | PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
efree(buf);
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
| 7,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int get_devices_from_authfile(const char *authfile, const char *username,
unsigned max_devs, int verbose, FILE *debug_file,
device_t *devices, unsigned *n_devs) {
char *buf = NULL;
char *s_user, *s_token;
int retval = 0;
int fd = -1;
struct stat st;
struct passwd *pw = NULL, pw_s;
char buffer[BUFSIZE];
int gpu_ret;
FILE *opwfile = NULL;
unsigned i, j;
/* Ensure we never return uninitialized count. */
*n_devs = 0;
fd = open(authfile, O_RDONLY, 0);
if (fd < 0) {
if (verbose)
D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (fstat(fd, &st) < 0) {
if (verbose)
D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (!S_ISREG(st.st_mode)) {
if (verbose)
D(debug_file, "%s is not a regular file", authfile);
goto err;
}
if (st.st_size == 0) {
if (verbose)
D(debug_file, "File %s is empty", authfile);
goto err;
}
gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);
if (gpu_ret != 0 || pw == NULL) {
D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid,
strerror(errno));
goto err;
}
if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) {
if (strcmp(username, "root") != 0) {
D(debug_file, "The owner of the authentication file is neither %s nor root",
username);
} else {
D(debug_file, "The owner of the authentication file is not root");
}
goto err;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if (verbose)
D(debug_file, "fdopen: %s", strerror(errno));
goto err;
}
buf = malloc(sizeof(char) * (DEVSIZE * max_devs));
if (!buf) {
if (verbose)
D(debug_file, "Unable to allocate memory");
goto err;
}
retval = -2;
while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {
char *saveptr = NULL;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
if (verbose)
D(debug_file, "Authorization line: %s", buf);
s_user = strtok_r(buf, ":", &saveptr);
if (s_user && strcmp(username, s_user) == 0) {
if (verbose)
D(debug_file, "Matched user: %s", s_user);
retval = -1; // We found at least one line for the user
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
i = 0;
while ((s_token = strtok_r(NULL, ",", &saveptr))) {
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
if ((*n_devs)++ > MAX_DEVS - 1) {
*n_devs = MAX_DEVS;
if (verbose)
D(debug_file, "Found more than %d devices, ignoring the remaining ones",
MAX_DEVS);
break;
}
if (verbose)
D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token);
devices[i].keyHandle = strdup(s_token);
if (!devices[i].keyHandle) {
if (verbose)
D(debug_file, "Unable to allocate memory for keyHandle number %d", i);
goto err;
}
s_token = strtok_r(NULL, ":", &saveptr);
if (!s_token) {
if (verbose)
D(debug_file, "Unable to retrieve publicKey number %d", i + 1);
goto err;
}
if (verbose)
D(debug_file, "publicKey for device number %d: %s", i + 1, s_token);
if (strlen(s_token) % 2 != 0) {
if (verbose)
D(debug_file, "Length of key number %d not even", i + 1);
goto err;
}
devices[i].key_len = strlen(s_token) / 2;
if (verbose)
D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len);
devices[i].publicKey =
malloc((sizeof(unsigned char) * devices[i].key_len));
if (!devices[i].publicKey) {
if (verbose)
D(debug_file, "Unable to allocate memory for publicKey number %d", i);
goto err;
}
for (j = 0; j < devices[i].key_len; j++) {
unsigned int x;
if (sscanf(&s_token[2 * j], "%2x", &x) != 1) {
if (verbose)
D(debug_file, "Invalid hex number in key");
goto err;
}
devices[i].publicKey[j] = (unsigned char)x;
}
i++;
}
}
}
if (verbose)
D(debug_file, "Found %d device(s) for user %s", *n_devs, username);
retval = 1;
goto out;
err:
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
out:
if (buf) {
free(buf);
buf = NULL;
}
if (opwfile)
fclose(opwfile);
else if (fd >= 0)
close(fd);
return retval;
}
Commit Message: Do not leak file descriptor when doing exec
When opening a custom debug file, the descriptor would stay
open when calling exec and leak to the child process.
Make sure all files are opened with close-on-exec.
This fixes CVE-2019-12210.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.
CWE ID: CWE-200 | int get_devices_from_authfile(const char *authfile, const char *username,
unsigned max_devs, int verbose, FILE *debug_file,
device_t *devices, unsigned *n_devs) {
char *buf = NULL;
char *s_user, *s_token;
int retval = 0;
int fd = -1;
struct stat st;
struct passwd *pw = NULL, pw_s;
char buffer[BUFSIZE];
int gpu_ret;
FILE *opwfile = NULL;
unsigned i, j;
/* Ensure we never return uninitialized count. */
*n_devs = 0;
fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY);
if (fd < 0) {
if (verbose)
D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (fstat(fd, &st) < 0) {
if (verbose)
D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (!S_ISREG(st.st_mode)) {
if (verbose)
D(debug_file, "%s is not a regular file", authfile);
goto err;
}
if (st.st_size == 0) {
if (verbose)
D(debug_file, "File %s is empty", authfile);
goto err;
}
gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);
if (gpu_ret != 0 || pw == NULL) {
D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid,
strerror(errno));
goto err;
}
if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) {
if (strcmp(username, "root") != 0) {
D(debug_file, "The owner of the authentication file is neither %s nor root",
username);
} else {
D(debug_file, "The owner of the authentication file is not root");
}
goto err;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if (verbose)
D(debug_file, "fdopen: %s", strerror(errno));
goto err;
} else {
fd = -1; /* fd belongs to opwfile */
}
buf = malloc(sizeof(char) * (DEVSIZE * max_devs));
if (!buf) {
if (verbose)
D(debug_file, "Unable to allocate memory");
goto err;
}
retval = -2;
while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {
char *saveptr = NULL;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
if (verbose)
D(debug_file, "Authorization line: %s", buf);
s_user = strtok_r(buf, ":", &saveptr);
if (s_user && strcmp(username, s_user) == 0) {
if (verbose)
D(debug_file, "Matched user: %s", s_user);
retval = -1; // We found at least one line for the user
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
i = 0;
while ((s_token = strtok_r(NULL, ",", &saveptr))) {
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
if ((*n_devs)++ > MAX_DEVS - 1) {
*n_devs = MAX_DEVS;
if (verbose)
D(debug_file, "Found more than %d devices, ignoring the remaining ones",
MAX_DEVS);
break;
}
if (verbose)
D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token);
devices[i].keyHandle = strdup(s_token);
if (!devices[i].keyHandle) {
if (verbose)
D(debug_file, "Unable to allocate memory for keyHandle number %d", i);
goto err;
}
s_token = strtok_r(NULL, ":", &saveptr);
if (!s_token) {
if (verbose)
D(debug_file, "Unable to retrieve publicKey number %d", i + 1);
goto err;
}
if (verbose)
D(debug_file, "publicKey for device number %d: %s", i + 1, s_token);
if (strlen(s_token) % 2 != 0) {
if (verbose)
D(debug_file, "Length of key number %d not even", i + 1);
goto err;
}
devices[i].key_len = strlen(s_token) / 2;
if (verbose)
D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len);
devices[i].publicKey =
malloc((sizeof(unsigned char) * devices[i].key_len));
if (!devices[i].publicKey) {
if (verbose)
D(debug_file, "Unable to allocate memory for publicKey number %d", i);
goto err;
}
for (j = 0; j < devices[i].key_len; j++) {
unsigned int x;
if (sscanf(&s_token[2 * j], "%2x", &x) != 1) {
if (verbose)
D(debug_file, "Invalid hex number in key");
goto err;
}
devices[i].publicKey[j] = (unsigned char)x;
}
i++;
}
}
}
if (verbose)
D(debug_file, "Found %d device(s) for user %s", *n_devs, username);
retval = 1;
goto out;
err:
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
out:
if (buf) {
free(buf);
buf = NULL;
}
if (opwfile)
fclose(opwfile);
if (fd != -1)
close(fd);
return retval;
}
| 24,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void AutoFillMetrics::Log(QualityMetric metric) const {
DCHECK(metric < NUM_QUALITY_METRICS);
UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric,
NUM_QUALITY_METRICS);
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AutoFillMetrics::Log(QualityMetric metric) const {
void AutoFillMetrics::Log(QualityMetric metric,
const std::string& experiment_id) const {
DCHECK(metric < NUM_QUALITY_METRICS);
std::string histogram_name = "AutoFill.Quality";
if (!experiment_id.empty())
histogram_name += "_" + experiment_id;
UMA_HISTOGRAM_ENUMERATION(histogram_name, metric, NUM_QUALITY_METRICS);
}
| 9,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pud_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pud_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
| 22,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(&batch);
put_ioctx(ctx);
return i ? i : ret;
}
Commit Message: Unused iocbs in a batch should not be accounted as active.
commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream.
Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are
allocated in a batch during processing of first iocbs. All iocbs in a
batch are automatically added to ctx->active_reqs list and accounted in
ctx->reqs_active.
If one (not the last one) of iocbs submitted by an user fails, further
iocbs are not processed, but they are still present in ctx->active_reqs
and accounted in ctx->reqs_active. This causes process to stuck in a D
state in wait_for_all_aios() on exit since ctx->reqs_active will never
go down to zero. Furthermore since kiocb_batch_free() frees iocb
without removing it from active_reqs list the list become corrupted
which may cause oops.
Fix this by removing iocb from ctx->active_reqs and updating
ctx->reqs_active in kiocb_batch_free().
Signed-off-by: Gleb Natapov <gleb@redhat.com>
Reviewed-by: Jeff Moyer <jmoyer@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>
CWE ID: CWE-399 | long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(ctx, &batch);
put_ioctx(ctx);
return i ? i : ret;
}
| 1,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: RenderView::RenderView(RenderThreadBase* render_thread,
gfx::NativeViewId parent_hwnd,
int32 opener_id,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
SharedRenderViewCounter* counter,
int32 routing_id,
int64 session_storage_namespace_id,
const string16& frame_name)
: RenderWidget(render_thread, WebKit::WebPopupTypeNone),
webkit_preferences_(webkit_prefs),
send_content_state_immediately_(false),
enabled_bindings_(0),
send_preferred_size_changes_(false),
is_loading_(false),
navigation_gesture_(NavigationGestureUnknown),
opened_by_user_gesture_(true),
opener_suppressed_(false),
page_id_(-1),
last_page_id_sent_to_browser_(-1),
history_list_offset_(-1),
history_list_length_(0),
target_url_status_(TARGET_NONE),
ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(accessibility_method_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)),
geolocation_dispatcher_(NULL),
speech_input_dispatcher_(NULL),
device_orientation_dispatcher_(NULL),
accessibility_ack_pending_(false),
p2p_socket_dispatcher_(NULL),
session_storage_namespace_id_(session_storage_namespace_id) {
routing_id_ = routing_id;
if (opener_id != MSG_ROUTING_NONE)
opener_id_ = opener_id;
webwidget_ = WebView::create(this);
if (counter) {
shared_popup_counter_ = counter;
shared_popup_counter_->data++;
decrement_shared_popup_at_destruction_ = true;
} else {
shared_popup_counter_ = new SharedRenderViewCounter(0);
decrement_shared_popup_at_destruction_ = false;
}
notification_provider_ = new NotificationProvider(this);
render_thread_->AddRoute(routing_id_, this);
AddRef();
if (opener_id == MSG_ROUTING_NONE) {
did_show_ = true;
CompleteInit(parent_hwnd);
}
g_view_map.Get().insert(std::make_pair(webview(), this));
webkit_preferences_.Apply(webview());
webview()->initializeMainFrame(this);
if (!frame_name.empty())
webview()->mainFrame()->setName(frame_name);
webview()->settings()->setMinimumTimerInterval(
is_hidden() ? webkit_glue::kBackgroundTabTimerInterval :
webkit_glue::kForegroundTabTimerInterval);
OnSetRendererPrefs(renderer_prefs);
host_window_ = parent_hwnd;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableAccessibility))
WebAccessibilityCache::enableAccessibility();
#if defined(ENABLE_P2P_APIS)
p2p_socket_dispatcher_ = new P2PSocketDispatcher(this);
#endif
new MHTMLGenerator(this);
if (command_line.HasSwitch(switches::kEnableMediaStream)) {
media_stream_impl_ = new MediaStreamImpl(
RenderThread::current()->video_capture_impl_manager());
}
content::GetContentClient()->renderer()->RenderViewCreated(this);
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | RenderView::RenderView(RenderThreadBase* render_thread,
gfx::NativeViewId parent_hwnd,
int32 opener_id,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
SharedRenderViewCounter* counter,
int32 routing_id,
int64 session_storage_namespace_id,
const string16& frame_name)
: RenderWidget(render_thread, WebKit::WebPopupTypeNone),
webkit_preferences_(webkit_prefs),
send_content_state_immediately_(false),
enabled_bindings_(0),
send_preferred_size_changes_(false),
is_loading_(false),
navigation_gesture_(NavigationGestureUnknown),
opened_by_user_gesture_(true),
opener_suppressed_(false),
page_id_(-1),
last_page_id_sent_to_browser_(-1),
history_list_offset_(-1),
history_list_length_(0),
target_url_status_(TARGET_NONE),
ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(accessibility_method_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)),
geolocation_dispatcher_(NULL),
speech_input_dispatcher_(NULL),
device_orientation_dispatcher_(NULL),
accessibility_ack_pending_(false),
p2p_socket_dispatcher_(NULL),
session_storage_namespace_id_(session_storage_namespace_id) {
routing_id_ = routing_id;
if (opener_id != MSG_ROUTING_NONE)
opener_id_ = opener_id;
webwidget_ = WebView::create(this);
if (counter) {
shared_popup_counter_ = counter;
shared_popup_counter_->data++;
decrement_shared_popup_at_destruction_ = true;
} else {
shared_popup_counter_ = new SharedRenderViewCounter(0);
decrement_shared_popup_at_destruction_ = false;
}
notification_provider_ = new NotificationProvider(this);
render_thread_->AddRoute(routing_id_, this);
AddRef();
if (opener_id == MSG_ROUTING_NONE) {
did_show_ = true;
CompleteInit(parent_hwnd);
}
g_view_map.Get().insert(std::make_pair(webview(), this));
webkit_preferences_.Apply(webview());
webview()->initializeMainFrame(this);
if (!frame_name.empty())
webview()->mainFrame()->setName(frame_name);
webview()->settings()->setMinimumTimerInterval(
is_hidden() ? webkit_glue::kBackgroundTabTimerInterval :
webkit_glue::kForegroundTabTimerInterval);
OnSetRendererPrefs(renderer_prefs);
host_window_ = parent_hwnd;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableAccessibility))
WebAccessibilityCache::enableAccessibility();
#if defined(ENABLE_P2P_APIS)
p2p_socket_dispatcher_ = new P2PSocketDispatcher(this);
#endif
new MHTMLGenerator(this);
new DevToolsAgent(this);
if (command_line.HasSwitch(switches::kEnableMediaStream)) {
media_stream_impl_ = new MediaStreamImpl(
RenderThread::current()->video_capture_impl_manager());
}
content::GetContentClient()->renderer()->RenderViewCreated(this);
}
| 15,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: perf_event_read_event(struct perf_event *event,
struct task_struct *task)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_read_event read_event = {
.header = {
.type = PERF_RECORD_READ,
.misc = 0,
.size = sizeof(read_event) + event->read_size,
},
.pid = perf_event_pid(event, task),
.tid = perf_event_tid(event, task),
};
int ret;
perf_event_header__init_id(&read_event.header, &sample, event);
ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
if (ret)
return;
perf_output_put(&handle, read_event);
perf_output_read(&handle, event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: CWE-399 | perf_event_read_event(struct perf_event *event,
struct task_struct *task)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_read_event read_event = {
.header = {
.type = PERF_RECORD_READ,
.misc = 0,
.size = sizeof(read_event) + event->read_size,
},
.pid = perf_event_pid(event, task),
.tid = perf_event_tid(event, task),
};
int ret;
perf_event_header__init_id(&read_event.header, &sample, event);
ret = perf_output_begin(&handle, event, read_event.header.size, 0);
if (ret)
return;
perf_output_put(&handle, read_event);
perf_output_read(&handle, event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
| 4,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + (rlen + 1);
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
list[i] = NULL;
}
} else
list[i] = NULL;
}
}
} else
Commit Message:
CWE ID: CWE-682 | char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
} else
| 20,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void NaClProcessHost::OnPpapiChannelCreated(
const IPC::ChannelHandle& channel_handle) {
DCHECK(enable_ipc_proxy_);
ReplyToRenderer(channel_handle);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void NaClProcessHost::OnPpapiChannelCreated(
return ReplyToRenderer() && StartNaClExecution();
}
| 17,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
unsigned char arg[MAX_ARG_LEN];
struct ip_vs_service_user *usvc_compat;
struct ip_vs_service_user_kern usvc;
struct ip_vs_service *svc;
struct ip_vs_dest_user *udest_compat;
struct ip_vs_dest_user_kern udest;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (len != set_arglen[SET_CMDID(cmd)]) {
pr_err("set_ctl: len %u != %u\n",
len, set_arglen[SET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, len) != 0)
return -EFAULT;
/* increase the module use count */
ip_vs_use_count_inc();
if (mutex_lock_interruptible(&__ip_vs_mutex)) {
ret = -ERESTARTSYS;
goto out_dec;
}
if (cmd == IP_VS_SO_SET_FLUSH) {
/* Flush the virtual service */
ret = ip_vs_flush();
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_TIMEOUT) {
/* Set timeout values for (tcp tcpfin udp) */
ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STARTDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STOPDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = stop_sync_thread(dm->state);
goto out_unlock;
}
usvc_compat = (struct ip_vs_service_user *)arg;
udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
/* We only use the new structs internally, so copy userspace compat
* structs to extended internal versions */
ip_vs_copy_usvc_compat(&usvc, usvc_compat);
ip_vs_copy_udest_compat(&udest, udest_compat);
if (cmd == IP_VS_SO_SET_ZERO) {
/* if no service address is set, zero counters in all */
if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
ret = ip_vs_zero_all();
goto out_unlock;
}
}
/* Check for valid protocol: TCP or UDP, even for fwmark!=0 */
if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) {
pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
usvc.protocol, &usvc.addr.ip,
ntohs(usvc.port), usvc.sched_name);
ret = -EFAULT;
goto out_unlock;
}
/* Lookup the exact service by <protocol, addr, port> or fwmark */
if (usvc.fwmark == 0)
svc = __ip_vs_service_get(usvc.af, usvc.protocol,
&usvc.addr, usvc.port);
else
svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark);
if (cmd != IP_VS_SO_SET_ADD
&& (svc == NULL || svc->protocol != usvc.protocol)) {
ret = -ESRCH;
goto out_unlock;
}
switch (cmd) {
case IP_VS_SO_SET_ADD:
if (svc != NULL)
ret = -EEXIST;
else
ret = ip_vs_add_service(&usvc, &svc);
break;
case IP_VS_SO_SET_EDIT:
ret = ip_vs_edit_service(svc, &usvc);
break;
case IP_VS_SO_SET_DEL:
ret = ip_vs_del_service(svc);
if (!ret)
goto out_unlock;
break;
case IP_VS_SO_SET_ZERO:
ret = ip_vs_zero_service(svc);
break;
case IP_VS_SO_SET_ADDDEST:
ret = ip_vs_add_dest(svc, &udest);
break;
case IP_VS_SO_SET_EDITDEST:
ret = ip_vs_edit_dest(svc, &udest);
break;
case IP_VS_SO_SET_DELDEST:
ret = ip_vs_del_dest(svc, &udest);
break;
default:
ret = -EINVAL;
}
if (svc)
ip_vs_service_put(svc);
out_unlock:
mutex_unlock(&__ip_vs_mutex);
out_dec:
/* decrease the module use count */
ip_vs_use_count_dec();
return ret;
}
Commit Message: ipvs: Add boundary check on ioctl arguments
The ipvs code has a nifty system for doing the size of ioctl command
copies; it defines an array with values into which it indexes the cmd
to find the right length.
Unfortunately, the ipvs code forgot to check if the cmd was in the
range that the array provides, allowing for an index outside of the
array, which then gives a "garbage" result into the length, which
then gets used for copying into a stack buffer.
Fix this by adding sanity checks on these as well as the copy size.
[ horms@verge.net.au: adjusted limit to IP_VS_SO_GET_MAX ]
Signed-off-by: Arjan van de Ven <arjan@linux.intel.com>
Acked-by: Julian Anastasov <ja@ssi.bg>
Signed-off-by: Simon Horman <horms@verge.net.au>
Signed-off-by: Patrick McHardy <kaber@trash.net>
CWE ID: CWE-119 | do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
unsigned char arg[MAX_ARG_LEN];
struct ip_vs_service_user *usvc_compat;
struct ip_vs_service_user_kern usvc;
struct ip_vs_service *svc;
struct ip_vs_dest_user *udest_compat;
struct ip_vs_dest_user_kern udest;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
return -EINVAL;
if (len < 0 || len > MAX_ARG_LEN)
return -EINVAL;
if (len != set_arglen[SET_CMDID(cmd)]) {
pr_err("set_ctl: len %u != %u\n",
len, set_arglen[SET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, len) != 0)
return -EFAULT;
/* increase the module use count */
ip_vs_use_count_inc();
if (mutex_lock_interruptible(&__ip_vs_mutex)) {
ret = -ERESTARTSYS;
goto out_dec;
}
if (cmd == IP_VS_SO_SET_FLUSH) {
/* Flush the virtual service */
ret = ip_vs_flush();
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_TIMEOUT) {
/* Set timeout values for (tcp tcpfin udp) */
ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STARTDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STOPDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = stop_sync_thread(dm->state);
goto out_unlock;
}
usvc_compat = (struct ip_vs_service_user *)arg;
udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
/* We only use the new structs internally, so copy userspace compat
* structs to extended internal versions */
ip_vs_copy_usvc_compat(&usvc, usvc_compat);
ip_vs_copy_udest_compat(&udest, udest_compat);
if (cmd == IP_VS_SO_SET_ZERO) {
/* if no service address is set, zero counters in all */
if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
ret = ip_vs_zero_all();
goto out_unlock;
}
}
/* Check for valid protocol: TCP or UDP, even for fwmark!=0 */
if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) {
pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
usvc.protocol, &usvc.addr.ip,
ntohs(usvc.port), usvc.sched_name);
ret = -EFAULT;
goto out_unlock;
}
/* Lookup the exact service by <protocol, addr, port> or fwmark */
if (usvc.fwmark == 0)
svc = __ip_vs_service_get(usvc.af, usvc.protocol,
&usvc.addr, usvc.port);
else
svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark);
if (cmd != IP_VS_SO_SET_ADD
&& (svc == NULL || svc->protocol != usvc.protocol)) {
ret = -ESRCH;
goto out_unlock;
}
switch (cmd) {
case IP_VS_SO_SET_ADD:
if (svc != NULL)
ret = -EEXIST;
else
ret = ip_vs_add_service(&usvc, &svc);
break;
case IP_VS_SO_SET_EDIT:
ret = ip_vs_edit_service(svc, &usvc);
break;
case IP_VS_SO_SET_DEL:
ret = ip_vs_del_service(svc);
if (!ret)
goto out_unlock;
break;
case IP_VS_SO_SET_ZERO:
ret = ip_vs_zero_service(svc);
break;
case IP_VS_SO_SET_ADDDEST:
ret = ip_vs_add_dest(svc, &udest);
break;
case IP_VS_SO_SET_EDITDEST:
ret = ip_vs_edit_dest(svc, &udest);
break;
case IP_VS_SO_SET_DELDEST:
ret = ip_vs_del_dest(svc, &udest);
break;
default:
ret = -EINVAL;
}
if (svc)
ip_vs_service_put(svc);
out_unlock:
mutex_unlock(&__ip_vs_mutex);
out_dec:
/* decrease the module use count */
ip_vs_use_count_dec();
return ret;
}
| 18,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void btsnoop_net_write(const void *data, size_t length) {
#if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE))
return; // Disable using network sockets for security reasons
#endif
pthread_mutex_lock(&client_socket_lock_);
if (client_socket_ != -1) {
if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) {
safe_close_(&client_socket_);
}
}
pthread_mutex_unlock(&client_socket_lock_);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void btsnoop_net_write(const void *data, size_t length) {
#if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE))
return; // Disable using network sockets for security reasons
#endif
pthread_mutex_lock(&client_socket_lock_);
if (client_socket_ != -1) {
if (TEMP_FAILURE_RETRY(send(client_socket_, data, length, 0)) == -1 && errno == ECONNRESET) {
safe_close_(&client_socket_);
}
}
pthread_mutex_unlock(&client_socket_lock_);
}
| 3,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. | Code: void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode) {
SplashBitmap *scaledMask;
SplashClipResult clipRes, clipRes2;
SplashPipe pipe;
int scaledWidth, scaledHeight, t0, t1;
SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
SplashCoord vx[4], vy[4];
int xMin, yMin, xMax, yMax;
ImageSection section[3];
int nSections;
int y, xa, xb, x, i, xx, yy;
vx[0] = mat[4]; vy[0] = mat[5];
vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5];
vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5];
vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5];
xMin = imgCoordMungeLowerC(vx[0], glyphMode);
xMax = imgCoordMungeUpperC(vx[0], glyphMode);
yMin = imgCoordMungeLowerC(vy[0], glyphMode);
yMax = imgCoordMungeUpperC(vy[0], glyphMode);
for (i = 1; i < 4; ++i) {
t0 = imgCoordMungeLowerC(vx[i], glyphMode);
if (t0 < xMin) {
xMin = t0;
}
t0 = imgCoordMungeUpperC(vx[i], glyphMode);
if (t0 > xMax) {
xMax = t0;
}
t1 = imgCoordMungeLowerC(vy[i], glyphMode);
if (t1 < yMin) {
yMin = t1;
}
t1 = imgCoordMungeUpperC(vy[i], glyphMode);
if (t1 > yMax) {
yMax = t1;
}
}
clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
opClipRes = clipRes;
if (clipRes == splashClipAllOutside) {
return;
}
if (mat[0] >= 0) {
t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
}
if (mat[1] >= 0) {
t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
}
scaledWidth = t0 > t1 ? t0 : t1;
if (mat[2] >= 0) {
t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
}
if (mat[3] >= 0) {
t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
}
scaledHeight = t0 > t1 ? t0 : t1;
if (scaledWidth == 0) {
scaledWidth = 1;
}
if (scaledHeight == 0) {
scaledHeight = 1;
}
r00 = mat[0] / scaledWidth;
r01 = mat[1] / scaledWidth;
r10 = mat[2] / scaledHeight;
r11 = mat[3] / scaledHeight;
det = r00 * r11 - r01 * r10;
if (splashAbs(det) < 1e-6) {
return;
}
ir00 = r11 / det;
ir01 = -r01 / det;
ir10 = -r10 / det;
ir11 = r00 / det;
scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
scaledWidth, scaledHeight);
i = (vy[2] <= vy[3]) ? 2 : 3;
}
Commit Message:
CWE ID: | void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode) {
SplashBitmap *scaledMask;
SplashClipResult clipRes, clipRes2;
SplashPipe pipe;
int scaledWidth, scaledHeight, t0, t1;
SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
SplashCoord vx[4], vy[4];
int xMin, yMin, xMax, yMax;
ImageSection section[3];
int nSections;
int y, xa, xb, x, i, xx, yy;
vx[0] = mat[4]; vy[0] = mat[5];
vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5];
vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5];
vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5];
xMin = imgCoordMungeLowerC(vx[0], glyphMode);
xMax = imgCoordMungeUpperC(vx[0], glyphMode);
yMin = imgCoordMungeLowerC(vy[0], glyphMode);
yMax = imgCoordMungeUpperC(vy[0], glyphMode);
for (i = 1; i < 4; ++i) {
t0 = imgCoordMungeLowerC(vx[i], glyphMode);
if (t0 < xMin) {
xMin = t0;
}
t0 = imgCoordMungeUpperC(vx[i], glyphMode);
if (t0 > xMax) {
xMax = t0;
}
t1 = imgCoordMungeLowerC(vy[i], glyphMode);
if (t1 < yMin) {
yMin = t1;
}
t1 = imgCoordMungeUpperC(vy[i], glyphMode);
if (t1 > yMax) {
yMax = t1;
}
}
clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
opClipRes = clipRes;
if (clipRes == splashClipAllOutside) {
return;
}
if (mat[0] >= 0) {
t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
}
if (mat[1] >= 0) {
t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
}
scaledWidth = t0 > t1 ? t0 : t1;
if (mat[2] >= 0) {
t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
}
if (mat[3] >= 0) {
t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
}
scaledHeight = t0 > t1 ? t0 : t1;
if (scaledWidth == 0) {
scaledWidth = 1;
}
if (scaledHeight == 0) {
scaledHeight = 1;
}
r00 = mat[0] / scaledWidth;
r01 = mat[1] / scaledWidth;
r10 = mat[2] / scaledHeight;
r11 = mat[3] / scaledHeight;
det = r00 * r11 - r01 * r10;
if (splashAbs(det) < 1e-6) {
return;
}
ir00 = r11 / det;
ir01 = -r01 / det;
ir10 = -r10 / det;
ir11 = r00 / det;
scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
scaledWidth, scaledHeight);
if (scaledMask->data == NULL) {
error(errInternal, -1, "scaledMask->data is NULL in Splash::scaleMaskYuXu");
delete scaledMask;
return;
}
i = (vy[2] <= vy[3]) ? 2 : 3;
}
| 7,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: std::string MakeMediaAccessRequest(int index) {
const int render_process_id = 1;
const int render_frame_id = 1;
const int page_request_id = 1;
const url::Origin security_origin;
MediaStreamManager::MediaAccessRequestCallback callback =
base::BindOnce(&MediaStreamManagerTest::ResponseCallback,
base::Unretained(this), index);
StreamControls controls(true, true);
return media_stream_manager_->MakeMediaAccessRequest(
render_process_id, render_frame_id, page_request_id, controls,
security_origin, std::move(callback));
}
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 <emircan@chromium.org>
Reviewed-by: Ken Buchanan <kenrb@chromium.org>
Reviewed-by: Olga Sharonova <olka@chromium.org>
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | std::string MakeMediaAccessRequest(int index) {
const int render_process_id = 1;
const int render_frame_id = 1;
const int requester_id = 1;
const int page_request_id = 1;
const url::Origin security_origin;
MediaStreamManager::MediaAccessRequestCallback callback =
base::BindOnce(&MediaStreamManagerTest::ResponseCallback,
base::Unretained(this), index);
StreamControls controls(true, true);
return media_stream_manager_->MakeMediaAccessRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
controls, security_origin, std::move(callback));
}
| 380 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1613
CWE ID: CWE-119 | static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
(void) strncpy((char *) q,buffer,extent);
q+=extent;
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 16,539 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | 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 <thuanpv@comp.nus.edu.sg>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
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);
}
| 21,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void sample_to_timespec(const clockid_t which_clock,
union cpu_time_count cpu,
struct timespec *tp)
{
if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {
tp->tv_sec = div_long_long_rem(cpu.sched,
NSEC_PER_SEC, &tp->tv_nsec);
} else {
cputime_to_timespec(cpu.cpu, tp);
}
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <zippel@linux-m68k.org>
Cc: Ralf Baechle <ralf@linux-mips.org>
Cc: Ingo Molnar <mingo@elte.hu>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: john stultz <johnstul@us.ibm.com>
Cc: Christoph Lameter <clameter@sgi.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-189 | static void sample_to_timespec(const clockid_t which_clock,
union cpu_time_count cpu,
struct timespec *tp)
{
if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED)
*tp = ns_to_timespec(cpu.sched);
else
cputime_to_timespec(cpu.cpu, tp);
}
| 19,144 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: virtual void runTest()
{
webkit_support::PostDelayedTask(CCLayerTreeHostTest::onBeginTest, static_cast<void*>(this), 0);
webkit_support::PostDelayedTask(CCLayerTreeHostTest::testTimeout, static_cast<void*>(this), 5000);
webkit_support::RunMessageLoop();
m_running = false;
bool timedOut = m_timedOut; // Save whether we're timed out in case RunAllPendingMessages has the timeout.
webkit_support::RunAllPendingMessages();
ASSERT(!m_layerTreeHost.get());
m_client.clear();
if (timedOut) {
FAIL() << "Test timed out";
return;
}
afterTest();
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | virtual void runTest()
class TimeoutTask : public webkit_support::TaskAdaptor {
public:
explicit TimeoutTask(CCLayerTreeHostTest* test)
: m_test(test)
{
}
void clearTest()
{
m_test = 0;
}
virtual ~TimeoutTask()
{
if (m_test)
m_test->clearTimeout();
}
virtual void Run()
{
if (m_test)
m_test->timeout();
}
private:
CCLayerTreeHostTest* m_test;
};
virtual void runTest(bool threaded)
{
m_settings.enableCompositorThread = threaded;
webkit_support::PostDelayedTask(CCLayerTreeHostTest::onBeginTest, static_cast<void*>(this), 0);
m_timeoutTask = new TimeoutTask(this);
webkit_support::PostDelayedTask(m_timeoutTask, 5000); // webkit_support takes ownership of the task
webkit_support::RunMessageLoop();
webkit_support::RunAllPendingMessages();
if (m_timeoutTask)
m_timeoutTask->clearTest();
ASSERT(!m_layerTreeHost.get());
m_client.clear();
if (m_timedOut) {
FAIL() << "Test timed out";
return;
}
afterTest();
}
| 23,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
| 23,099 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
Commit Message: fix bug #64660 - yyparse can return 2, not only 1
CWE ID: CWE-20 | ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result != 0) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
| 16,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int nntp_add_group(char *line, void *data)
{
struct NntpServer *nserv = data;
struct NntpData *nntp_data = NULL;
char group[LONG_STRING];
char desc[HUGE_STRING] = "";
char mod;
anum_t first, last;
if (!nserv || !line)
return 0;
if (sscanf(line, "%s " ANUM " " ANUM " %c %[^\n]", group, &last, &first, &mod, desc) < 4)
return 0;
nntp_data = nntp_data_find(nserv, group);
nntp_data->deleted = false;
nntp_data->first_message = first;
nntp_data->last_message = last;
nntp_data->allowed = (mod == 'y') || (mod == 'm');
mutt_str_replace(&nntp_data->desc, desc);
if (nntp_data->newsrc_ent || nntp_data->last_cached)
nntp_group_unread_stat(nntp_data);
else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message)
nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1;
else
nntp_data->unread = 0;
return 0;
}
Commit Message: Set length modifiers for group and desc
nntp_add_group parses a line controlled by the connected nntp server.
Restrict the maximum lengths read into the stack buffers group, and
desc.
CWE ID: CWE-119 | int nntp_add_group(char *line, void *data)
{
struct NntpServer *nserv = data;
struct NntpData *nntp_data = NULL;
char group[LONG_STRING] = "";
char desc[HUGE_STRING] = "";
char mod;
anum_t first, last;
if (!nserv || !line)
return 0;
/* These sscanf limits must match the sizes of the group and desc arrays */
if (sscanf(line, "%1023s " ANUM " " ANUM " %c %8191[^\n]", group, &last, &first, &mod, desc) < 4)
{
mutt_debug(4, "Cannot parse server line: %s\n", line);
return 0;
}
nntp_data = nntp_data_find(nserv, group);
nntp_data->deleted = false;
nntp_data->first_message = first;
nntp_data->last_message = last;
nntp_data->allowed = (mod == 'y') || (mod == 'm');
mutt_str_replace(&nntp_data->desc, desc);
if (nntp_data->newsrc_ent || nntp_data->last_cached)
nntp_group_unread_stat(nntp_data);
else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message)
nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1;
else
nntp_data->unread = 0;
return 0;
}
| 18,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: ExtensionDevToolsClientHost::ExtensionDevToolsClientHost(
Profile* profile,
DevToolsAgentHost* agent_host,
const std::string& extension_id,
const std::string& extension_name,
const Debuggee& debuggee)
: profile_(profile),
agent_host_(agent_host),
extension_id_(extension_id),
last_request_id_(0),
infobar_(nullptr),
detach_reason_(api::debugger::DETACH_REASON_TARGET_CLOSED),
extension_registry_observer_(this) {
CopyDebuggee(&debuggee_, debuggee);
g_attached_client_hosts.Get().insert(this);
extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
agent_host_->AttachClient(this);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kSilentDebuggerExtensionAPI)) {
return;
}
const Extension* extension =
ExtensionRegistry::Get(profile)->enabled_extensions().GetByID(
extension_id);
if (extension && Manifest::IsPolicyLocation(extension->location()))
return;
infobar_ = ExtensionDevToolsInfoBar::Create(
extension_id, extension_name, this,
base::Bind(&ExtensionDevToolsClientHost::InfoBarDismissed,
base::Unretained(this)));
}
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.
TBR=alexclarke@chromium.org
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <dgozman@chromium.org>
Reviewed-by: Devlin <rdevlin.cronin@chromium.org>
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | ExtensionDevToolsClientHost::ExtensionDevToolsClientHost(
Profile* profile,
DevToolsAgentHost* agent_host,
const std::string& extension_id,
const std::string& extension_name,
const Debuggee& debuggee)
: profile_(profile),
agent_host_(agent_host),
extension_id_(extension_id),
extension_name_(extension_name),
last_request_id_(0),
infobar_(nullptr),
detach_reason_(api::debugger::DETACH_REASON_TARGET_CLOSED),
extension_registry_observer_(this) {
CopyDebuggee(&debuggee_, debuggee);
g_attached_client_hosts.Get().insert(this);
extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
}
bool ExtensionDevToolsClientHost::Attach() {
if (!agent_host_->AttachRestrictedClient(this))
return false;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kSilentDebuggerExtensionAPI)) {
return true;
}
const Extension* extension =
ExtensionRegistry::Get(profile_)->enabled_extensions().GetByID(
extension_id_);
// TODO(dgozman): null-checking |extension| below is sketchy.
// We probably should not allow debugging in this case. Or maybe
// it's never null?
if (extension && Manifest::IsPolicyLocation(extension->location()))
return true;
infobar_ = ExtensionDevToolsInfoBar::Create(
extension_id_, extension_name_, this,
base::Bind(&ExtensionDevToolsClientHost::InfoBarDismissed,
base::Unretained(this)));
return true;
}
| 29,930 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 5,755 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void StyleResolver::matchUARules(ElementRuleCollector& collector)
{
collector.setMatchingUARules(true);
if (CSSDefaultStyleSheets::simpleDefaultStyleSheet)
collector.matchedResult().isCacheable = false;
RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle;
matchUARules(collector, userAgentStyleSheet);
if (document().inQuirksMode())
matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle);
if (document().isViewSource())
matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
collector.setMatchingUARules(false);
matchWatchSelectorRules(collector);
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void StyleResolver::matchUARules(ElementRuleCollector& collector)
{
collector.setMatchingUARules(true);
RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle;
matchUARules(collector, userAgentStyleSheet);
if (document().inQuirksMode())
matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle);
if (document().isViewSource())
matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
collector.setMatchingUARules(false);
matchWatchSelectorRules(collector);
}
| 4,852 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption -> key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption -> signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption -> sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos, size, pReader, &encryption->aes_settings);
if (status)
return status;
}
pos += size; // consume payload
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 ContentEncoding::ParseEncryptionEntry(long long start, long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption->key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption->signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption->sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos, size, pReader, &encryption->aes_settings);
if (status)
return status;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
return 0;
}
| 26,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
struct stream packet = *s;
if (!s_check(s))
{
rdp_protocol_error("seamless_process(), stream is in unstable state", &packet);
}
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
| 16,026 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
int bufsize)
{
/* If this function is being called, the buffer should not have been
initialized yet. */
assert(!stream->bufbase_);
if (bufmode != JAS_STREAM_UNBUF) {
/* The full- or line-buffered mode is being employed. */
if (!buf) {
/* The caller has not specified a buffer to employ, so allocate
one. */
if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
JAS_STREAM_MAXPUTBACK))) {
stream->bufmode_ |= JAS_STREAM_FREEBUF;
stream->bufsize_ = JAS_STREAM_BUFSIZE;
} else {
/* The buffer allocation has failed. Resort to unbuffered
operation. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
} else {
/* The caller has specified a buffer to employ. */
/* The buffer must be large enough to accommodate maximum
putback. */
assert(bufsize > JAS_STREAM_MAXPUTBACK);
stream->bufbase_ = JAS_CAST(uchar *, buf);
stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
}
} else {
/* The unbuffered mode is being employed. */
/* A buffer should not have been supplied by the caller. */
assert(!buf);
/* Use a trivial one-character buffer. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
stream->ptr_ = stream->bufstart_;
stream->cnt_ = 0;
stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
int bufsize)
{
/* If this function is being called, the buffer should not have been
initialized yet. */
assert(!stream->bufbase_);
if (bufmode != JAS_STREAM_UNBUF) {
/* The full- or line-buffered mode is being employed. */
if (!buf) {
/* The caller has not specified a buffer to employ, so allocate
one. */
if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
JAS_STREAM_MAXPUTBACK))) {
stream->bufmode_ |= JAS_STREAM_FREEBUF;
stream->bufsize_ = JAS_STREAM_BUFSIZE;
} else {
/* The buffer allocation has failed. Resort to unbuffered
operation. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
} else {
/* The caller has specified a buffer to employ. */
/* The buffer must be large enough to accommodate maximum
putback. */
assert(bufsize > JAS_STREAM_MAXPUTBACK);
stream->bufbase_ = JAS_CAST(jas_uchar *, buf);
stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
}
} else {
/* The unbuffered mode is being employed. */
/* A buffer should not have been supplied by the caller. */
assert(!buf);
/* Use a trivial one-character buffer. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
stream->ptr_ = stream->bufstart_;
stream->cnt_ = 0;
stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
}
| 23,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,
pmd_t *pmd, unsigned int flags)
{
int result;
handle_t *handle = NULL;
struct inode *inode = file_inode(vma->vm_file);
struct super_block *sb = inode->i_sb;
bool write = flags & FAULT_FLAG_WRITE;
if (write) {
sb_start_pagefault(sb);
file_update_time(vma->vm_file);
handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
ext4_chunk_trans_blocks(inode,
PMD_SIZE / PAGE_SIZE));
}
if (IS_ERR(handle))
result = VM_FAULT_SIGBUS;
else
result = __dax_pmd_fault(vma, addr, pmd, flags,
ext4_get_block_dax, ext4_end_io_unwritten);
if (write) {
if (!IS_ERR(handle))
ext4_journal_stop(handle);
sb_end_pagefault(sb);
}
return result;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <jack@suse.com>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-362 | static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,
pmd_t *pmd, unsigned int flags)
{
int result;
handle_t *handle = NULL;
struct inode *inode = file_inode(vma->vm_file);
struct super_block *sb = inode->i_sb;
bool write = flags & FAULT_FLAG_WRITE;
if (write) {
sb_start_pagefault(sb);
file_update_time(vma->vm_file);
down_read(&EXT4_I(inode)->i_mmap_sem);
handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
ext4_chunk_trans_blocks(inode,
PMD_SIZE / PAGE_SIZE));
} else
down_read(&EXT4_I(inode)->i_mmap_sem);
if (IS_ERR(handle))
result = VM_FAULT_SIGBUS;
else
result = __dax_pmd_fault(vma, addr, pmd, flags,
ext4_get_block_dax, ext4_end_io_unwritten);
if (write) {
if (!IS_ERR(handle))
ext4_journal_stop(handle);
up_read(&EXT4_I(inode)->i_mmap_sem);
sb_end_pagefault(sb);
} else
up_read(&EXT4_I(inode)->i_mmap_sem);
return result;
}
| 17,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. | Code: void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
if (spdy_proxy_auth_enabled_.GetValue() != enabled) {
spdy_proxy_auth_enabled_.SetValue(enabled);
OnProxyEnabledPrefChange();
#if defined(OS_ANDROID)
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(enabled);
#endif // defined(OS_ANDROID)
}
}
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 <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
if (GetOriginalProfilePrefs()->GetBoolean(prefs::kDataSaverEnabled) !=
enabled) {
GetOriginalProfilePrefs()->SetBoolean(prefs::kDataSaverEnabled, enabled);
OnProxyEnabledPrefChange();
#if defined(OS_ANDROID)
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(enabled);
#endif // defined(OS_ANDROID)
}
}
| 8,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int re_yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | int re_yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
| 13,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: stringprep (char *in,
size_t maxlen,
Stringprep_profile_flags flags,
const Stringprep_profile * profile)
{
int rc;
char *utf8 = NULL;
uint32_t *ucs4 = NULL;
size_t ucs4len, maxucs4len, adducs4len = 50;
do
{
uint32_t *newp;
free (ucs4);
ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len);
maxucs4len = ucs4len + adducs4len;
newp = realloc (ucs4, maxucs4len * sizeof (uint32_t));
if (!newp)
return STRINGPREP_MALLOC_ERROR;
}
ucs4 = newp;
rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile);
adducs4len += 50;
}
Commit Message:
CWE ID: CWE-119 | stringprep (char *in,
size_t maxlen,
Stringprep_profile_flags flags,
const Stringprep_profile * profile)
{
int rc;
char *utf8 = NULL;
uint32_t *ucs4 = NULL;
size_t ucs4len, maxucs4len, adducs4len = 50;
do
{
uint32_t *newp;
free (ucs4);
ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len);
if (ucs4 == NULL)
return STRINGPREP_ICONV_ERROR;
maxucs4len = ucs4len + adducs4len;
newp = realloc (ucs4, maxucs4len * sizeof (uint32_t));
if (!newp)
return STRINGPREP_MALLOC_ERROR;
}
ucs4 = newp;
rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile);
adducs4len += 50;
}
| 17,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < ETH_MAX_L2_HDR_LEN) {
l2_hdr->iov_len = 0;
return false;
} else {
l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
Commit Message:
CWE ID: CWE-20 | static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
| 2,562 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
if (!context || data || (scanline == 0))
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
if (context->priv->PlaneBuffersLength < rw * scanline)
return FALSE;
if (rw < scanline * 2)
return FALSE;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
return TRUE;
}
| 12,958 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int ras_validate(jas_stream_t *in)
{
uchar buf[RAS_MAGICLEN];
int i;
int n;
uint_fast32_t magic;
assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < RAS_MAGICLEN) {
return -1;
}
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Is the signature correct for the Sun Rasterfile format? */
if (magic != RAS_MAGIC) {
return -1;
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | int ras_validate(jas_stream_t *in)
{
jas_uchar buf[RAS_MAGICLEN];
int i;
int n;
uint_fast32_t magic;
assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < RAS_MAGICLEN) {
return -1;
}
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Is the signature correct for the Sun Rasterfile format? */
if (magic != RAS_MAGIC) {
return -1;
}
return 0;
}
| 15,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT(
GLenum target,
GLuint id,
int32_t sync_shm_id,
uint32_t sync_shm_offset) {
GLuint service_id = GetQueryServiceID(id, &query_id_map_);
QueryInfo* query_info = &query_info_map_[service_id];
scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id);
if (!buffer)
return error::kInvalidArguments;
QuerySync* sync = static_cast<QuerySync*>(
buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync)));
if (!sync)
return error::kOutOfBounds;
if (IsEmulatedQueryTarget(target)) {
if (active_queries_.find(target) != active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "Query already active on target.");
return error::kNoError;
}
if (id == 0) {
InsertError(GL_INVALID_OPERATION, "Query id is 0.");
return error::kNoError;
}
if (query_info->type != GL_NONE && query_info->type != target) {
InsertError(GL_INVALID_OPERATION,
"Query type does not match the target.");
return error::kNoError;
}
} else {
CheckErrorCallbackState();
api()->glBeginQueryFn(target, service_id);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
query_info->type = target;
RemovePendingQuery(service_id);
ActiveQuery query;
query.service_id = service_id;
query.shm = std::move(buffer);
query.sync = sync;
active_queries_[target] = std::move(query);
return error::kNoError;
}
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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT(
GLenum target,
GLuint id,
int32_t sync_shm_id,
uint32_t sync_shm_offset) {
GLuint service_id = GetQueryServiceID(id, &query_id_map_);
QueryInfo* query_info = &query_info_map_[service_id];
scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id);
if (!buffer)
return error::kInvalidArguments;
QuerySync* sync = static_cast<QuerySync*>(
buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync)));
if (!sync)
return error::kOutOfBounds;
if (target == GL_PROGRAM_COMPLETION_QUERY_CHROMIUM) {
linking_program_service_id_ = 0u;
}
if (IsEmulatedQueryTarget(target)) {
if (active_queries_.find(target) != active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "Query already active on target.");
return error::kNoError;
}
if (id == 0) {
InsertError(GL_INVALID_OPERATION, "Query id is 0.");
return error::kNoError;
}
if (query_info->type != GL_NONE && query_info->type != target) {
InsertError(GL_INVALID_OPERATION,
"Query type does not match the target.");
return error::kNoError;
}
} else {
CheckErrorCallbackState();
api()->glBeginQueryFn(target, service_id);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
query_info->type = target;
RemovePendingQuery(service_id);
ActiveQuery query;
query.service_id = service_id;
query.shm = std::move(buffer);
query.sync = sync;
active_queries_[target] = std::move(query);
return error::kNoError;
}
| 13,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
CWE ID: CWE-119 | static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (!r->iov.iov_base) {
r->buflen = SCSI_DMA_BUF_SIZE;
r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
}
r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
| 23,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op)
{
WORD32 ret = IV_SUCCESS;
codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle);
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
WORD32 proc_idx = 0;
WORD32 prev_proc_idx = 0;
/* Initialize error code */
ps_codec->i4_error_code = 0;
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size; //Restore size field
}
if(ps_codec->i4_init_done != 1)
{
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE;
return IV_FAIL;
}
if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED;
return IV_FAIL;
}
/* If reset flag is set, flush the existing buffers */
if(ps_codec->i4_reset_flag)
{
ps_codec->i4_flush_mode = 1;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
/* In case the decoder is not in flush mode check for input buffer validity */
if(0 == ps_codec->i4_flush_mode)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN)
{
if((WORD32)ps_dec_ip->u4_num_Bytes > 0)
ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes;
else
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
#ifdef APPLY_CONCEALMENT
{
WORD32 num_mbs;
num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8;
/* Reset MB Count at the beginning of every process call */
ps_codec->mb_count = 0;
memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3));
}
#endif
if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0)
{
UWORD32 i;
if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++)
{
if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_codec->u4_ts = ps_dec_ip->u4_ts;
if(ps_codec->i4_flush_mode)
{
ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd;
ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht;
ps_dec_op->u4_new_seq = 0;
ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get(
(disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id);
/* In case of non-shared mode, then convert/copy the frame to output buffer */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
if((ps_codec->ps_disp_buf)
&& ((0 == ps_codec->i4_share_disp_buf)
|| (IV_YUV_420P
== ps_codec->e_chroma_fmt)))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx];
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
/* Set remaining number of rows to be processed */
ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx],
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], 0,
ps_codec->i4_disp_ht);
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->i4_disp_buf_id, BUF_MGR_DISP);
}
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
if(1 == ps_dec_op->u4_output_present)
{
WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD;
WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT;
if(ypos < 0)
ypos = 0;
if(xpos < 0)
xpos = 0;
INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd,
xpos,
ypos,
ps_codec->e_chroma_fmt,
ps_codec->i4_disp_wd,
ps_codec->i4_disp_ht);
}
if(NULL == ps_codec->ps_disp_buf)
{
/* If in flush mode and there are no more buffers to flush,
* check for the reset flag and reset the decoder */
if(ps_codec->i4_reset_flag)
{
ihevcd_init(ps_codec);
}
return (IV_FAIL);
}
return (IV_SUCCESS);
}
/* In case of shared mode, check if there is a free buffer for reconstruction */
if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf))
{
WORD32 buf_status;
buf_status = 1;
if(ps_codec->pv_pic_buf_mgr)
buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr);
/* If there is no free buffer, then return with an error code */
if(0 == buf_status)
{
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return IV_FAIL;
}
}
ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes;
ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer;
ps_codec->s_parse.i4_end_of_frame = 0;
ps_codec->i4_pic_present = 0;
ps_codec->i4_slice_error = 0;
ps_codec->ps_disp_buf = NULL;
if(ps_codec->i4_num_cores > 1)
{
ithread_set_affinity(0);
}
while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining)
{
WORD32 nal_len;
WORD32 nal_ofst;
WORD32 bits_len;
if(ps_codec->i4_slice_error)
{
slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x +
ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb;
if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr)
ps_codec->i4_slice_error = 0;
}
if(ps_codec->pu1_bitsbuf_dynamic)
{
ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic;
ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic;
}
else
{
ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static;
ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static;
}
nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf,
ps_codec->i4_bytes_remaining);
ps_codec->i4_nal_ofst = nal_ofst;
{
WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst;
bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size);
ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst,
ps_codec->pu1_bitsbuf,
bytes_remaining,
&nal_len, &bits_len);
/* Decoder may read upto 8 extra bytes at the end of frame */
/* These are not used, but still set them to zero to avoid uninitialized reads */
if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8))
{
memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32));
}
}
/* This may be used to update the offsets for tiles and entropy sync row offsets */
ps_codec->i4_num_emln_bytes = nal_len - bits_len;
ps_codec->i4_nal_len = nal_len;
ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf,
bits_len);
ret = ihevcd_nal_unit(ps_codec);
/* If the frame is incomplete and
* the bytes remaining is zero or a header is received,
* complete the frame treating it to be in error */
if(ps_codec->i4_pic_present &&
(ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb))
{
if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) ||
(ps_codec->i4_header_in_slice_mode))
{
slice_header_t *ps_slice_hdr_next;
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;
ps_codec->i4_slice_error = 1;
continue;
}
}
if(IHEVCD_IGNORE_SLICE == ret)
{
ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len);
ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len);
continue;
}
if((IVD_RES_CHANGED == ret) ||
(IHEVCD_UNSUPPORTED_DIMENSIONS == ret))
{
break;
}
/* Update bytes remaining and bytes consumed and input bitstream pointer */
/* Do not consume the NAL in the following cases */
/* Slice header reached during header decode mode */
/* TODO: Next picture's slice reached */
if(ret != IHEVCD_SLICE_IN_HEADER_MODE)
{
if((0 == ps_codec->i4_slice_error) ||
(ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN))
{
ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len);
ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len);
}
if(ret != IHEVCD_SUCCESS)
break;
if(ps_codec->s_parse.i4_end_of_frame)
break;
}
else
{
ret = IHEVCD_SUCCESS;
break;
}
/* Allocate dynamic bitstream buffer once SPS is decoded */
if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done)
{
WORD32 ret;
ret = ihevcd_allocate_dynamic_bufs(ps_codec);
if(ret != IV_SUCCESS)
{
/* Free any dynamic buffers that are allocated */
ihevcd_free_dynamic_bufs(ps_codec);
ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED;
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED;
return IV_FAIL;
}
}
BREAK_AFTER_SLICE_NAL();
}
if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS))
{
ps_codec->i4_error_code = ret;
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
return IV_FAIL;
}
if(1 == ps_codec->i4_pic_present)
{
WORD32 i;
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->i4_first_pic_done = 1;
/*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */
if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame)
{
/* Add job queue for format conversion / frame copy for each ctb row */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
process_ctxt_t *ps_proc;
/* i4_num_cores - 1 contexts are currently being used by other threads */
ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1];
if((ps_codec->ps_disp_buf) &&
((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt)))
{
/* If format conversion jobs were not issued in pic_init() add them here */
if((0 == ps_codec->u4_enable_fmt_conv_ahead) ||
(ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id))
for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++)
{
proc_job_t s_job;
IHEVCD_ERROR_T ret;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i2_ctb_cnt = 0;
s_job.i2_ctb_x = 0;
s_job.i2_ctb_y = i;
s_job.i2_slice_idx = 0;
s_job.i4_tu_coeff_data_ofst = 0;
ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq,
&s_job, sizeof(proc_job_t), 1);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
return (WORD32)ret;
}
}
/* Reached end of frame : Signal terminate */
/* The terminate flag is checked only after all the jobs are dequeued */
ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq);
while(1)
{
IHEVCD_ERROR_T ret;
proc_job_t s_job;
process_ctxt_t *ps_proc;
/* i4_num_cores - 1 contexts are currently being used by other threads */
ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1];
ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job,
sizeof(proc_job_t), 1);
if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret)
break;
ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt;
ps_proc->i4_ctb_x = s_job.i2_ctb_x;
ps_proc->i4_ctb_y = s_job.i2_ctb_y;
ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx;
if(CMD_PROCESS == s_job.i4_cmd)
{
ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst);
ihevcd_process(ps_proc);
}
else if(CMD_FMTCONV == s_job.i4_cmd)
{
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size;
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size)));
if(num_rows < 0)
num_rows = 0;
ihevcd_fmt_conv(ps_codec, ps_proc,
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2],
s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size,
num_rows);
}
}
}
/* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) ||
(IV_YUV_420P == ps_codec->e_chroma_fmt)) &&
(ps_codec->s_parse.i4_end_of_frame))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx];
/* Set remaining number of rows to be processed */
ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht
- ps_codec->s_fmt_conv.i4_cur_row;
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
if(ps_codec->s_fmt_conv.i4_num_rows < 0)
ps_codec->s_fmt_conv.i4_num_rows = 0;
ret = ihevcd_fmt_conv(ps_codec, ps_proc,
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2],
ps_codec->s_fmt_conv.i4_cur_row,
ps_codec->s_fmt_conv.i4_num_rows);
ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows;
}
DEBUG_DUMP_MV_MAP(ps_codec);
/* Mark MV Buf as needed for reference */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id,
BUF_MGR_REF);
/* Mark pic buf as needed for reference */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id,
BUF_MGR_REF);
/* Mark pic buf as needed for display */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id,
BUF_MGR_DISP);
/* Insert the current picture as short term reference */
ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr,
ps_codec->as_process[proc_idx].ps_cur_pic,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id);
/* If a frame was displayed (in non-shared mode), then release it from display manager */
if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf))
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->i4_disp_buf_id, BUF_MGR_DISP);
/* Wait for threads */
for(i = 0; i < (ps_codec->i4_num_cores - 1); i++)
{
if(ps_codec->ai4_process_thread_created[i])
{
ithread_join(ps_codec->apv_process_thread_handle[i], NULL);
ps_codec->ai4_process_thread_created[i] = 0;
}
}
DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]);
if(ps_codec->u4_pic_cnt > 0)
{
DEBUG_DUMP_PIC_PU(ps_codec);
}
DEBUG_DUMP_PIC_BUFFERS(ps_codec);
/* Increment the number of pictures decoded */
ps_codec->u4_pic_cnt++;
}
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
if(1 == ps_dec_op->u4_output_present)
{
WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD;
WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT;
if(ypos < 0)
ypos = 0;
if(xpos < 0)
xpos = 0;
INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd,
xpos,
ypos,
ps_codec->e_chroma_fmt,
ps_codec->i4_disp_wd,
ps_codec->i4_disp_ht);
}
return ret;
}
Commit Message: Handle invalid slice_address in slice header
If an invalid slice_address was parsed, it was resulting in an incomplete
slice header during decode stage. Fix this by not incrementing slice_idx
for ignore slice error
Bug: 32322258
Change-Id: I8638d7094d65f4409faa9b9e337ef7e7b64505de
(cherry picked from commit f4f3556e04a9776bcc776523ae0763e7d0d5c668)
CWE ID: | WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op)
{
WORD32 ret = IV_SUCCESS;
codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle);
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
WORD32 proc_idx = 0;
WORD32 prev_proc_idx = 0;
/* Initialize error code */
ps_codec->i4_error_code = 0;
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size; //Restore size field
}
if(ps_codec->i4_init_done != 1)
{
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE;
return IV_FAIL;
}
if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED;
return IV_FAIL;
}
/* If reset flag is set, flush the existing buffers */
if(ps_codec->i4_reset_flag)
{
ps_codec->i4_flush_mode = 1;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
/* In case the decoder is not in flush mode check for input buffer validity */
if(0 == ps_codec->i4_flush_mode)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN)
{
if((WORD32)ps_dec_ip->u4_num_Bytes > 0)
ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes;
else
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
#ifdef APPLY_CONCEALMENT
{
WORD32 num_mbs;
num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8;
/* Reset MB Count at the beginning of every process call */
ps_codec->mb_count = 0;
memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3));
}
#endif
if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0)
{
UWORD32 i;
if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++)
{
if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_codec->u4_ts = ps_dec_ip->u4_ts;
if(ps_codec->i4_flush_mode)
{
ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd;
ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht;
ps_dec_op->u4_new_seq = 0;
ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get(
(disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id);
/* In case of non-shared mode, then convert/copy the frame to output buffer */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
if((ps_codec->ps_disp_buf)
&& ((0 == ps_codec->i4_share_disp_buf)
|| (IV_YUV_420P
== ps_codec->e_chroma_fmt)))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx];
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
/* Set remaining number of rows to be processed */
ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx],
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], 0,
ps_codec->i4_disp_ht);
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->i4_disp_buf_id, BUF_MGR_DISP);
}
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
if(1 == ps_dec_op->u4_output_present)
{
WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD;
WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT;
if(ypos < 0)
ypos = 0;
if(xpos < 0)
xpos = 0;
INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd,
xpos,
ypos,
ps_codec->e_chroma_fmt,
ps_codec->i4_disp_wd,
ps_codec->i4_disp_ht);
}
if(NULL == ps_codec->ps_disp_buf)
{
/* If in flush mode and there are no more buffers to flush,
* check for the reset flag and reset the decoder */
if(ps_codec->i4_reset_flag)
{
ihevcd_init(ps_codec);
}
return (IV_FAIL);
}
return (IV_SUCCESS);
}
/* In case of shared mode, check if there is a free buffer for reconstruction */
if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf))
{
WORD32 buf_status;
buf_status = 1;
if(ps_codec->pv_pic_buf_mgr)
buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr);
/* If there is no free buffer, then return with an error code */
if(0 == buf_status)
{
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return IV_FAIL;
}
}
ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes;
ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer;
ps_codec->s_parse.i4_end_of_frame = 0;
ps_codec->i4_pic_present = 0;
ps_codec->i4_slice_error = 0;
ps_codec->ps_disp_buf = NULL;
if(ps_codec->i4_num_cores > 1)
{
ithread_set_affinity(0);
}
while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining)
{
WORD32 nal_len;
WORD32 nal_ofst;
WORD32 bits_len;
if(ps_codec->i4_slice_error)
{
slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x +
ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb;
if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr)
ps_codec->i4_slice_error = 0;
}
if(ps_codec->pu1_bitsbuf_dynamic)
{
ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic;
ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic;
}
else
{
ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static;
ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static;
}
nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf,
ps_codec->i4_bytes_remaining);
ps_codec->i4_nal_ofst = nal_ofst;
{
WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst;
bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size);
ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst,
ps_codec->pu1_bitsbuf,
bytes_remaining,
&nal_len, &bits_len);
/* Decoder may read upto 8 extra bytes at the end of frame */
/* These are not used, but still set them to zero to avoid uninitialized reads */
if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8))
{
memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32));
}
}
/* This may be used to update the offsets for tiles and entropy sync row offsets */
ps_codec->i4_num_emln_bytes = nal_len - bits_len;
ps_codec->i4_nal_len = nal_len;
ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf,
bits_len);
ret = ihevcd_nal_unit(ps_codec);
/* If the frame is incomplete and
* the bytes remaining is zero or a header is received,
* complete the frame treating it to be in error */
if(ps_codec->i4_pic_present &&
(ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb))
{
if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) ||
(ps_codec->i4_header_in_slice_mode))
{
slice_header_t *ps_slice_hdr_next;
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;
ps_codec->i4_slice_error = 1;
continue;
}
}
if(IHEVCD_IGNORE_SLICE == ret)
{
ps_codec->s_parse.i4_cur_slice_idx = MAX(0, (ps_codec->s_parse.i4_cur_slice_idx - 1));
ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len);
ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len);
continue;
}
if((IVD_RES_CHANGED == ret) ||
(IHEVCD_UNSUPPORTED_DIMENSIONS == ret))
{
break;
}
/* Update bytes remaining and bytes consumed and input bitstream pointer */
/* Do not consume the NAL in the following cases */
/* Slice header reached during header decode mode */
/* TODO: Next picture's slice reached */
if(ret != IHEVCD_SLICE_IN_HEADER_MODE)
{
if((0 == ps_codec->i4_slice_error) ||
(ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN))
{
ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len);
ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len);
}
if(ret != IHEVCD_SUCCESS)
break;
if(ps_codec->s_parse.i4_end_of_frame)
break;
}
else
{
ret = IHEVCD_SUCCESS;
break;
}
/* Allocate dynamic bitstream buffer once SPS is decoded */
if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done)
{
WORD32 ret;
ret = ihevcd_allocate_dynamic_bufs(ps_codec);
if(ret != IV_SUCCESS)
{
/* Free any dynamic buffers that are allocated */
ihevcd_free_dynamic_bufs(ps_codec);
ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED;
ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR;
ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED;
return IV_FAIL;
}
}
BREAK_AFTER_SLICE_NAL();
}
if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS))
{
ps_codec->i4_error_code = ret;
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
return IV_FAIL;
}
if(1 == ps_codec->i4_pic_present)
{
WORD32 i;
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->i4_first_pic_done = 1;
/*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */
if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame)
{
/* Add job queue for format conversion / frame copy for each ctb row */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
process_ctxt_t *ps_proc;
/* i4_num_cores - 1 contexts are currently being used by other threads */
ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1];
if((ps_codec->ps_disp_buf) &&
((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt)))
{
/* If format conversion jobs were not issued in pic_init() add them here */
if((0 == ps_codec->u4_enable_fmt_conv_ahead) ||
(ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id))
for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++)
{
proc_job_t s_job;
IHEVCD_ERROR_T ret;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i2_ctb_cnt = 0;
s_job.i2_ctb_x = 0;
s_job.i2_ctb_y = i;
s_job.i2_slice_idx = 0;
s_job.i4_tu_coeff_data_ofst = 0;
ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq,
&s_job, sizeof(proc_job_t), 1);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
return (WORD32)ret;
}
}
/* Reached end of frame : Signal terminate */
/* The terminate flag is checked only after all the jobs are dequeued */
ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq);
while(1)
{
IHEVCD_ERROR_T ret;
proc_job_t s_job;
process_ctxt_t *ps_proc;
/* i4_num_cores - 1 contexts are currently being used by other threads */
ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1];
ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job,
sizeof(proc_job_t), 1);
if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret)
break;
ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt;
ps_proc->i4_ctb_x = s_job.i2_ctb_x;
ps_proc->i4_ctb_y = s_job.i2_ctb_y;
ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx;
if(CMD_PROCESS == s_job.i4_cmd)
{
ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst);
ihevcd_process(ps_proc);
}
else if(CMD_FMTCONV == s_job.i4_cmd)
{
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size;
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size)));
if(num_rows < 0)
num_rows = 0;
ihevcd_fmt_conv(ps_codec, ps_proc,
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2],
s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size,
num_rows);
}
}
}
/* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */
/* Only if the codec is in non-shared mode or in shared mode but needs 420P output */
else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) ||
(IV_YUV_420P == ps_codec->e_chroma_fmt)) &&
(ps_codec->s_parse.i4_end_of_frame))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx];
/* Set remaining number of rows to be processed */
ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht
- ps_codec->s_fmt_conv.i4_cur_row;
if(0 == ps_proc->i4_init_done)
{
ihevcd_init_proc_ctxt(ps_proc, 0);
}
if(ps_codec->s_fmt_conv.i4_num_rows < 0)
ps_codec->s_fmt_conv.i4_num_rows = 0;
ret = ihevcd_fmt_conv(ps_codec, ps_proc,
ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2],
ps_codec->s_fmt_conv.i4_cur_row,
ps_codec->s_fmt_conv.i4_num_rows);
ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows;
}
DEBUG_DUMP_MV_MAP(ps_codec);
/* Mark MV Buf as needed for reference */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id,
BUF_MGR_REF);
/* Mark pic buf as needed for reference */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id,
BUF_MGR_REF);
/* Mark pic buf as needed for display */
ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id,
BUF_MGR_DISP);
/* Insert the current picture as short term reference */
ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr,
ps_codec->as_process[proc_idx].ps_cur_pic,
ps_codec->as_process[proc_idx].i4_cur_pic_buf_id);
/* If a frame was displayed (in non-shared mode), then release it from display manager */
if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf))
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr,
ps_codec->i4_disp_buf_id, BUF_MGR_DISP);
/* Wait for threads */
for(i = 0; i < (ps_codec->i4_num_cores - 1); i++)
{
if(ps_codec->ai4_process_thread_created[i])
{
ithread_join(ps_codec->apv_process_thread_handle[i], NULL);
ps_codec->ai4_process_thread_created[i] = 0;
}
}
DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]);
if(ps_codec->u4_pic_cnt > 0)
{
DEBUG_DUMP_PIC_PU(ps_codec);
}
DEBUG_DUMP_PIC_BUFFERS(ps_codec);
/* Increment the number of pictures decoded */
ps_codec->u4_pic_cnt++;
}
ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op);
if(1 == ps_dec_op->u4_output_present)
{
WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD;
WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT;
if(ypos < 0)
ypos = 0;
if(xpos < 0)
xpos = 0;
INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd,
xpos,
ypos,
ps_codec->e_chroma_fmt,
ps_codec->i4_disp_wd,
ps_codec->i4_disp_ht);
}
return ret;
}
| 16,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool LayoutSVGTransformableContainer::calculateLocalTransform()
{
SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
ASSERT(element);
SVGUseElement* useElement = nullptr;
if (isSVGUseElement(*element)) {
useElement = toSVGUseElement(element);
} else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) {
SVGElement* correspondingElement = element->correspondingElement();
if (isSVGUseElement(correspondingElement))
useElement = toSVGUseElement(correspondingElement);
}
if (useElement) {
SVGLengthContext lengthContext(useElement);
FloatSize translation(
useElement->x()->currentValue()->value(lengthContext),
useElement->y()->currentValue()->value(lengthContext));
if (translation != m_additionalTranslation)
m_needsTransformUpdate = true;
m_additionalTranslation = translation;
}
if (!m_needsTransformUpdate)
return false;
m_localTransform = element->calculateAnimatedLocalTransform();
m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height());
m_needsTransformUpdate = false;
return true;
}
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: | bool LayoutSVGTransformableContainer::calculateLocalTransform()
void LayoutSVGTransformableContainer::setNeedsTransformUpdate()
{
setMayNeedPaintInvalidationSubtree();
m_needsTransformUpdate = true;
}
static std::pair<double, double> scaleReference(const AffineTransform& transform)
{
return std::make_pair(transform.xScaleSquared(), transform.yScaleSquared());
}
LayoutSVGContainer::TransformChange LayoutSVGTransformableContainer::calculateLocalTransform()
{
SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
ASSERT(element);
SVGUseElement* useElement = nullptr;
if (isSVGUseElement(*element)) {
useElement = toSVGUseElement(element);
} else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) {
SVGElement* correspondingElement = element->correspondingElement();
if (isSVGUseElement(correspondingElement))
useElement = toSVGUseElement(correspondingElement);
}
if (useElement) {
SVGLengthContext lengthContext(useElement);
FloatSize translation(
useElement->x()->currentValue()->value(lengthContext),
useElement->y()->currentValue()->value(lengthContext));
// TODO(fs): Signal this on style update instead. (Since these are
// suppose to be presentation attributes now, this does feel a bit
// broken...)
if (translation != m_additionalTranslation)
setNeedsTransformUpdate();
m_additionalTranslation = translation;
}
if (!m_needsTransformUpdate)
return TransformChange::None;
std::pair<double, double> oldScale = scaleReference(m_localTransform);
m_localTransform = element->calculateAnimatedLocalTransform();
m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height());
m_needsTransformUpdate = false;
return scaleReference(m_localTransform) != oldScale
? TransformChange::Full : TransformChange::ScaleInvariant;
}
| 22,134 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool GLSurfaceEGLSurfaceControl::SupportsSwapBuffersWithBounds() {
return false;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
R=piman@chromium.org
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <khushalsagar@chromium.org>
Commit-Queue: Antoine Labour <piman@chromium.org>
Reviewed-by: Antoine Labour <piman@chromium.org>
Auto-Submit: Khushal <khushalsagar@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | bool GLSurfaceEGLSurfaceControl::SupportsSwapBuffersWithBounds() {
| 9,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void HistoryController::UpdateForCommit(RenderFrameImpl* frame,
const WebHistoryItem& item,
WebHistoryCommitType commit_type,
bool navigation_within_page) {
switch (commit_type) {
case blink::WebBackForwardCommit:
if (!provisional_entry_)
return;
current_entry_.reset(provisional_entry_.release());
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
node->set_item(item);
}
break;
case blink::WebStandardCommit:
CreateNewBackForwardItem(frame, item, navigation_within_page);
break;
case blink::WebInitialCommitInChildFrame:
UpdateForInitialLoadInChildFrame(frame, item);
break;
case blink::WebHistoryInertCommit:
if (current_entry_) {
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
if (!navigation_within_page)
node->RemoveChildren();
node->set_item(item);
}
}
break;
default:
NOTREACHED() << "Invalid commit type: " << commit_type;
}
}
Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry.
BUG=597322
TEST=See bug for repro steps.
Review URL: https://codereview.chromium.org/1848103004
Cr-Commit-Position: refs/heads/master@{#384659}
CWE ID: CWE-254 | void HistoryController::UpdateForCommit(RenderFrameImpl* frame,
const WebHistoryItem& item,
WebHistoryCommitType commit_type,
bool navigation_within_page) {
switch (commit_type) {
case blink::WebBackForwardCommit:
if (!provisional_entry_)
return;
// Commit the provisional entry, but only if this back/forward item
// matches it. Otherwise it could be a commit from an earlier attempt to
// go back/forward, and we should leave the provisional entry in place.
if (HistoryEntry::HistoryNode* node =
provisional_entry_->GetHistoryNodeForFrame(frame)) {
if (node->item().itemSequenceNumber() == item.itemSequenceNumber())
current_entry_.reset(provisional_entry_.release());
}
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
node->set_item(item);
}
break;
case blink::WebStandardCommit:
CreateNewBackForwardItem(frame, item, navigation_within_page);
break;
case blink::WebInitialCommitInChildFrame:
UpdateForInitialLoadInChildFrame(frame, item);
break;
case blink::WebHistoryInertCommit:
if (current_entry_) {
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
if (!navigation_within_page)
node->RemoveChildren();
node->set_item(item);
}
}
break;
default:
NOTREACHED() << "Invalid commit type: " << commit_type;
}
}
| 1,402 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: scoped_refptr<VideoFrame> CloneVideoFrameWithLayout(
const VideoFrame* const src_frame,
const VideoFrameLayout& dst_layout) {
LOG_ASSERT(src_frame->IsMappable());
LOG_ASSERT(src_frame->format() == dst_layout.format());
auto dst_frame = VideoFrame::CreateFrameWithLayout(
dst_layout, src_frame->visible_rect(), src_frame->natural_size(),
src_frame->timestamp(), false /* zero_initialize_memory*/);
if (!dst_frame) {
LOG(ERROR) << "Failed to create VideoFrame";
return nullptr;
}
const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format());
LOG_ASSERT(dst_layout.planes().size() == num_planes);
LOG_ASSERT(src_frame->layout().planes().size() == num_planes);
for (size_t i = 0; i < num_planes; ++i) {
libyuv::CopyPlane(
src_frame->data(i), src_frame->layout().planes()[i].stride,
dst_frame->data(i), dst_frame->layout().planes()[i].stride,
VideoFrame::Columns(i, dst_frame->format(),
dst_frame->natural_size().width()),
VideoFrame::Rows(i, dst_frame->format(),
dst_frame->natural_size().height()));
}
return dst_frame;
}
Commit Message: media/gpu/test: ImageProcessorClient: Use bytes for width and height in libyuv::CopyPlane()
|width| is in bytes in libyuv::CopyPlane(). We formerly pass width in pixels.
This should matter when a pixel format is used whose pixel is composed of
more than one bytes.
Bug: None
Test: image_processor_test
Change-Id: I98e90be70c8d0128319172d4d19f3a8017b65d78
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1553129
Commit-Queue: Hirokazu Honda <hiroh@chromium.org>
Reviewed-by: Alexandre Courbot <acourbot@chromium.org>
Cr-Commit-Position: refs/heads/master@{#648117}
CWE ID: CWE-20 | scoped_refptr<VideoFrame> CloneVideoFrameWithLayout(
const VideoFrame* const src_frame,
const VideoFrameLayout& dst_layout) {
LOG_ASSERT(src_frame->IsMappable());
LOG_ASSERT(src_frame->format() == dst_layout.format());
auto dst_frame = VideoFrame::CreateFrameWithLayout(
dst_layout, src_frame->visible_rect(), src_frame->natural_size(),
src_frame->timestamp(), false /* zero_initialize_memory*/);
if (!dst_frame) {
LOG(ERROR) << "Failed to create VideoFrame";
return nullptr;
}
const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format());
LOG_ASSERT(dst_layout.planes().size() == num_planes);
LOG_ASSERT(src_frame->layout().planes().size() == num_planes);
for (size_t i = 0; i < num_planes; ++i) {
// |width| in libyuv::CopyPlane() is in bytes, not pixels.
gfx::Size plane_size = VideoFrame::PlaneSize(dst_frame->format(), i,
dst_frame->natural_size());
libyuv::CopyPlane(
src_frame->data(i), src_frame->layout().planes()[i].stride,
dst_frame->data(i), dst_frame->layout().planes()[i].stride,
plane_size.width(), plane_size.height());
}
return dst_frame;
}
| 23,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int rt_fill_info(struct net *net, __be32 dst, __be32 src,
struct flowi4 *fl4, struct sk_buff *skb, u32 portid,
u32 seq, int event, int nowait, unsigned int flags)
{
struct rtable *rt = skb_rtable(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned long expires = 0;
u32 error;
u32 metrics[RTAX_MAX];
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags);
if (nlh == NULL)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_INET;
r->rtm_dst_len = 32;
r->rtm_src_len = 0;
r->rtm_tos = fl4->flowi4_tos;
r->rtm_table = RT_TABLE_MAIN;
if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN))
goto nla_put_failure;
r->rtm_type = rt->rt_type;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (nla_put_be32(skb, RTA_DST, dst))
goto nla_put_failure;
if (src) {
r->rtm_src_len = 32;
if (nla_put_be32(skb, RTA_SRC, src))
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
#ifdef CONFIG_IP_ROUTE_CLASSID
if (rt->dst.tclassid &&
nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
goto nla_put_failure;
#endif
if (!rt_is_input_route(rt) &&
fl4->saddr != src) {
if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr))
goto nla_put_failure;
}
if (rt->rt_uses_gateway &&
nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway))
goto nla_put_failure;
expires = rt->dst.expires;
if (expires) {
unsigned long now = jiffies;
if (time_before(now, expires))
expires -= now;
else
expires = 0;
}
memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
if (rt->rt_pmtu && expires)
metrics[RTAX_MTU - 1] = rt->rt_pmtu;
if (rtnetlink_put_metrics(skb, metrics) < 0)
goto nla_put_failure;
if (fl4->flowi4_mark &&
nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
goto nla_put_failure;
error = rt->dst.error;
if (rt_is_input_route(rt)) {
#ifdef CONFIG_IP_MROUTE
if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) &&
IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
int err = ipmr_get_route(net, skb,
fl4->saddr, fl4->daddr,
r, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
error = err;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex))
goto nla_put_failure;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <ja@ssi.bg>
Signed-off-by: Marcelo Leitner <mleitner@redhat.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: Julian Anastasov <ja@ssi.bg>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-17 | static int rt_fill_info(struct net *net, __be32 dst, __be32 src,
struct flowi4 *fl4, struct sk_buff *skb, u32 portid,
u32 seq, int event, int nowait, unsigned int flags)
{
struct rtable *rt = skb_rtable(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned long expires = 0;
u32 error;
u32 metrics[RTAX_MAX];
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags);
if (nlh == NULL)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_INET;
r->rtm_dst_len = 32;
r->rtm_src_len = 0;
r->rtm_tos = fl4->flowi4_tos;
r->rtm_table = RT_TABLE_MAIN;
if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN))
goto nla_put_failure;
r->rtm_type = rt->rt_type;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (IPCB(skb)->flags & IPSKB_DOREDIRECT)
r->rtm_flags |= RTCF_DOREDIRECT;
if (nla_put_be32(skb, RTA_DST, dst))
goto nla_put_failure;
if (src) {
r->rtm_src_len = 32;
if (nla_put_be32(skb, RTA_SRC, src))
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
#ifdef CONFIG_IP_ROUTE_CLASSID
if (rt->dst.tclassid &&
nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
goto nla_put_failure;
#endif
if (!rt_is_input_route(rt) &&
fl4->saddr != src) {
if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr))
goto nla_put_failure;
}
if (rt->rt_uses_gateway &&
nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway))
goto nla_put_failure;
expires = rt->dst.expires;
if (expires) {
unsigned long now = jiffies;
if (time_before(now, expires))
expires -= now;
else
expires = 0;
}
memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
if (rt->rt_pmtu && expires)
metrics[RTAX_MTU - 1] = rt->rt_pmtu;
if (rtnetlink_put_metrics(skb, metrics) < 0)
goto nla_put_failure;
if (fl4->flowi4_mark &&
nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
goto nla_put_failure;
error = rt->dst.error;
if (rt_is_input_route(rt)) {
#ifdef CONFIG_IP_MROUTE
if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) &&
IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
int err = ipmr_get_route(net, skb,
fl4->saddr, fl4->daddr,
r, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
error = err;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex))
goto nla_put_failure;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
| 1,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: PowerPopupView() {
SetHorizontalAlignment(ALIGN_RIGHT);
UpdateText();
}
Commit Message: ash: Fix right-alignment of power-status text.
It turns out setting ALING_RIGHT on a Label isn't enough to get proper
right-aligned text. Label has to be explicitly told that it is multi-lined.
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/9918026
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@129898 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | PowerPopupView() {
SetHorizontalAlignment(ALIGN_RIGHT);
SetMultiLine(true);
UpdateText();
}
| 18,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long cs;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &ctxt->_eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->op_bytes == 4)
ctxt->_eip = (u32)ctxt->_eip;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
return rc;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: stable@vger.kernel.org
Signed-off-by: Nadav Amit <namit@cs.technion.ac.il>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-264 | static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, new_desc.l);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
| 20,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
Commit Message: KVM: x86: fix for buffer overflow in handling of MSR_KVM_SYSTEM_TIME (CVE-2013-1796)
If the guest sets the GPA of the time_page so that the request to update the
time straddles a page then KVM will write onto an incorrect page. The
write is done byusing kmap atomic to get a pointer to the page for the time
structure and then performing a memcpy to that page starting at an offset
that the guest controls. Well behaved guests always provide a 32-byte aligned
address, however a malicious guest could use this to corrupt host kernel
memory.
Tested: Tested against kvmclock unit test.
Signed-off-by: Andrew Honig <ahonig@google.com>
Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com>
CWE ID: CWE-119 | int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
/* Check that the address is 32-byte aligned. */
if (vcpu->arch.time_offset &
(sizeof(struct pvclock_vcpu_time_info) - 1))
break;
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
| 17,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <jfilak@redhat.com>
CWE ID: CWE-200 | static void ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
value = get_map_string_item_or_NULL(settings, "PrivateReports");
if (value)
{
g_settings_privatereports = string_to_bool(value);
remove_map_string_item(settings, "PrivateReports");
}
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
}
| 14,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
int64 item_length = static_cast<int64>(item.length());
if (item_length == -1)
item_length = result - item.offset();
DCHECK_LT(index, item_length_list_.size());
item_length_list_[index] = item_length;
total_size_ += item_length;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
uint64 file_length = result;
uint64 item_offset = item.offset();
uint64 item_length = item.length();
if (item_offset > file_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
uint64 max_length = file_length - item_offset;
if (item_length == static_cast<uint64>(-1)) {
item_length = max_length;
} else if (item_length > max_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
if (!AddItemLength(index, item_length))
return;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
| 21,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
netdev->ethtool_ops = &atl2_ethtool_ops;
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX;
netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX);
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
setup_timer(&adapter->watchdog_timer, atl2_watchdog,
(unsigned long)adapter);
setup_timer(&adapter->phy_config_timer, atl2_phy_config,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
Commit Message: atl2: Disable unimplemented scatter/gather feature
atl2 includes NETIF_F_SG in hw_features even though it has no support
for non-linear skbs. This bug was originally harmless since the
driver does not claim to implement checksum offload and that used to
be a requirement for SG.
Now that SG and checksum offload are independent features, if you
explicitly enable SG *and* use one of the rare protocols that can use
SG without checkusm offload, this potentially leaks sensitive
information (before you notice that it just isn't working). Therefore
this obscure bug has been designated CVE-2016-2117.
Reported-by: Justin Yackoski <jyackoski@crypto-nite.com>
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Fixes: ec5f06156423 ("net: Kill link between CSUM and SG features.")
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
netdev->ethtool_ops = &atl2_ethtool_ops;
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
netdev->hw_features = NETIF_F_HW_VLAN_CTAG_RX;
netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX);
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
setup_timer(&adapter->watchdog_timer, atl2_watchdog,
(unsigned long)adapter);
setup_timer(&adapter->phy_config_timer, atl2_phy_config,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
| 19,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual const ImePropertyList& current_ime_properties() const {
virtual const input_method::ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
| 15,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
{
int ret;
/* MBIM backwards compatible function? */
if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
return -ENODEV;
/* The NCM data altsetting is fixed, so we hard-coded it.
* Additionally, generic NCM devices are assumed to accept arbitrarily
* placed NDP.
*/
ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);
/*
* We should get an event when network connection is "connected" or
* "disconnected". Set network connection in "disconnected" state
* (carrier is OFF) during attach, so the IP network stack does not
* start IPv6 negotiation and more.
*/
usbnet_link_change(dev, 0, 0);
return ret;
}
Commit Message: cdc_ncm: do not call usbnet_link_change from cdc_ncm_bind
usbnet_link_change will call schedule_work and should be
avoided if bind is failing. Otherwise we will end up with
scheduled work referring to a netdev which has gone away.
Instead of making the call conditional, we can just defer
it to usbnet_probe, using the driver_info flag made for
this purpose.
Fixes: 8a34b0ae8778 ("usbnet: cdc_ncm: apply usbnet_link_change")
Reported-by: Andrey Konovalov <andreyknvl@gmail.com>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Bjørn Mork <bjorn@mork.no>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: | static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
{
/* MBIM backwards compatible function? */
if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
return -ENODEV;
/* The NCM data altsetting is fixed, so we hard-coded it.
* Additionally, generic NCM devices are assumed to accept arbitrarily
* placed NDP.
*/
return cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);
}
| 4,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
| 3,743 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t count = m->str_range;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, count) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o,
nbytes, count);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (nbytes < offset || nbytes < (offset + 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (nbytes < offset || nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) %
off;
break;
}
} else
offset = (short)((p->hs[0]<<8)|
(p->hs[1]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (nbytes < offset || nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) %
off;
break;
}
} else
offset = (short)((p->hs[1]<<8)|
(p->hs[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (nbytes < offset || nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (nbytes < offset || nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (nbytes < offset || nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (nbytes < offset || nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (nbytes < offset || nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (nbytes < (offset + 1)) /* should alway be true */
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (nbytes < (offset + 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (nbytes < (offset + 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (nbytes < (offset + 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (nbytes < (offset + m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(m->desc, "%u"), offset) == -1)
return -1;
if (file_printf(ms, "%s", rbuf) == -1)
return -1;
free(rbuf);
}
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
Commit Message: PR/313: Aaron Reffett: Check properly for exceeding the offset.
CWE ID: CWE-119 | mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t count = m->str_range;
int rv, oneed_separator, in_type;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, count) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o,
nbytes, count);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (in_type = cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) %
off;
break;
}
} else
offset = (short)((p->hs[0]<<8)|
(p->hs[1]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) %
off;
break;
}
} else
offset = (short)((p->hs[1]<<8)|
(p->hs[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
default:
break;
}
switch (in_type) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
#ifndef COMPILE_ONLY
file_mdump(m);
#endif
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (OFFSET_OOB(nbytes, offset, 1))
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (OFFSET_OOB(nbytes, offset, 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (OFFSET_OOB(nbytes, offset, 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (OFFSET_OOB(nbytes, offset, 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (OFFSET_OOB(nbytes, offset, m->vallen))
return 0;
break;
case FILE_REGEX:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
break;
case FILE_INDIRECT:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, F(m->desc, "%u"), offset) == -1)
return -1;
if (file_printf(ms, "%s", rbuf) == -1)
return -1;
free(rbuf);
}
return rv;
case FILE_USE:
if (OFFSET_OOB(nbytes, offset, 0))
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
case FILE_CLEAR:
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
return 1;
}
| 9,890 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
{
long v;
int u;
/* We can reliably get at most 31 bits since ISO/IEC 9899 only
guarantees that a long can represent values up to 2^31-1. */
assert(n >= 0 && n < 32);
/* Get the number of bits requested from the specified bit stream. */
v = 0;
while (--n >= 0) {
if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
return -1;
}
v = (v << 1) | u;
}
return v;
}
Commit Message: Changed the JPC bitstream code to more gracefully handle a request
for a larger sized integer than what can be handled (i.e., return
with an error instead of failing an assert).
CWE ID: | long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
{
long v;
int u;
/* We can reliably get at most 31 bits since ISO/IEC 9899 only
guarantees that a long can represent values up to 2^31-1. */
//assert(n >= 0 && n < 32);
if (n < 0 || n >= 32) {
return -1;
}
/* Get the number of bits requested from the specified bit stream. */
v = 0;
while (--n >= 0) {
if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
return -1;
}
v = (v << 1) | u;
}
return v;
}
| 7,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void Sp_replace_regexp(js_State *J)
{
js_Regexp *re;
const char *source, *s, *r;
js_Buffer *sb = NULL;
int n, x;
Resub m;
source = checkstring(J, 0);
re = js_toregexp(J, 1);
if (js_regexec(re->prog, source, &m, 0)) {
js_copy(J, 0);
return;
}
re->last = 0;
loop:
s = m.sub[0].sp;
n = m.sub[0].ep - m.sub[0].sp;
if (js_iscallable(J, 2)) {
js_copy(J, 2);
js_pushundefined(J);
for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */
js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp);
js_pushnumber(J, s - source); /* arg x+2: offset within search string */
js_copy(J, 0); /* arg x+3: search string */
js_call(J, 2 + x);
r = js_tostring(J, -1);
js_putm(J, &sb, source, s);
js_puts(J, &sb, r);
js_pop(J, 1);
} else {
r = js_tostring(J, 2);
js_putm(J, &sb, source, s);
while (*r) {
if (*r == '$') {
switch (*(++r)) {
case 0: --r; /* end of string; back up */
/* fallthrough */
case '$': js_putc(J, &sb, '$'); break;
case '`': js_putm(J, &sb, source, s); break;
case '\'': js_puts(J, &sb, s + n); break;
case '&':
js_putm(J, &sb, s, s + n);
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
x = *r - '0';
if (r[1] >= '0' && r[1] <= '9')
x = x * 10 + *(++r) - '0';
if (x > 0 && x < m.nsub) {
js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep);
} else {
js_putc(J, &sb, '$');
if (x > 10) {
js_putc(J, &sb, '0' + x / 10);
js_putc(J, &sb, '0' + x % 10);
} else {
js_putc(J, &sb, '0' + x);
}
}
break;
default:
js_putc(J, &sb, '$');
js_putc(J, &sb, *r);
break;
}
++r;
} else {
js_putc(J, &sb, *r++);
}
}
}
if (re->flags & JS_REGEXP_G) {
source = m.sub[0].ep;
if (n == 0) {
if (*source)
js_putc(J, &sb, *source++);
else
goto end;
}
if (!js_regexec(re->prog, source, &m, REG_NOTBOL))
goto loop;
}
end:
js_puts(J, &sb, s + n);
js_putc(J, &sb, 0);
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
js_pushstring(J, sb ? sb->s : "");
js_endtry(J);
js_free(J, sb);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400 | static void Sp_replace_regexp(js_State *J)
{
js_Regexp *re;
const char *source, *s, *r;
js_Buffer *sb = NULL;
int n, x;
Resub m;
source = checkstring(J, 0);
re = js_toregexp(J, 1);
if (js_doregexec(J, re->prog, source, &m, 0)) {
js_copy(J, 0);
return;
}
re->last = 0;
loop:
s = m.sub[0].sp;
n = m.sub[0].ep - m.sub[0].sp;
if (js_iscallable(J, 2)) {
js_copy(J, 2);
js_pushundefined(J);
for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */
js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp);
js_pushnumber(J, s - source); /* arg x+2: offset within search string */
js_copy(J, 0); /* arg x+3: search string */
js_call(J, 2 + x);
r = js_tostring(J, -1);
js_putm(J, &sb, source, s);
js_puts(J, &sb, r);
js_pop(J, 1);
} else {
r = js_tostring(J, 2);
js_putm(J, &sb, source, s);
while (*r) {
if (*r == '$') {
switch (*(++r)) {
case 0: --r; /* end of string; back up */
/* fallthrough */
case '$': js_putc(J, &sb, '$'); break;
case '`': js_putm(J, &sb, source, s); break;
case '\'': js_puts(J, &sb, s + n); break;
case '&':
js_putm(J, &sb, s, s + n);
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
x = *r - '0';
if (r[1] >= '0' && r[1] <= '9')
x = x * 10 + *(++r) - '0';
if (x > 0 && x < m.nsub) {
js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep);
} else {
js_putc(J, &sb, '$');
if (x > 10) {
js_putc(J, &sb, '0' + x / 10);
js_putc(J, &sb, '0' + x % 10);
} else {
js_putc(J, &sb, '0' + x);
}
}
break;
default:
js_putc(J, &sb, '$');
js_putc(J, &sb, *r);
break;
}
++r;
} else {
js_putc(J, &sb, *r++);
}
}
}
if (re->flags & JS_REGEXP_G) {
source = m.sub[0].ep;
if (n == 0) {
if (*source)
js_putc(J, &sb, *source++);
else
goto end;
}
if (!js_doregexec(J, re->prog, source, &m, REG_NOTBOL))
goto loop;
}
end:
js_puts(J, &sb, s + n);
js_putc(J, &sb, 0);
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
js_pushstring(J, sb ? sb->s : "");
js_endtry(J);
js_free(J, sb);
}
| 5,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: xmlParseComment(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int size = XML_PARSER_BUFFER_SIZE;
int len = 0;
xmlParserInputState state;
const xmlChar *in;
int nbchar = 0, ccol;
int inputid;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
inputid = ctxt->input->id;
SKIP(4);
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
in = ctxt->input->cur;
do {
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
}
get_more:
ccol = ctxt->input->col;
while (((*in > '-') && (*in <= 0x7F)) ||
((*in >= 0x20) && (*in < '-')) ||
(*in == 0x09)) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
nbchar = in - ctxt->input->cur;
/*
* save current set of data
*/
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->comment != NULL)) {
if (buf == NULL) {
if ((*in == '-') && (in[1] == '-'))
size = nbchar + 1;
else
size = XML_PARSER_BUFFER_SIZE + nbchar;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
len = 0;
} else if (len + nbchar + 1 >= size) {
xmlChar *new_buf;
size += len + nbchar + XML_PARSER_BUFFER_SIZE;
new_buf = (xmlChar *) xmlRealloc(buf,
size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
buf = new_buf;
}
memcpy(&buf[len], ctxt->input->cur, nbchar);
len += nbchar;
buf[len] = 0;
}
}
ctxt->input->cur = in;
if (*in == 0xA) {
in++;
ctxt->input->line++; ctxt->input->col = 1;
}
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
SHRINK;
GROW;
in = ctxt->input->cur;
if (*in == '-') {
if (in[1] == '-') {
if (in[2] == '>') {
if (ctxt->input->id != inputid) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"comment doesn't start and stop in the same entity\n");
}
SKIP(3);
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX)) {
if (buf != NULL)
ctxt->sax->comment(ctxt->userData, buf);
else
ctxt->sax->comment(ctxt->userData, BAD_CAST "");
}
if (buf != NULL)
xmlFree(buf);
ctxt->instate = state;
return;
}
if (buf != NULL)
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n",
buf);
else
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n", NULL);
in++;
ctxt->input->col++;
}
in++;
ctxt->input->col++;
goto get_more;
}
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
xmlParseCommentComplex(ctxt, buf, len, size);
ctxt->instate = state;
return;
}
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 | xmlParseComment(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int size = XML_PARSER_BUFFER_SIZE;
int len = 0;
xmlParserInputState state;
const xmlChar *in;
int nbchar = 0, ccol;
int inputid;
/*
* Check that there is a comment right here.
*/
if ((RAW != '<') || (NXT(1) != '!') ||
(NXT(2) != '-') || (NXT(3) != '-')) return;
state = ctxt->instate;
ctxt->instate = XML_PARSER_COMMENT;
inputid = ctxt->input->id;
SKIP(4);
SHRINK;
GROW;
/*
* Accelerated common case where input don't need to be
* modified before passing it to the handler.
*/
in = ctxt->input->cur;
do {
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
}
get_more:
ccol = ctxt->input->col;
while (((*in > '-') && (*in <= 0x7F)) ||
((*in >= 0x20) && (*in < '-')) ||
(*in == 0x09)) {
in++;
ccol++;
}
ctxt->input->col = ccol;
if (*in == 0xA) {
do {
ctxt->input->line++; ctxt->input->col = 1;
in++;
} while (*in == 0xA);
goto get_more;
}
nbchar = in - ctxt->input->cur;
/*
* save current set of data
*/
if (nbchar > 0) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->comment != NULL)) {
if (buf == NULL) {
if ((*in == '-') && (in[1] == '-'))
size = nbchar + 1;
else
size = XML_PARSER_BUFFER_SIZE + nbchar;
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
len = 0;
} else if (len + nbchar + 1 >= size) {
xmlChar *new_buf;
size += len + nbchar + XML_PARSER_BUFFER_SIZE;
new_buf = (xmlChar *) xmlRealloc(buf,
size * sizeof(xmlChar));
if (new_buf == NULL) {
xmlFree (buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
buf = new_buf;
}
memcpy(&buf[len], ctxt->input->cur, nbchar);
len += nbchar;
buf[len] = 0;
}
}
ctxt->input->cur = in;
if (*in == 0xA) {
in++;
ctxt->input->line++; ctxt->input->col = 1;
}
if (*in == 0xD) {
in++;
if (*in == 0xA) {
ctxt->input->cur = in;
in++;
ctxt->input->line++; ctxt->input->col = 1;
continue; /* while */
}
in--;
}
SHRINK;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
in = ctxt->input->cur;
if (*in == '-') {
if (in[1] == '-') {
if (in[2] == '>') {
if (ctxt->input->id != inputid) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"comment doesn't start and stop in the same entity\n");
}
SKIP(3);
if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
(!ctxt->disableSAX)) {
if (buf != NULL)
ctxt->sax->comment(ctxt->userData, buf);
else
ctxt->sax->comment(ctxt->userData, BAD_CAST "");
}
if (buf != NULL)
xmlFree(buf);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
if (buf != NULL)
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n<!--%.50s\n",
buf);
else
xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
"Comment not terminated \n", NULL);
in++;
ctxt->input->col++;
}
in++;
ctxt->input->col++;
goto get_more;
}
} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
xmlParseCommentComplex(ctxt, buf, len, size);
ctxt->instate = state;
return;
}
| 27,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
(void) fputc(c,file);
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199
CWE ID: CWE-20 | static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
if (fputc(c,file) != c)
break;
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 18,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. | Code: static void perf_log_throttle(struct perf_event *event, int enable)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
struct {
struct perf_event_header header;
u64 time;
u64 id;
u64 stream_id;
} throttle_event = {
.header = {
.type = PERF_RECORD_THROTTLE,
.misc = 0,
.size = sizeof(throttle_event),
},
.time = perf_clock(),
.id = primary_event_id(event),
.stream_id = event->id,
};
if (enable)
throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
perf_event_header__init_id(&throttle_event.header, &sample, event);
ret = perf_output_begin(&handle, event,
throttle_event.header.size, 1, 0);
if (ret)
return;
perf_output_put(&handle, throttle_event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: CWE-399 | static void perf_log_throttle(struct perf_event *event, int enable)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
struct {
struct perf_event_header header;
u64 time;
u64 id;
u64 stream_id;
} throttle_event = {
.header = {
.type = PERF_RECORD_THROTTLE,
.misc = 0,
.size = sizeof(throttle_event),
},
.time = perf_clock(),
.id = primary_event_id(event),
.stream_id = event->id,
};
if (enable)
throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
perf_event_header__init_id(&throttle_event.header, &sample, event);
ret = perf_output_begin(&handle, event,
throttle_event.header.size, 0);
if (ret)
return;
perf_output_put(&handle, throttle_event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
| 5,461 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
| 2,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
CWE ID: CWE-125 | atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
if (char_cnt == 0)
return (0);
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
| 22,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-119 | check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
| 26,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | 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;
}
| 26,846 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: IntRect PopupContainer::layoutAndCalculateWidgetRect(int targetControlHeight, const IntPoint& popupInitialCoordinate)
{
m_listBox->setMaxHeight(kMaxHeight);
m_listBox->setMaxWidth(std::numeric_limits<int>::max());
int rtlOffset = layoutAndGetRTLOffset();
bool isRTL = this->isRTL();
int rightOffset = isRTL ? rtlOffset : 0;
IntSize targetSize(m_listBox->width() + kBorderSize * 2,
m_listBox->height() + kBorderSize * 2);
IntRect widgetRect;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
FloatRect screen = screenAvailableRect(m_frameView.get());
widgetRect = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + rightOffset, popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
FloatRect windowRect = chromeClient->windowRect();
if (windowRect.x() >= screen.x() && windowRect.maxX() <= screen.maxX() && (widgetRect.x() < screen.x() || widgetRect.maxX() > screen.maxX())) {
IntRect inverseWidgetRect = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + (isRTL ? 0 : rtlOffset), popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
IntRect enclosingScreen = enclosingIntRect(screen);
unsigned originalCutoff = max(enclosingScreen.x() - widgetRect.x(), 0) + max(widgetRect.maxX() - enclosingScreen.maxX(), 0);
unsigned inverseCutoff = max(enclosingScreen.x() - inverseWidgetRect.x(), 0) + max(inverseWidgetRect.maxX() - enclosingScreen.maxX(), 0);
if (inverseCutoff < originalCutoff)
widgetRect = inverseWidgetRect;
if (widgetRect.x() < screen.x()) {
unsigned widgetRight = widgetRect.maxX();
widgetRect.setWidth(widgetRect.maxX() - screen.x());
widgetRect.setX(widgetRight - widgetRect.width());
listBox()->setMaxWidthAndLayout(max(widgetRect.width() - kBorderSize * 2, 0));
} else if (widgetRect.maxX() > screen.maxX()) {
widgetRect.setWidth(screen.maxX() - widgetRect.x());
listBox()->setMaxWidthAndLayout(max(widgetRect.width() - kBorderSize * 2, 0));
}
}
if (widgetRect.maxY() > static_cast<int>(screen.maxY())) {
if (widgetRect.y() - widgetRect.height() - targetControlHeight > 0) {
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
} else {
int spaceAbove = widgetRect.y() - targetControlHeight;
int spaceBelow = screen.maxY() - widgetRect.y();
if (spaceAbove > spaceBelow)
m_listBox->setMaxHeight(spaceAbove);
else
m_listBox->setMaxHeight(spaceBelow);
layoutAndGetRTLOffset();
IntRect frameInScreen = chromeClient->rootViewToScreen(frameRect());
widgetRect.setY(frameInScreen.y());
widgetRect.setHeight(frameInScreen.height());
if (spaceAbove > spaceBelow)
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
}
}
}
return widgetRect;
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | IntRect PopupContainer::layoutAndCalculateWidgetRect(int targetControlHeight, const IntPoint& popupInitialCoordinate)
{
m_listBox->setMaxHeight(kMaxHeight);
m_listBox->setMaxWidth(std::numeric_limits<int>::max());
int rtlOffset = layoutAndGetRTLOffset();
bool isRTL = this->isRTL();
int rightOffset = isRTL ? rtlOffset : 0;
IntSize targetSize(m_listBox->width() + kBorderSize * 2,
m_listBox->height() + kBorderSize * 2);
IntRect widgetRectInScreen;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
FloatRect screen = screenAvailableRect(m_frameView.get());
widgetRectInScreen = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + rightOffset, popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
FloatRect windowRect = chromeClient->windowRect();
if (windowRect.x() >= screen.x() && windowRect.maxX() <= screen.maxX() && (widgetRectInScreen.x() < screen.x() || widgetRectInScreen.maxX() > screen.maxX())) {
IntRect inverseWidgetRectInScreen = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + (isRTL ? 0 : rtlOffset), popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
IntRect enclosingScreen = enclosingIntRect(screen);
unsigned originalCutoff = max(enclosingScreen.x() - widgetRectInScreen.x(), 0) + max(widgetRectInScreen.maxX() - enclosingScreen.maxX(), 0);
unsigned inverseCutoff = max(enclosingScreen.x() - inverseWidgetRectInScreen.x(), 0) + max(inverseWidgetRectInScreen.maxX() - enclosingScreen.maxX(), 0);
if (inverseCutoff < originalCutoff)
widgetRectInScreen = inverseWidgetRectInScreen;
if (widgetRectInScreen.x() < screen.x()) {
unsigned widgetRight = widgetRectInScreen.maxX();
widgetRectInScreen.setWidth(widgetRectInScreen.maxX() - screen.x());
widgetRectInScreen.setX(widgetRight - widgetRectInScreen.width());
listBox()->setMaxWidthAndLayout(max(widgetRectInScreen.width() - kBorderSize * 2, 0));
} else if (widgetRectInScreen.maxX() > screen.maxX()) {
widgetRectInScreen.setWidth(screen.maxX() - widgetRectInScreen.x());
listBox()->setMaxWidthAndLayout(max(widgetRectInScreen.width() - kBorderSize * 2, 0));
}
}
if (widgetRectInScreen.maxY() > static_cast<int>(screen.maxY())) {
if (widgetRectInScreen.y() - widgetRectInScreen.height() - targetControlHeight > 0) {
widgetRectInScreen.move(0, -(widgetRectInScreen.height() + targetControlHeight));
} else {
int spaceAbove = widgetRectInScreen.y() - targetControlHeight;
int spaceBelow = screen.maxY() - widgetRectInScreen.y();
if (spaceAbove > spaceBelow)
m_listBox->setMaxHeight(spaceAbove);
else
m_listBox->setMaxHeight(spaceBelow);
layoutAndGetRTLOffset();
IntRect frameInScreen = chromeClient->rootViewToScreen(frameRect());
widgetRectInScreen.setY(frameInScreen.y());
widgetRectInScreen.setHeight(frameInScreen.height());
if (spaceAbove > spaceBelow)
widgetRectInScreen.move(0, -(widgetRectInScreen.height() + targetControlHeight));
}
}
}
return widgetRectInScreen;
}
| 25,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. | Code: int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
int err = 0;
size_t target, copied = 0;
long timeo;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
msg->msg_namelen = 0;
BT_DBG("sk %p size %zu", sk, size);
lock_sock(sk);
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
struct sk_buff *skb;
int chunk;
skb = skb_dequeue(&sk->sk_receive_queue);
if (!skb) {
if (copied >= target)
break;
err = sock_error(sk);
if (err)
break;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
err = -EAGAIN;
if (!timeo)
break;
timeo = bt_sock_data_wait(sk, timeo);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (!copied)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
int skb_len = skb_headlen(skb);
if (chunk <= skb_len) {
__skb_pull(skb, chunk);
} else {
struct sk_buff *frag;
__skb_pull(skb, skb_len);
chunk -= skb_len;
skb_walk_frags(skb, frag) {
if (chunk <= frag->len) {
/* Pulling partial data */
skb->len -= chunk;
skb->data_len -= chunk;
__skb_pull(frag, chunk);
break;
} else if (frag->len) {
/* Pulling all frag data */
chunk -= frag->len;
skb->len -= frag->len;
skb->data_len -= frag->len;
__skb_pull(frag, frag->len);
}
}
}
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
out:
release_sock(sk);
return copied ? : err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20 | int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
int err = 0;
size_t target, copied = 0;
long timeo;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
BT_DBG("sk %p size %zu", sk, size);
lock_sock(sk);
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
struct sk_buff *skb;
int chunk;
skb = skb_dequeue(&sk->sk_receive_queue);
if (!skb) {
if (copied >= target)
break;
err = sock_error(sk);
if (err)
break;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
err = -EAGAIN;
if (!timeo)
break;
timeo = bt_sock_data_wait(sk, timeo);
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (!copied)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
int skb_len = skb_headlen(skb);
if (chunk <= skb_len) {
__skb_pull(skb, chunk);
} else {
struct sk_buff *frag;
__skb_pull(skb, skb_len);
chunk -= skb_len;
skb_walk_frags(skb, frag) {
if (chunk <= frag->len) {
/* Pulling partial data */
skb->len -= chunk;
skb->data_len -= chunk;
__skb_pull(frag, chunk);
break;
} else if (frag->len) {
/* Pulling all frag data */
chunk -= frag->len;
skb->len -= frag->len;
skb->data_len -= frag->len;
__skb_pull(frag, frag->len);
}
}
}
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
out:
release_sock(sk);
return copied ? : err;
}
| 11,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + data_blob_len;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
Commit Message:
CWE ID: CWE-119 | static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + blob1.length;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
| 6,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. | Code: std::string SanitizeFrontendPath(const std::string& path) {
for (size_t i = 0; i < path.length(); i++) {
if (path[i] != '/' && path[i] != '-' && path[i] != '_'
&& path[i] != '.' && path[i] != '@'
&& !(path[i] >= '0' && path[i] <= '9')
&& !(path[i] >= 'a' && path[i] <= 'z')
&& !(path[i] >= 'A' && path[i] <= 'Z')) {
return std::string();
}
}
return path;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | std::string SanitizeFrontendPath(const std::string& path) {
| 25,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. | Code: void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <fs@opera.com>
Commit-Queue: Chris Harrelson <chrishtr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200 | void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
origin_tainted_by_content_ = false;
}
| 12,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: BrowserContextDestroyer::BrowserContextDestroyer(
BrowserContext* context,
const std::set<content::RenderProcessHost*>& hosts)
: context_(context),
pending_hosts_(0) {
for (std::set<content::RenderProcessHost*>::iterator it = hosts.begin();
it != hosts.end(); ++it) {
(*it)->AddObserver(this);
++pending_hosts_;
}
}
Commit Message:
CWE ID: CWE-20 | BrowserContextDestroyer::BrowserContextDestroyer(
std::unique_ptr<BrowserContext> context,
const std::set<content::RenderProcessHost*>& hosts,
uint32_t otr_contexts_pending_deletion)
: context_(std::move(context)),
otr_contexts_pending_deletion_(otr_contexts_pending_deletion),
finish_destroy_scheduled_(false) {
DCHECK(hosts.size() > 0 ||
(!context->IsOffTheRecord() &&
(otr_contexts_pending_deletion > 0 ||
context->HasOffTheRecordContext())));
g_contexts_pending_deletion.Get().push_back(this);
for (auto* host : hosts) {
ObserveHost(host);
}
}
| 6,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: finish_process_as_req(struct as_req_state *state, krb5_error_code errcode)
{
krb5_key_data *server_key;
krb5_keyblock *as_encrypting_key = NULL;
krb5_data *response = NULL;
const char *emsg = 0;
int did_log = 0;
loop_respond_fn oldrespond;
void *oldarg;
kdc_realm_t *kdc_active_realm = state->active_realm;
krb5_audit_state *au_state = state->au_state;
assert(state);
oldrespond = state->respond;
oldarg = state->arg;
if (errcode)
goto egress;
au_state->stage = ENCR_REP;
if ((errcode = validate_forwardable(state->request, *state->client,
*state->server, state->kdc_time,
&state->status))) {
errcode += ERROR_TABLE_BASE_krb5;
goto egress;
}
errcode = check_indicators(kdc_context, state->server,
state->auth_indicators);
if (errcode) {
state->status = "HIGHER_AUTHENTICATION_REQUIRED";
goto egress;
}
state->ticket_reply.enc_part2 = &state->enc_tkt_reply;
/*
* Find the server key
*/
if ((errcode = krb5_dbe_find_enctype(kdc_context, state->server,
-1, /* ignore keytype */
-1, /* Ignore salttype */
0, /* Get highest kvno */
&server_key))) {
state->status = "FINDING_SERVER_KEY";
goto egress;
}
/*
* Convert server->key into a real key
* (it may be encrypted in the database)
*
* server_keyblock is later used to generate auth data signatures
*/
if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
server_key,
&state->server_keyblock,
NULL))) {
state->status = "DECRYPT_SERVER_KEY";
goto egress;
}
/* Start assembling the response */
state->reply.msg_type = KRB5_AS_REP;
state->reply.client = state->enc_tkt_reply.client; /* post canonization */
state->reply.ticket = &state->ticket_reply;
state->reply_encpart.session = &state->session_key;
if ((errcode = fetch_last_req_info(state->client,
&state->reply_encpart.last_req))) {
state->status = "FETCH_LAST_REQ";
goto egress;
}
state->reply_encpart.nonce = state->request->nonce;
state->reply_encpart.key_exp = get_key_exp(state->client);
state->reply_encpart.flags = state->enc_tkt_reply.flags;
state->reply_encpart.server = state->ticket_reply.server;
/* copy the time fields EXCEPT for authtime; it's location
* is used for ktime
*/
state->reply_encpart.times = state->enc_tkt_reply.times;
state->reply_encpart.times.authtime = state->authtime = state->kdc_time;
state->reply_encpart.caddrs = state->enc_tkt_reply.caddrs;
state->reply_encpart.enc_padata = NULL;
/* Fetch the padata info to be returned (do this before
* authdata to handle possible replacement of reply key
*/
errcode = return_padata(kdc_context, &state->rock, state->req_pkt,
state->request, &state->reply,
&state->client_keyblock, &state->pa_context);
if (errcode) {
state->status = "KDC_RETURN_PADATA";
goto egress;
}
/* If we didn't find a client long-term key and no preauth mechanism
* replaced the reply key, error out now. */
if (state->client_keyblock.enctype == ENCTYPE_NULL) {
state->status = "CANT_FIND_CLIENT_KEY";
errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
goto egress;
}
errcode = handle_authdata(kdc_context,
state->c_flags,
state->client,
state->server,
NULL,
state->local_tgt,
&state->client_keyblock,
&state->server_keyblock,
NULL,
state->req_pkt,
state->request,
NULL, /* for_user_princ */
NULL, /* enc_tkt_request */
state->auth_indicators,
&state->enc_tkt_reply);
if (errcode) {
krb5_klog_syslog(LOG_INFO, _("AS_REQ : handle_authdata (%d)"),
errcode);
state->status = "HANDLE_AUTHDATA";
goto egress;
}
errcode = krb5_encrypt_tkt_part(kdc_context, &state->server_keyblock,
&state->ticket_reply);
if (errcode) {
state->status = "ENCRYPT_TICKET";
goto egress;
}
errcode = kau_make_tkt_id(kdc_context, &state->ticket_reply,
&au_state->tkt_out_id);
if (errcode) {
state->status = "GENERATE_TICKET_ID";
goto egress;
}
state->ticket_reply.enc_part.kvno = server_key->key_data_kvno;
errcode = kdc_fast_response_handle_padata(state->rstate,
state->request,
&state->reply,
state->client_keyblock.enctype);
if (errcode) {
state->status = "MAKE_FAST_RESPONSE";
goto egress;
}
/* now encode/encrypt the response */
state->reply.enc_part.enctype = state->client_keyblock.enctype;
errcode = kdc_fast_handle_reply_key(state->rstate, &state->client_keyblock,
&as_encrypting_key);
if (errcode) {
state->status = "MAKE_FAST_REPLY_KEY";
goto egress;
}
errcode = return_enc_padata(kdc_context, state->req_pkt, state->request,
as_encrypting_key, state->server,
&state->reply_encpart, FALSE);
if (errcode) {
state->status = "KDC_RETURN_ENC_PADATA";
goto egress;
}
if (kdc_fast_hide_client(state->rstate))
state->reply.client = (krb5_principal)krb5_anonymous_principal();
errcode = krb5_encode_kdc_rep(kdc_context, KRB5_AS_REP,
&state->reply_encpart, 0,
as_encrypting_key,
&state->reply, &response);
if (state->client_key != NULL)
state->reply.enc_part.kvno = state->client_key->key_data_kvno;
if (errcode) {
state->status = "ENCODE_KDC_REP";
goto egress;
}
/* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
can use them in raw form if needed. But, we don't... */
memset(state->reply.enc_part.ciphertext.data, 0,
state->reply.enc_part.ciphertext.length);
free(state->reply.enc_part.ciphertext.data);
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client, state->cname,
state->server, state->sname, state->authtime, 0, 0, 0);
did_log = 1;
egress:
if (errcode != 0)
assert (state->status != 0);
au_state->status = state->status;
au_state->reply = &state->reply;
kau_as_req(kdc_context,
(errcode || state->preauth_err) ? FALSE : TRUE, au_state);
kau_free_kdc_req(au_state);
free_padata_context(kdc_context, state->pa_context);
if (as_encrypting_key)
krb5_free_keyblock(kdc_context, as_encrypting_key);
if (errcode)
emsg = krb5_get_error_message(kdc_context, errcode);
if (state->status) {
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client,
state->cname, state->server, state->sname, state->authtime,
state->status, errcode, emsg);
did_log = 1;
}
if (errcode) {
if (state->status == 0) {
state->status = emsg;
}
if (errcode != KRB5KDC_ERR_DISCARD) {
errcode -= ERROR_TABLE_BASE_krb5;
if (errcode < 0 || errcode > KRB_ERR_MAX)
errcode = KRB_ERR_GENERIC;
errcode = prepare_error_as(state->rstate, state->request,
state->local_tgt, errcode,
state->e_data, state->typed_e_data,
((state->client != NULL) ?
state->client->princ : NULL),
&response, state->status);
state->status = 0;
}
}
if (emsg)
krb5_free_error_message(kdc_context, emsg);
if (state->enc_tkt_reply.authorization_data != NULL)
krb5_free_authdata(kdc_context,
state->enc_tkt_reply.authorization_data);
if (state->server_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->server_keyblock);
if (state->client_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->client_keyblock);
if (state->reply.padata != NULL)
krb5_free_pa_data(kdc_context, state->reply.padata);
if (state->reply_encpart.enc_padata)
krb5_free_pa_data(kdc_context, state->reply_encpart.enc_padata);
if (state->cname != NULL)
free(state->cname);
if (state->sname != NULL)
free(state->sname);
krb5_db_free_principal(kdc_context, state->client);
krb5_db_free_principal(kdc_context, state->server);
krb5_db_free_principal(kdc_context, state->local_tgt_storage);
if (state->session_key.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->session_key);
if (state->ticket_reply.enc_part.ciphertext.data != NULL) {
memset(state->ticket_reply.enc_part.ciphertext.data , 0,
state->ticket_reply.enc_part.ciphertext.length);
free(state->ticket_reply.enc_part.ciphertext.data);
}
krb5_free_pa_data(kdc_context, state->e_data);
krb5_free_data(kdc_context, state->inner_body);
kdc_free_rstate(state->rstate);
krb5_free_kdc_req(kdc_context, state->request);
k5_free_data_ptr_list(state->auth_indicators);
assert(did_log != 0);
free(state);
(*oldrespond)(oldarg, errcode, response);
}
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 | finish_process_as_req(struct as_req_state *state, krb5_error_code errcode)
{
krb5_key_data *server_key;
krb5_keyblock *as_encrypting_key = NULL;
krb5_data *response = NULL;
const char *emsg = 0;
int did_log = 0;
loop_respond_fn oldrespond;
void *oldarg;
kdc_realm_t *kdc_active_realm = state->active_realm;
krb5_audit_state *au_state = state->au_state;
assert(state);
oldrespond = state->respond;
oldarg = state->arg;
if (errcode)
goto egress;
au_state->stage = ENCR_REP;
if ((errcode = validate_forwardable(state->request, *state->client,
*state->server, state->kdc_time,
&state->status))) {
errcode += ERROR_TABLE_BASE_krb5;
goto egress;
}
errcode = check_indicators(kdc_context, state->server,
state->auth_indicators);
if (errcode) {
state->status = "HIGHER_AUTHENTICATION_REQUIRED";
goto egress;
}
state->ticket_reply.enc_part2 = &state->enc_tkt_reply;
/*
* Find the server key
*/
if ((errcode = krb5_dbe_find_enctype(kdc_context, state->server,
-1, /* ignore keytype */
-1, /* Ignore salttype */
0, /* Get highest kvno */
&server_key))) {
state->status = "FINDING_SERVER_KEY";
goto egress;
}
/*
* Convert server->key into a real key
* (it may be encrypted in the database)
*
* server_keyblock is later used to generate auth data signatures
*/
if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
server_key,
&state->server_keyblock,
NULL))) {
state->status = "DECRYPT_SERVER_KEY";
goto egress;
}
/* Start assembling the response */
state->reply.msg_type = KRB5_AS_REP;
state->reply.client = state->enc_tkt_reply.client; /* post canonization */
state->reply.ticket = &state->ticket_reply;
state->reply_encpart.session = &state->session_key;
if ((errcode = fetch_last_req_info(state->client,
&state->reply_encpart.last_req))) {
state->status = "FETCH_LAST_REQ";
goto egress;
}
state->reply_encpart.nonce = state->request->nonce;
state->reply_encpart.key_exp = get_key_exp(state->client);
state->reply_encpart.flags = state->enc_tkt_reply.flags;
state->reply_encpart.server = state->ticket_reply.server;
/* copy the time fields EXCEPT for authtime; it's location
* is used for ktime
*/
state->reply_encpart.times = state->enc_tkt_reply.times;
state->reply_encpart.times.authtime = state->authtime = state->kdc_time;
state->reply_encpart.caddrs = state->enc_tkt_reply.caddrs;
state->reply_encpart.enc_padata = NULL;
/* Fetch the padata info to be returned (do this before
* authdata to handle possible replacement of reply key
*/
errcode = return_padata(kdc_context, &state->rock, state->req_pkt,
state->request, &state->reply,
&state->client_keyblock, &state->pa_context);
if (errcode) {
state->status = "KDC_RETURN_PADATA";
goto egress;
}
/* If we didn't find a client long-term key and no preauth mechanism
* replaced the reply key, error out now. */
if (state->client_keyblock.enctype == ENCTYPE_NULL) {
state->status = "CANT_FIND_CLIENT_KEY";
errcode = KRB5KDC_ERR_ETYPE_NOSUPP;
goto egress;
}
errcode = handle_authdata(kdc_context,
state->c_flags,
state->client,
state->server,
NULL,
state->local_tgt,
&state->client_keyblock,
&state->server_keyblock,
NULL,
state->req_pkt,
state->request,
NULL, /* for_user_princ */
NULL, /* enc_tkt_request */
state->auth_indicators,
&state->enc_tkt_reply);
if (errcode) {
krb5_klog_syslog(LOG_INFO, _("AS_REQ : handle_authdata (%d)"),
errcode);
state->status = "HANDLE_AUTHDATA";
goto egress;
}
errcode = krb5_encrypt_tkt_part(kdc_context, &state->server_keyblock,
&state->ticket_reply);
if (errcode) {
state->status = "ENCRYPT_TICKET";
goto egress;
}
errcode = kau_make_tkt_id(kdc_context, &state->ticket_reply,
&au_state->tkt_out_id);
if (errcode) {
state->status = "GENERATE_TICKET_ID";
goto egress;
}
state->ticket_reply.enc_part.kvno = server_key->key_data_kvno;
errcode = kdc_fast_response_handle_padata(state->rstate,
state->request,
&state->reply,
state->client_keyblock.enctype);
if (errcode) {
state->status = "MAKE_FAST_RESPONSE";
goto egress;
}
/* now encode/encrypt the response */
state->reply.enc_part.enctype = state->client_keyblock.enctype;
errcode = kdc_fast_handle_reply_key(state->rstate, &state->client_keyblock,
&as_encrypting_key);
if (errcode) {
state->status = "MAKE_FAST_REPLY_KEY";
goto egress;
}
errcode = return_enc_padata(kdc_context, state->req_pkt, state->request,
as_encrypting_key, state->server,
&state->reply_encpart, FALSE);
if (errcode) {
state->status = "KDC_RETURN_ENC_PADATA";
goto egress;
}
if (kdc_fast_hide_client(state->rstate))
state->reply.client = (krb5_principal)krb5_anonymous_principal();
errcode = krb5_encode_kdc_rep(kdc_context, KRB5_AS_REP,
&state->reply_encpart, 0,
as_encrypting_key,
&state->reply, &response);
if (state->client_key != NULL)
state->reply.enc_part.kvno = state->client_key->key_data_kvno;
if (errcode) {
state->status = "ENCODE_KDC_REP";
goto egress;
}
/* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
can use them in raw form if needed. But, we don't... */
memset(state->reply.enc_part.ciphertext.data, 0,
state->reply.enc_part.ciphertext.length);
free(state->reply.enc_part.ciphertext.data);
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client, state->cname,
state->server, state->sname, state->authtime, 0, 0, 0);
did_log = 1;
egress:
if (errcode != 0 && state->status == NULL)
state->status = "UNKNOWN_REASON";
au_state->status = state->status;
au_state->reply = &state->reply;
kau_as_req(kdc_context,
(errcode || state->preauth_err) ? FALSE : TRUE, au_state);
kau_free_kdc_req(au_state);
free_padata_context(kdc_context, state->pa_context);
if (as_encrypting_key)
krb5_free_keyblock(kdc_context, as_encrypting_key);
if (errcode)
emsg = krb5_get_error_message(kdc_context, errcode);
if (state->status) {
log_as_req(kdc_context, state->local_addr, state->remote_addr,
state->request, &state->reply, state->client,
state->cname, state->server, state->sname, state->authtime,
state->status, errcode, emsg);
did_log = 1;
}
if (errcode) {
if (state->status == 0) {
state->status = emsg;
}
if (errcode != KRB5KDC_ERR_DISCARD) {
errcode -= ERROR_TABLE_BASE_krb5;
if (errcode < 0 || errcode > KRB_ERR_MAX)
errcode = KRB_ERR_GENERIC;
errcode = prepare_error_as(state->rstate, state->request,
state->local_tgt, errcode,
state->e_data, state->typed_e_data,
((state->client != NULL) ?
state->client->princ : NULL),
&response, state->status);
state->status = 0;
}
}
if (emsg)
krb5_free_error_message(kdc_context, emsg);
if (state->enc_tkt_reply.authorization_data != NULL)
krb5_free_authdata(kdc_context,
state->enc_tkt_reply.authorization_data);
if (state->server_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->server_keyblock);
if (state->client_keyblock.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->client_keyblock);
if (state->reply.padata != NULL)
krb5_free_pa_data(kdc_context, state->reply.padata);
if (state->reply_encpart.enc_padata)
krb5_free_pa_data(kdc_context, state->reply_encpart.enc_padata);
if (state->cname != NULL)
free(state->cname);
if (state->sname != NULL)
free(state->sname);
krb5_db_free_principal(kdc_context, state->client);
krb5_db_free_principal(kdc_context, state->server);
krb5_db_free_principal(kdc_context, state->local_tgt_storage);
if (state->session_key.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &state->session_key);
if (state->ticket_reply.enc_part.ciphertext.data != NULL) {
memset(state->ticket_reply.enc_part.ciphertext.data , 0,
state->ticket_reply.enc_part.ciphertext.length);
free(state->ticket_reply.enc_part.ciphertext.data);
}
krb5_free_pa_data(kdc_context, state->e_data);
krb5_free_data(kdc_context, state->inner_body);
kdc_free_rstate(state->rstate);
krb5_free_kdc_req(kdc_context, state->request);
k5_free_data_ptr_list(state->auth_indicators);
assert(did_log != 0);
free(state);
(*oldrespond)(oldarg, errcode, response);
}
| 2,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. | Code: status_t Camera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("Client2[%d] (%p) Client: %s PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
String8(mClientPackageName).string(),
mClientPid);
result.append(" State: ");
#define CASE_APPEND_ENUM(x) case x: result.append(#x "\n"); break;
const Parameters& p = mParameters.unsafeAccess();
result.append(Parameters::getStateName(p.state));
result.append("\n Current parameters:\n");
result.appendFormat(" Preview size: %d x %d\n",
p.previewWidth, p.previewHeight);
result.appendFormat(" Preview FPS range: %d - %d\n",
p.previewFpsRange[0], p.previewFpsRange[1]);
result.appendFormat(" Preview HAL pixel format: 0x%x\n",
p.previewFormat);
result.appendFormat(" Preview transform: %x\n",
p.previewTransform);
result.appendFormat(" Picture size: %d x %d\n",
p.pictureWidth, p.pictureHeight);
result.appendFormat(" Jpeg thumbnail size: %d x %d\n",
p.jpegThumbSize[0], p.jpegThumbSize[1]);
result.appendFormat(" Jpeg quality: %d, thumbnail quality: %d\n",
p.jpegQuality, p.jpegThumbQuality);
result.appendFormat(" Jpeg rotation: %d\n", p.jpegRotation);
result.appendFormat(" GPS tags %s\n",
p.gpsEnabled ? "enabled" : "disabled");
if (p.gpsEnabled) {
result.appendFormat(" GPS lat x long x alt: %f x %f x %f\n",
p.gpsCoordinates[0], p.gpsCoordinates[1],
p.gpsCoordinates[2]);
result.appendFormat(" GPS timestamp: %lld\n",
p.gpsTimestamp);
result.appendFormat(" GPS processing method: %s\n",
p.gpsProcessingMethod.string());
}
result.append(" White balance mode: ");
switch (p.wbMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_INCANDESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_TWILIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_SHADE)
default: result.append("UNKNOWN\n");
}
result.append(" Effect mode: ");
switch (p.effectMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_MONO)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_NEGATIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SOLARIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SEPIA)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_POSTERIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_AQUA)
default: result.append("UNKNOWN\n");
}
result.append(" Antibanding mode: ");
switch (p.antibandingMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ)
default: result.append("UNKNOWN\n");
}
result.append(" Scene mode: ");
switch (p.sceneMode) {
case ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED:
result.append("AUTO\n"); break;
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_ACTION)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_LANDSCAPE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_THEATRE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BEACH)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SNOW)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SUNSET)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_FIREWORKS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SPORTS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PARTY)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BARCODE)
default: result.append("UNKNOWN\n");
}
result.append(" Flash mode: ");
switch (p.flashMode) {
CASE_APPEND_ENUM(Parameters::FLASH_MODE_OFF)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_ON)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_TORCH)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_RED_EYE)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus mode: ");
switch (p.focusMode) {
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_MACRO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_VIDEO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_PICTURE)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_EDOF)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INFINITY)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_FIXED)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus state: ");
switch (p.focusState) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_INACTIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED)
default: result.append("UNKNOWN\n");
}
result.append(" Focusing areas:\n");
for (size_t i = 0; i < p.focusingAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.focusingAreas[i].left,
p.focusingAreas[i].top,
p.focusingAreas[i].right,
p.focusingAreas[i].bottom,
p.focusingAreas[i].weight);
}
result.appendFormat(" Exposure compensation index: %d\n",
p.exposureCompensation);
result.appendFormat(" AE lock %s, AWB lock %s\n",
p.autoExposureLock ? "enabled" : "disabled",
p.autoWhiteBalanceLock ? "enabled" : "disabled" );
result.appendFormat(" Metering areas:\n");
for (size_t i = 0; i < p.meteringAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.meteringAreas[i].left,
p.meteringAreas[i].top,
p.meteringAreas[i].right,
p.meteringAreas[i].bottom,
p.meteringAreas[i].weight);
}
result.appendFormat(" Zoom index: %d\n", p.zoom);
result.appendFormat(" Video size: %d x %d\n", p.videoWidth,
p.videoHeight);
result.appendFormat(" Recording hint is %s\n",
p.recordingHint ? "set" : "not set");
result.appendFormat(" Video stabilization is %s\n",
p.videoStabilization ? "enabled" : "disabled");
result.appendFormat(" Selected still capture FPS range: %d - %d\n",
p.fastInfo.bestStillCaptureFpsRange[0],
p.fastInfo.bestStillCaptureFpsRange[1]);
result.append(" Current streams:\n");
result.appendFormat(" Preview stream ID: %d\n",
getPreviewStreamId());
result.appendFormat(" Capture stream ID: %d\n",
getCaptureStreamId());
result.appendFormat(" Recording stream ID: %d\n",
getRecordingStreamId());
result.append(" Quirks for this camera:\n");
bool haveQuirk = false;
if (p.quirks.triggerAfWithAuto) {
result.appendFormat(" triggerAfWithAuto\n");
haveQuirk = true;
}
if (p.quirks.useZslFormat) {
result.appendFormat(" useZslFormat\n");
haveQuirk = true;
}
if (p.quirks.meteringCropRegion) {
result.appendFormat(" meteringCropRegion\n");
haveQuirk = true;
}
if (p.quirks.partialResults) {
result.appendFormat(" usePartialResult\n");
haveQuirk = true;
}
if (!haveQuirk) {
result.appendFormat(" none\n");
}
write(fd, result.string(), result.size());
mStreamingProcessor->dump(fd, args);
mCaptureSequencer->dump(fd, args);
mFrameProcessor->dump(fd, args);
mZslProcessor->dump(fd, args);
return dumpDevice(fd, args);
#undef CASE_APPEND_ENUM
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264 | status_t Camera2Client::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t Camera2Client::dumpClient(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("Client2[%d] (%p) Client: %s PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
String8(mClientPackageName).string(),
mClientPid);
result.append(" State: ");
#define CASE_APPEND_ENUM(x) case x: result.append(#x "\n"); break;
const Parameters& p = mParameters.unsafeAccess();
result.append(Parameters::getStateName(p.state));
result.append("\n Current parameters:\n");
result.appendFormat(" Preview size: %d x %d\n",
p.previewWidth, p.previewHeight);
result.appendFormat(" Preview FPS range: %d - %d\n",
p.previewFpsRange[0], p.previewFpsRange[1]);
result.appendFormat(" Preview HAL pixel format: 0x%x\n",
p.previewFormat);
result.appendFormat(" Preview transform: %x\n",
p.previewTransform);
result.appendFormat(" Picture size: %d x %d\n",
p.pictureWidth, p.pictureHeight);
result.appendFormat(" Jpeg thumbnail size: %d x %d\n",
p.jpegThumbSize[0], p.jpegThumbSize[1]);
result.appendFormat(" Jpeg quality: %d, thumbnail quality: %d\n",
p.jpegQuality, p.jpegThumbQuality);
result.appendFormat(" Jpeg rotation: %d\n", p.jpegRotation);
result.appendFormat(" GPS tags %s\n",
p.gpsEnabled ? "enabled" : "disabled");
if (p.gpsEnabled) {
result.appendFormat(" GPS lat x long x alt: %f x %f x %f\n",
p.gpsCoordinates[0], p.gpsCoordinates[1],
p.gpsCoordinates[2]);
result.appendFormat(" GPS timestamp: %lld\n",
p.gpsTimestamp);
result.appendFormat(" GPS processing method: %s\n",
p.gpsProcessingMethod.string());
}
result.append(" White balance mode: ");
switch (p.wbMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_INCANDESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_TWILIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_SHADE)
default: result.append("UNKNOWN\n");
}
result.append(" Effect mode: ");
switch (p.effectMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_MONO)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_NEGATIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SOLARIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SEPIA)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_POSTERIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_AQUA)
default: result.append("UNKNOWN\n");
}
result.append(" Antibanding mode: ");
switch (p.antibandingMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ)
default: result.append("UNKNOWN\n");
}
result.append(" Scene mode: ");
switch (p.sceneMode) {
case ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED:
result.append("AUTO\n"); break;
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_ACTION)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_LANDSCAPE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_THEATRE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BEACH)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SNOW)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SUNSET)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_FIREWORKS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SPORTS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PARTY)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BARCODE)
default: result.append("UNKNOWN\n");
}
result.append(" Flash mode: ");
switch (p.flashMode) {
CASE_APPEND_ENUM(Parameters::FLASH_MODE_OFF)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_ON)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_TORCH)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_RED_EYE)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus mode: ");
switch (p.focusMode) {
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_MACRO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_VIDEO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_PICTURE)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_EDOF)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INFINITY)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_FIXED)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus state: ");
switch (p.focusState) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_INACTIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED)
default: result.append("UNKNOWN\n");
}
result.append(" Focusing areas:\n");
for (size_t i = 0; i < p.focusingAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.focusingAreas[i].left,
p.focusingAreas[i].top,
p.focusingAreas[i].right,
p.focusingAreas[i].bottom,
p.focusingAreas[i].weight);
}
result.appendFormat(" Exposure compensation index: %d\n",
p.exposureCompensation);
result.appendFormat(" AE lock %s, AWB lock %s\n",
p.autoExposureLock ? "enabled" : "disabled",
p.autoWhiteBalanceLock ? "enabled" : "disabled" );
result.appendFormat(" Metering areas:\n");
for (size_t i = 0; i < p.meteringAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.meteringAreas[i].left,
p.meteringAreas[i].top,
p.meteringAreas[i].right,
p.meteringAreas[i].bottom,
p.meteringAreas[i].weight);
}
result.appendFormat(" Zoom index: %d\n", p.zoom);
result.appendFormat(" Video size: %d x %d\n", p.videoWidth,
p.videoHeight);
result.appendFormat(" Recording hint is %s\n",
p.recordingHint ? "set" : "not set");
result.appendFormat(" Video stabilization is %s\n",
p.videoStabilization ? "enabled" : "disabled");
result.appendFormat(" Selected still capture FPS range: %d - %d\n",
p.fastInfo.bestStillCaptureFpsRange[0],
p.fastInfo.bestStillCaptureFpsRange[1]);
result.append(" Current streams:\n");
result.appendFormat(" Preview stream ID: %d\n",
getPreviewStreamId());
result.appendFormat(" Capture stream ID: %d\n",
getCaptureStreamId());
result.appendFormat(" Recording stream ID: %d\n",
getRecordingStreamId());
result.append(" Quirks for this camera:\n");
bool haveQuirk = false;
if (p.quirks.triggerAfWithAuto) {
result.appendFormat(" triggerAfWithAuto\n");
haveQuirk = true;
}
if (p.quirks.useZslFormat) {
result.appendFormat(" useZslFormat\n");
haveQuirk = true;
}
if (p.quirks.meteringCropRegion) {
result.appendFormat(" meteringCropRegion\n");
haveQuirk = true;
}
if (p.quirks.partialResults) {
result.appendFormat(" usePartialResult\n");
haveQuirk = true;
}
if (!haveQuirk) {
result.appendFormat(" none\n");
}
write(fd, result.string(), result.size());
mStreamingProcessor->dump(fd, args);
mCaptureSequencer->dump(fd, args);
mFrameProcessor->dump(fd, args);
mZslProcessor->dump(fd, args);
return dumpDevice(fd, args);
#undef CASE_APPEND_ENUM
}
| 14,130 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool LauncherView::IsShowingMenu() const {
#if !defined(OS_MACOSX)
return (overflow_menu_runner_.get() &&
overflow_menu_runner_->IsRunning()) ||
(launcher_menu_runner_.get() &&
launcher_menu_runner_->IsRunning());
#endif
return false;
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool LauncherView::IsShowingMenu() const {
#if !defined(OS_MACOSX)
return (launcher_menu_runner_.get() &&
launcher_menu_runner_->IsRunning());
#endif
return false;
}
| 24,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp)
{
static gstrings_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gstrings_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth("kadm5_get_strings", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings,
&ret.count);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_strings", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp)
{
static gstrings_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gstrings_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth("kadm5_get_strings", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings,
&ret.count);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_strings", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 22,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void ncq_err(NCQTransferState *ncq_tfs)
{
IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
ide_state->error = ABRT_ERR;
ide_state->status = READY_STAT | ERR_STAT;
ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
}
Commit Message:
CWE ID: | static void ncq_err(NCQTransferState *ncq_tfs)
{
IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
ide_state->error = ABRT_ERR;
ide_state->status = READY_STAT | ERR_STAT;
ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
ncq_tfs->used = 0;
}
| 26,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
| 7,099 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER)
dev = alloc_netdev(0, "pvceth%d", ether_setup);
else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-264 | static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER) {
dev = alloc_netdev(0, "pvceth%d", ether_setup);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
} else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
random_ether_addr(dev->dev_addr);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
| 23,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool GLES2DecoderImpl::SimulateAttrib0(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
if (static_cast<GLsizei>(size_needed) > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
if (info->divisor())
glVertexAttribDivisorANGLE(0, 0);
*simulated = true;
return true;
}
Commit Message: Always write data to new buffer in SimulateAttrib0
This is to work around linux nvidia driver bug.
TEST=asan
BUG=118970
Review URL: http://codereview.chromium.org/10019003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131538 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool GLES2DecoderImpl::SimulateAttrib0(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_;
if (new_buffer) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
}
if (new_buffer ||
(attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3])))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
if (info->divisor())
glVertexAttribDivisorANGLE(0, 0);
*simulated = true;
return true;
}
| 28,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
old_cs = get_segment_selector(ctxt, VCPU_SREG_CS);
old_eip = ctxt->_eip;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
if (load_segment_descriptor(ctxt, sel, VCPU_SREG_CS))
return X86EMUL_CONTINUE;
ctxt->_eip = 0;
memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes);
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = old_eip;
return em_push(ctxt);
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: stable@vger.kernel.org
Signed-off-by: Nadav Amit <namit@cs.technion.ac.il>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-264 | static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
int cpl = ctxt->ops->cpl(ctxt);
old_eip = ctxt->_eip;
ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return X86EMUL_CONTINUE;
rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
/* If we failed, we tainted the memory, but the very least we should
restore cs */
if (rc != X86EMUL_CONTINUE)
goto fail;
return rc;
fail:
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
| 24,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: MYSQLND_METHOD(mysqlnd_conn_data, set_server_option)(MYSQLND_CONN_DATA * const conn, enum_mysqlnd_server_option option TSRMLS_DC)
{
size_t this_func = STRUCT_OFFSET(struct st_mysqlnd_conn_data_methods, set_server_option);
zend_uchar buffer[2];
enum_func_status ret = FAIL;
DBG_ENTER("mysqlnd_conn_data::set_server_option");
if (PASS == conn->m->local_tx_start(conn, this_func TSRMLS_CC)) {
int2store(buffer, (unsigned int) option);
ret = conn->m->simple_command(conn, COM_SET_OPTION, buffer, sizeof(buffer), PROT_EOF_PACKET, FALSE, TRUE TSRMLS_CC);
conn->m->local_tx_end(conn, this_func, ret TSRMLS_CC);
}
DBG_RETURN(ret);
}
Commit Message:
CWE ID: CWE-284 | MYSQLND_METHOD(mysqlnd_conn_data, set_server_option)(MYSQLND_CONN_DATA * const conn, enum_mysqlnd_server_option option TSRMLS_DC)
{
size_t this_func = STRUCT_OFFSET(struct st_mysqlnd_conn_data_methods, set_server_option);
zend_uchar buffer[2];
enum_func_status ret = FAIL;
DBG_ENTER("mysqlnd_conn_data::set_server_option");
if (PASS == conn->m->local_tx_start(conn, this_func TSRMLS_CC)) {
int2store(buffer, (unsigned int) option);
ret = conn->m->simple_command(conn, COM_SET_OPTION, buffer, sizeof(buffer), PROT_EOF_PACKET, FALSE, TRUE TSRMLS_CC);
conn->m->local_tx_end(conn, this_func, ret TSRMLS_CC);
}
DBG_RETURN(ret);
}
| 4,825 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
xmlXPathStepOpPtr op,
xmlNodeSetPtr set,
int contextSize,
int minPos,
int maxPos,
int hasNsNodes)
{
if (op->ch1 != -1) {
xmlXPathCompExprPtr comp = ctxt->comp;
if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
/*
* TODO: raise an internal error.
*/
}
contextSize = xmlXPathCompOpEvalPredicate(ctxt,
&comp->steps[op->ch1], set, contextSize, hasNsNodes);
CHECK_ERROR0;
if (contextSize <= 0)
return(0);
}
/*
* Check if the node set contains a sufficient number of nodes for
* the requested range.
*/
if (contextSize < minPos) {
xmlXPathNodeSetClear(set, hasNsNodes);
return(0);
}
if (op->ch2 == -1) {
/*
* TODO: Can this ever happen?
*/
return (contextSize);
} else {
xmlDocPtr oldContextDoc;
int i, pos = 0, newContextSize = 0, contextPos = 0, res;
xmlXPathStepOpPtr exprOp;
xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
xmlNodePtr oldContextNode, contextNode = NULL;
xmlXPathContextPtr xpctxt = ctxt->context;
#ifdef LIBXML_XPTR_ENABLED
/*
* URGENT TODO: Check the following:
* We don't expect location sets if evaluating prediates, right?
* Only filters should expect location sets, right?
*/
#endif /* LIBXML_XPTR_ENABLED */
/*
* Save old context.
*/
oldContextNode = xpctxt->node;
oldContextDoc = xpctxt->doc;
/*
* Get the expression of this predicate.
*/
exprOp = &ctxt->comp->steps[op->ch2];
for (i = 0; i < set->nodeNr; i++) {
if (set->nodeTab[i] == NULL)
continue;
contextNode = set->nodeTab[i];
xpctxt->node = contextNode;
xpctxt->contextSize = contextSize;
xpctxt->proximityPosition = ++contextPos;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
if ((contextNode->type != XML_NAMESPACE_DECL) &&
(contextNode->doc != NULL))
xpctxt->doc = contextNode->doc;
/*
* Evaluate the predicate expression with 1 context node
* at a time; this node is packaged into a node set; this
* node set is handed over to the evaluation mechanism.
*/
if (contextObj == NULL)
contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
else
xmlXPathNodeSetAddUnique(contextObj->nodesetval,
contextNode);
valuePush(ctxt, contextObj);
res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
xmlXPathObjectPtr tmp;
/* pop the result if any */
tmp = valuePop(ctxt);
if (tmp != contextObj)
/*
* Free up the result
* then pop off contextObj, which will be freed later
*/
xmlXPathReleaseObject(xpctxt, tmp);
valuePop(ctxt);
goto evaluation_error;
}
if (res)
pos++;
if (res && (pos >= minPos) && (pos <= maxPos)) {
/*
* Fits in the requested range.
*/
newContextSize++;
if (minPos == maxPos) {
/*
* Only 1 node was requested.
*/
if (contextNode->type == XML_NAMESPACE_DECL) {
/*
* As always: take care of those nasty
* namespace nodes.
*/
set->nodeTab[i] = NULL;
}
xmlXPathNodeSetClear(set, hasNsNodes);
set->nodeNr = 1;
set->nodeTab[0] = contextNode;
goto evaluation_exit;
}
if (pos == maxPos) {
/*
* We are done.
*/
xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
goto evaluation_exit;
}
} else {
/*
* Remove the entry from the initial node set.
*/
set->nodeTab[i] = NULL;
if (contextNode->type == XML_NAMESPACE_DECL)
xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
}
if (exprRes != NULL) {
xmlXPathReleaseObject(ctxt->context, exprRes);
exprRes = NULL;
}
if (ctxt->value == contextObj) {
/*
* Don't free the temporary XPath object holding the
* context node, in order to avoid massive recreation
* inside this loop.
*/
valuePop(ctxt);
xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
} else {
/*
* The object was lost in the evaluation machinery.
* Can this happen? Maybe in case of internal-errors.
*/
contextObj = NULL;
}
}
goto evaluation_exit;
evaluation_error:
xmlXPathNodeSetClear(set, hasNsNodes);
newContextSize = 0;
evaluation_exit:
if (contextObj != NULL) {
if (ctxt->value == contextObj)
valuePop(ctxt);
xmlXPathReleaseObject(xpctxt, contextObj);
}
if (exprRes != NULL)
xmlXPathReleaseObject(ctxt->context, exprRes);
/*
* Reset/invalidate the context.
*/
xpctxt->node = oldContextNode;
xpctxt->doc = oldContextDoc;
xpctxt->contextSize = -1;
xpctxt->proximityPosition = -1;
return(newContextSize);
}
return(contextSize);
}
Commit Message: Fix libxml XPath bug.
BUG=89402
Review URL: http://codereview.chromium.org/7508039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95382 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
xmlXPathStepOpPtr op,
xmlNodeSetPtr set,
int contextSize,
int minPos,
int maxPos,
int hasNsNodes)
{
if (op->ch1 != -1) {
xmlXPathCompExprPtr comp = ctxt->comp;
if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
/*
* TODO: raise an internal error.
*/
}
contextSize = xmlXPathCompOpEvalPredicate(ctxt,
&comp->steps[op->ch1], set, contextSize, hasNsNodes);
CHECK_ERROR0;
if (contextSize <= 0)
return(0);
}
/*
* Check if the node set contains a sufficient number of nodes for
* the requested range.
*/
if (contextSize < minPos) {
xmlXPathNodeSetClear(set, hasNsNodes);
return(0);
}
if (op->ch2 == -1) {
/*
* TODO: Can this ever happen?
*/
return (contextSize);
} else {
xmlDocPtr oldContextDoc;
int i, pos = 0, newContextSize = 0, contextPos = 0, res;
xmlXPathStepOpPtr exprOp;
xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
xmlNodePtr oldContextNode, contextNode = NULL;
xmlXPathContextPtr xpctxt = ctxt->context;
#ifdef LIBXML_XPTR_ENABLED
/*
* URGENT TODO: Check the following:
* We don't expect location sets if evaluating prediates, right?
* Only filters should expect location sets, right?
*/
#endif /* LIBXML_XPTR_ENABLED */
/*
* Save old context.
*/
oldContextNode = xpctxt->node;
oldContextDoc = xpctxt->doc;
/*
* Get the expression of this predicate.
*/
exprOp = &ctxt->comp->steps[op->ch2];
for (i = 0; i < set->nodeNr; i++) {
if (set->nodeTab[i] == NULL)
continue;
contextNode = set->nodeTab[i];
xpctxt->node = contextNode;
xpctxt->contextSize = contextSize;
xpctxt->proximityPosition = ++contextPos;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
if ((contextNode->type != XML_NAMESPACE_DECL) &&
(contextNode->doc != NULL))
xpctxt->doc = contextNode->doc;
/*
* Evaluate the predicate expression with 1 context node
* at a time; this node is packaged into a node set; this
* node set is handed over to the evaluation mechanism.
*/
if (contextObj == NULL)
contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
else
xmlXPathNodeSetAddUnique(contextObj->nodesetval,
contextNode);
valuePush(ctxt, contextObj);
res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
xmlXPathObjectPtr tmp;
/* pop the result if any */
tmp = valuePop(ctxt);
while (tmp != contextObj) {
/*
* Free up the result
* then pop off contextObj, which will be freed later
*/
xmlXPathReleaseObject(xpctxt, tmp);
tmp = valuePop(ctxt);
}
goto evaluation_error;
}
if (res)
pos++;
if (res && (pos >= minPos) && (pos <= maxPos)) {
/*
* Fits in the requested range.
*/
newContextSize++;
if (minPos == maxPos) {
/*
* Only 1 node was requested.
*/
if (contextNode->type == XML_NAMESPACE_DECL) {
/*
* As always: take care of those nasty
* namespace nodes.
*/
set->nodeTab[i] = NULL;
}
xmlXPathNodeSetClear(set, hasNsNodes);
set->nodeNr = 1;
set->nodeTab[0] = contextNode;
goto evaluation_exit;
}
if (pos == maxPos) {
/*
* We are done.
*/
xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
goto evaluation_exit;
}
} else {
/*
* Remove the entry from the initial node set.
*/
set->nodeTab[i] = NULL;
if (contextNode->type == XML_NAMESPACE_DECL)
xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
}
if (exprRes != NULL) {
xmlXPathReleaseObject(ctxt->context, exprRes);
exprRes = NULL;
}
if (ctxt->value == contextObj) {
/*
* Don't free the temporary XPath object holding the
* context node, in order to avoid massive recreation
* inside this loop.
*/
valuePop(ctxt);
xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
} else {
/*
* The object was lost in the evaluation machinery.
* Can this happen? Maybe in case of internal-errors.
*/
contextObj = NULL;
}
}
goto evaluation_exit;
evaluation_error:
xmlXPathNodeSetClear(set, hasNsNodes);
newContextSize = 0;
evaluation_exit:
if (contextObj != NULL) {
if (ctxt->value == contextObj)
valuePop(ctxt);
xmlXPathReleaseObject(xpctxt, contextObj);
}
if (exprRes != NULL)
xmlXPathReleaseObject(ctxt->context, exprRes);
/*
* Reset/invalidate the context.
*/
xpctxt->node = oldContextNode;
xpctxt->doc = oldContextDoc;
xpctxt->contextSize = -1;
xpctxt->proximityPosition = -1;
return(newContextSize);
}
return(contextSize);
}
| 15,805 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
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 | xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if (ctxt->instate == XML_PARSER_EOF)
return(-1);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
| 7,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: long Chapters::Display::Parse(
IMkvReader* pReader,
long long pos,
long long size)
{
const long long stop = pos + size;
while (pos < stop)
{
long long id, size;
long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) // ChapterString ID
{
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
}
else if (id == 0x037C) // ChapterLanguage ID
{
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
}
else if (id == 0x037E) // ChapterCountry ID
{
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
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 | long Chapters::Display::Parse(
| 28,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: DWORD WtsSessionProcessDelegate::Core::GetExitCode() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
return exit_code;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | DWORD WtsSessionProcessDelegate::Core::GetExitCode() {
DWORD WtsSessionProcessDelegate::Core::GetProcessId() const {
DWORD pid = 0;
if (pipe_.IsValid() && get_named_pipe_client_pid_(pipe_, &pid)) {
return pid;
} else {
return 0;
}
}
bool WtsSessionProcessDelegate::Core::IsPermanentError(
int failure_count) const {
// Get exit code of the worker process if it is available.
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
// Stop trying to restart the worker process if it exited due to
// misconfiguration.
return (kMinPermanentErrorExitCode <= exit_code &&
exit_code <= kMaxPermanentErrorExitCode);
}
| 7,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec,
WORD32 i4_poc,
pocstruct_t *ps_temp_poc,
UWORD16 u2_frame_num,
dec_pic_params_t *ps_pps)
{
pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc;
pocstruct_t *ps_cur_poc = ps_temp_poc;
pic_buffer_t *pic_buf;
ivd_video_decode_op_t * ps_dec_output =
(ivd_video_decode_op_t *)ps_dec->pv_dec_out;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
dec_seq_params_t *ps_seq = ps_pps->ps_sps;
UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag;
UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;
/* high profile related declarations */
high_profile_tools_t s_high_profile;
WORD32 ret;
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0];
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1];
ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst;
ps_prev_poc->u2_frame_num = u2_frame_num;
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->i1_next_ctxt_idx = 0;
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores == 1)
ps_dec->u4_nmb_deblk = 1;
if(ps_seq->u1_mb_aff_flag == 1)
{
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores > 2)
ps_dec->u4_num_cores = 2;
}
ps_dec->u4_use_intrapred_line_copy = 0;
if (ps_seq->u1_mb_aff_flag == 0)
{
ps_dec->u4_use_intrapred_line_copy = 1;
}
ps_dec->u4_app_disable_deblk_frm = 0;
/* If degrade is enabled, set the degrade flags appropriately */
if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics)
{
WORD32 degrade_pic;
ps_dec->i4_degrade_pic_cnt++;
degrade_pic = 0;
/* If degrade is to be done in all frames, then do not check further */
switch(ps_dec->i4_degrade_pics)
{
case 4:
{
degrade_pic = 1;
break;
}
case 3:
{
if(ps_cur_slice->u1_slice_type != I_SLICE)
degrade_pic = 1;
break;
}
case 2:
{
/* If pic count hits non-degrade interval or it is an islice, then do not degrade */
if((ps_cur_slice->u1_slice_type != I_SLICE)
&& (ps_dec->i4_degrade_pic_cnt
!= ps_dec->i4_nondegrade_interval))
degrade_pic = 1;
break;
}
case 1:
{
/* Check if the current picture is non-ref */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
degrade_pic = 1;
}
break;
}
}
if(degrade_pic)
{
if(ps_dec->i4_degrade_type & 0x2)
ps_dec->u4_app_disable_deblk_frm = 1;
/* MC degrading is done only for non-ref pictures */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
if(ps_dec->i4_degrade_type & 0x4)
ps_dec->i4_mv_frac_mask = 0;
if(ps_dec->i4_degrade_type & 0x8)
ps_dec->i4_mv_frac_mask = 0;
}
}
else
ps_dec->i4_degrade_pic_cnt = 0;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_dec->u1_sl_typ_5_9
&& ((ps_cur_slice->u1_slice_type == I_SLICE)
|| (ps_cur_slice->u1_slice_type
== SI_SLICE)))
ps_err->u1_cur_pic_type = PIC_TYPE_I;
else
ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
if(ps_err->u1_pic_aud_i == PIC_TYPE_I)
{
ps_err->u1_cur_pic_type = PIC_TYPE_I;
ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
}
if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
if(ps_err->u1_err_flag)
ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr);
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending)
{
/* Reset the decoder picture buffers */
WORD32 j;
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
/* reset the decoder structure parameters related to buffer handling */
ps_dec->u1_second_field = 0;
ps_dec->i4_cur_display_seq = 0;
/********************************************************************/
/* indicate in the decoder output i4_status that some frames are being */
/* dropped, so that it resets timestamp and wait for a new sequence */
/********************************************************************/
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
}
ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps);
if(ret != OK)
return ret;
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info;
if(ps_dec->u1_separate_parse)
{
UWORD16 pic_wd = ps_dec->u4_width_at_init;
UWORD16 pic_ht = ps_dec->u4_height_at_init;
UWORD32 num_mbs;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
pic_wd = ps_dec->u2_pic_wd;
pic_ht = ps_dec->u2_pic_ht;
}
num_mbs = (pic_wd * pic_ht) >> 8;
if(ps_dec->pu1_dec_mb_map)
{
memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs);
}
if(ps_dec->pu1_recon_mb_map)
{
memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs);
}
if(ps_dec->pu2_slice_num_map)
{
memset((void *)ps_dec->pu2_slice_num_map, 0,
(num_mbs * sizeof(UWORD16)));
}
}
ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->u2_cur_slice_num = 0;
/* Initialize all the HP toolsets to zero */
ps_dec->s_high_profile.u1_scaling_present = 0;
ps_dec->s_high_profile.u1_transform8x8_present = 0;
/* Get Next Free Picture */
if(1 == ps_dec->u4_share_disp_buf)
{
UWORD32 i;
/* Free any buffer that is in the queue to be freed */
for(i = 0; i < MAX_DISP_BUFS_NEW; i++)
{
if(0 == ps_dec->u4_disp_buf_to_be_freed[i])
continue;
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i,
BUF_MGR_IO);
ps_dec->u4_disp_buf_to_be_freed[i] = 0;
ps_dec->u4_disp_buf_mapping[i] = 0;
}
}
if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field))
{
pic_buffer_t *ps_cur_pic;
WORD32 cur_pic_buf_id, cur_mv_buf_id;
col_mv_buf_t *ps_col_mv;
while(1)
{
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id])
{
break;
}
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
{
/*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0];
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic;
/* Initialize for field reference as well */
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic;
}
if(!ps_dec->ps_cur_pic)
{
WORD32 j;
H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n");
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
ps_dec->i4_cur_display_seq = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->i4_max_poc = 0;
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
}
ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag;
ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE;
H264_DEC_DEBUG_PRINT("got a buffer\n");
}
else
{
H264_DEC_DEBUG_PRINT("did not get a buffer\n");
}
ps_dec->u4_pic_buf_got = 1;
ps_dec->ps_cur_pic->i4_poc = i4_poc;
ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt =
ps_pps->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc;
ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts;
ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic);
if(u1_field_pic_flag && u1_bottom_field_flag)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
/* Point to odd lines, since it's bottom field */
ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y;
ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.ps_mv +=
((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5);
ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht
* ps_dec->u2_pic_wd) >> 5);
ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD;
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag
&& (!u1_field_pic_flag);
ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag
<< 2);
ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0];
ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->ps_top_mb_row =
ps_dec->ps_nbr_mb_row
+ ((ps_dec->u2_frm_wd_in_mbs + 1)
<< (1
- ps_dec->ps_cur_sps->u1_frame_mbs_only_flag));
ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->pu1_y = ps_dec->pu1_y_scratch[0];
ps_dec->pu1_u = ps_dec->pu1_u_scratch[0];
ps_dec->pu1_v = ps_dec->pu1_v_scratch[0];
ps_dec->u1_yuv_scratch_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0];
/* CHANGED CODE */
ps_dec->u1_mv_top_p = 0;
ps_dec->u1_mb_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_yleft = 0;
ps_dec->pu1_uleft = 0;
ps_dec->pu1_vleft = 0;
ps_dec->u1_not_wait_rec = 2;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE);
ps_dec->u4_pred_info_idx = 0;
ps_dec->u4_pred_info_pkd_idx = 0;
ps_dec->u4_dma_buf_idx = 0;
ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->i2_prev_slice_mbx = -1;
ps_dec->i2_prev_slice_mby = 0;
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u2_cur_slice_num_dec_thread = 0;
ps_dec->u2_cur_slice_num_bs = 0;
ps_dec->u4_intra_pred_line_ofst = 0;
ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line
+ (ps_dec->u2_frm_wd_in_mbs * MB_SIZE);
ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR;
ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn;
ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp;
/* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */
{
if(ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff;
ps_dec->pf_mvpred = ih264d_mvpred_mbaff;
}
else
{
ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff;
ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag;
}
}
/* Set up the Parameter for DMA transfer */
{
UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag;
UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag;
UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4)
% (ps_dec->u1_recon_mb_grp >> u1_mbaff));
UWORD16 ui16_lastmbs_widthY =
(uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 4));
UWORD16 ui16_lastmbs_widthUV =
uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 3);
ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y
<< u1_field_pic_flag;
ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv
<< u1_field_pic_flag;
if(u1_field_pic_flag)
{
ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y;
ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv;
}
/* Normal Increment of Pointer */
ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
/* End of Row Increment */
ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY
+ (PAD_LEN_Y_H << 1)
+ ps_dec->s_tran_addrecon.u2_frm_wd_y
* ((15 << u1_mbaff) + u1_mbaff));
ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV
+ (PAD_LEN_UV_H << 2)
+ ps_dec->s_tran_addrecon.u2_frm_wd_uv
* ((15 << u1_mbaff) + u1_mbaff));
/* Assign picture numbers to each frame/field */
/* only once per picture. */
ih264d_assign_pic_num(ps_dec);
ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp
<< 2) - 1 - (u1_mbaff << 2);
ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) - 1) << (4 + u1_mbaff);
}
/**********************************************************************/
/* High profile related initialization at pictrue level */
/**********************************************************************/
if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC)
{
if((ps_seq->i4_seq_scaling_matrix_present_flag)
|| (ps_pps->i4_pic_scaling_matrix_present_flag))
{
ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec);
ps_dec->s_high_profile.u1_scaling_present = 1;
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
if(ps_pps->i4_transform_8x8_mode_flag)
{
ps_dec->s_high_profile.u1_transform8x8_present = 1;
}
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
/* required while reading the transform_size_8x8 u4_flag */
ps_dec->s_high_profile.u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt;
ps_dec->i1_recon_in_thread3_flag = 1;
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon;
if(ps_dec->u1_separate_parse)
{
memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag)
{
memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon;
}
}
ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon),
ps_dec->u2_frm_wd_in_mbs, 0);
ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic;
ps_dec->u4_cur_deblk_mb_num = 0;
ps_dec->u4_deblk_mb_x = 0;
ps_dec->u4_deblk_mb_y = 0;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
Commit Message: Decoder: Fixed initialization of first_slice_in_pic
To handle some errors, first_slice_in_pic was being set to 2.
This is now cleaned up and first_slice_in_pic is set to 1 only once per pic.
This will ensure picture level initializations are done only once even in case
of error clips
Bug: 33717589
Bug: 33551775
Bug: 33716442
Bug: 33677995
Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
CWE ID: CWE-200 | WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec,
WORD32 i4_poc,
pocstruct_t *ps_temp_poc,
UWORD16 u2_frame_num,
dec_pic_params_t *ps_pps)
{
pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc;
pocstruct_t *ps_cur_poc = ps_temp_poc;
pic_buffer_t *pic_buf;
ivd_video_decode_op_t * ps_dec_output =
(ivd_video_decode_op_t *)ps_dec->pv_dec_out;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
dec_seq_params_t *ps_seq = ps_pps->ps_sps;
UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag;
UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;
/* high profile related declarations */
high_profile_tools_t s_high_profile;
WORD32 ret;
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0];
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1];
ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst;
ps_prev_poc->u2_frame_num = u2_frame_num;
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->i1_next_ctxt_idx = 0;
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores == 1)
ps_dec->u4_nmb_deblk = 1;
if(ps_seq->u1_mb_aff_flag == 1)
{
ps_dec->u4_nmb_deblk = 0;
if(ps_dec->u4_num_cores > 2)
ps_dec->u4_num_cores = 2;
}
ps_dec->u4_use_intrapred_line_copy = 0;
if (ps_seq->u1_mb_aff_flag == 0)
{
ps_dec->u4_use_intrapred_line_copy = 1;
}
ps_dec->u4_app_disable_deblk_frm = 0;
/* If degrade is enabled, set the degrade flags appropriately */
if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics)
{
WORD32 degrade_pic;
ps_dec->i4_degrade_pic_cnt++;
degrade_pic = 0;
/* If degrade is to be done in all frames, then do not check further */
switch(ps_dec->i4_degrade_pics)
{
case 4:
{
degrade_pic = 1;
break;
}
case 3:
{
if(ps_cur_slice->u1_slice_type != I_SLICE)
degrade_pic = 1;
break;
}
case 2:
{
/* If pic count hits non-degrade interval or it is an islice, then do not degrade */
if((ps_cur_slice->u1_slice_type != I_SLICE)
&& (ps_dec->i4_degrade_pic_cnt
!= ps_dec->i4_nondegrade_interval))
degrade_pic = 1;
break;
}
case 1:
{
/* Check if the current picture is non-ref */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
degrade_pic = 1;
}
break;
}
}
if(degrade_pic)
{
if(ps_dec->i4_degrade_type & 0x2)
ps_dec->u4_app_disable_deblk_frm = 1;
/* MC degrading is done only for non-ref pictures */
if(0 == ps_cur_slice->u1_nal_ref_idc)
{
if(ps_dec->i4_degrade_type & 0x4)
ps_dec->i4_mv_frac_mask = 0;
if(ps_dec->i4_degrade_type & 0x8)
ps_dec->i4_mv_frac_mask = 0;
}
}
else
ps_dec->i4_degrade_pic_cnt = 0;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_dec->u1_sl_typ_5_9
&& ((ps_cur_slice->u1_slice_type == I_SLICE)
|| (ps_cur_slice->u1_slice_type
== SI_SLICE)))
ps_err->u1_cur_pic_type = PIC_TYPE_I;
else
ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
if(ps_err->u1_pic_aud_i == PIC_TYPE_I)
{
ps_err->u1_cur_pic_type = PIC_TYPE_I;
ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
}
if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
if(ps_err->u1_err_flag)
ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr);
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending)
{
/* Reset the decoder picture buffers */
WORD32 j;
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
/* reset the decoder structure parameters related to buffer handling */
ps_dec->u1_second_field = 0;
ps_dec->i4_cur_display_seq = 0;
/********************************************************************/
/* indicate in the decoder output i4_status that some frames are being */
/* dropped, so that it resets timestamp and wait for a new sequence */
/********************************************************************/
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
}
ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps);
if(ret != OK)
return ret;
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data;
ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info;
if(ps_dec->u1_separate_parse)
{
UWORD16 pic_wd = ps_dec->u4_width_at_init;
UWORD16 pic_ht = ps_dec->u4_height_at_init;
UWORD32 num_mbs;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
pic_wd = ps_dec->u2_pic_wd;
pic_ht = ps_dec->u2_pic_ht;
}
num_mbs = (pic_wd * pic_ht) >> 8;
if(ps_dec->pu1_dec_mb_map)
{
memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs);
}
if(ps_dec->pu1_recon_mb_map)
{
memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs);
}
if(ps_dec->pu2_slice_num_map)
{
memset((void *)ps_dec->pu2_slice_num_map, 0,
(num_mbs * sizeof(UWORD16)));
}
}
ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]);
ps_dec->u2_cur_slice_num = 0;
/* Initialize all the HP toolsets to zero */
ps_dec->s_high_profile.u1_scaling_present = 0;
ps_dec->s_high_profile.u1_transform8x8_present = 0;
/* Get Next Free Picture */
if(1 == ps_dec->u4_share_disp_buf)
{
UWORD32 i;
/* Free any buffer that is in the queue to be freed */
for(i = 0; i < MAX_DISP_BUFS_NEW; i++)
{
if(0 == ps_dec->u4_disp_buf_to_be_freed[i])
continue;
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i,
BUF_MGR_IO);
ps_dec->u4_disp_buf_to_be_freed[i] = 0;
ps_dec->u4_disp_buf_mapping[i] = 0;
}
}
if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field))
{
pic_buffer_t *ps_cur_pic;
WORD32 cur_pic_buf_id, cur_mv_buf_id;
col_mv_buf_t *ps_col_mv;
while(1)
{
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id])
{
break;
}
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
{
/*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0];
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic;
/* Initialize for field reference as well */
*(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic;
}
if(!ps_dec->ps_cur_pic)
{
WORD32 j;
H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n");
for(j = 0; j < MAX_DISP_BUFS_NEW; j++)
{
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
ps_dec->au1_pic_buf_id_mv_buf_id_map[j],
BUF_MGR_REF);
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
j,
BUF_MGR_IO);
}
ps_dec->i4_cur_display_seq = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->i4_max_poc = 0;
ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
&cur_pic_buf_id);
if(ps_cur_pic == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T;
return ERROR_UNAVAIL_PICBUF_T;
}
ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr,
&cur_mv_buf_id);
if(ps_col_mv == NULL)
{
ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T;
return ERROR_UNAVAIL_MVBUF_T;
}
ps_dec->ps_cur_pic = ps_cur_pic;
ps_dec->u1_pic_buf_id = cur_pic_buf_id;
ps_cur_pic->u4_ts = ps_dec->u4_ts;
ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic;
ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id;
ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id;
ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag;
ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv;
ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0;
}
ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag;
ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE;
H264_DEC_DEBUG_PRINT("got a buffer\n");
}
else
{
H264_DEC_DEBUG_PRINT("did not get a buffer\n");
}
ps_dec->u4_pic_buf_got = 1;
ps_dec->ps_cur_pic->i4_poc = i4_poc;
ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt =
ps_pps->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc;
ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts;
ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic);
if(u1_field_pic_flag && u1_bottom_field_flag)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
/* Point to odd lines, since it's bottom field */
ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y;
ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv;
ps_dec->s_cur_pic.ps_mv +=
((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5);
ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht
* ps_dec->u2_pic_wd) >> 5);
ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD;
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag
&& (!u1_field_pic_flag);
ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag
<< 2);
ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0];
ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->ps_top_mb_row =
ps_dec->ps_nbr_mb_row
+ ((ps_dec->u2_frm_wd_in_mbs + 1)
<< (1
- ps_dec->ps_cur_sps->u1_frame_mbs_only_flag));
ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid
ps_dec->pu1_y = ps_dec->pu1_y_scratch[0];
ps_dec->pu1_u = ps_dec->pu1_u_scratch[0];
ps_dec->pu1_v = ps_dec->pu1_v_scratch[0];
ps_dec->u1_yuv_scratch_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0];
/* CHANGED CODE */
ps_dec->u1_mv_top_p = 0;
ps_dec->u1_mb_idx = 0;
/* CHANGED CODE */
ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_yleft = 0;
ps_dec->pu1_uleft = 0;
ps_dec->pu1_vleft = 0;
ps_dec->u1_not_wait_rec = 2;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE);
ps_dec->u4_pred_info_idx = 0;
ps_dec->u4_pred_info_pkd_idx = 0;
ps_dec->u4_dma_buf_idx = 0;
ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv;
ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv;
ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->i2_prev_slice_mbx = -1;
ps_dec->i2_prev_slice_mby = 0;
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u2_cur_slice_num_dec_thread = 0;
ps_dec->u2_cur_slice_num_bs = 0;
ps_dec->u4_intra_pred_line_ofst = 0;
ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line;
ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line;
ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line;
ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line
+ (ps_dec->u2_frm_wd_in_mbs * MB_SIZE);
ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR;
ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line
+ ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn;
ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp;
/* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */
{
if(ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff;
ps_dec->pf_mvpred = ih264d_mvpred_mbaff;
}
else
{
ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff;
ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag;
}
}
/* Set up the Parameter for DMA transfer */
{
UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag;
UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag;
UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4)
% (ps_dec->u1_recon_mb_grp >> u1_mbaff));
UWORD16 ui16_lastmbs_widthY =
(uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 4));
UWORD16 ui16_lastmbs_widthUV =
uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) << 3);
ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y
<< u1_field_pic_flag;
ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv
<< u1_field_pic_flag;
if(u1_field_pic_flag)
{
ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y;
ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv;
}
/* Normal Increment of Pointer */
ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4)
>> u1_mbaff);
/* End of Row Increment */
ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY
+ (PAD_LEN_Y_H << 1)
+ ps_dec->s_tran_addrecon.u2_frm_wd_y
* ((15 << u1_mbaff) + u1_mbaff));
ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV
+ (PAD_LEN_UV_H << 2)
+ ps_dec->s_tran_addrecon.u2_frm_wd_uv
* ((15 << u1_mbaff) + u1_mbaff));
/* Assign picture numbers to each frame/field */
/* only once per picture. */
ih264d_assign_pic_num(ps_dec);
ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp
<< 2) - 1 - (u1_mbaff << 2);
ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp
>> u1_mbaff) - 1) << (4 + u1_mbaff);
}
/**********************************************************************/
/* High profile related initialization at pictrue level */
/**********************************************************************/
if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC)
{
if((ps_seq->i4_seq_scaling_matrix_present_flag)
|| (ps_pps->i4_pic_scaling_matrix_present_flag))
{
ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec);
ps_dec->s_high_profile.u1_scaling_present = 1;
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
if(ps_pps->i4_transform_8x8_mode_flag)
{
ps_dec->s_high_profile.u1_transform8x8_present = 1;
}
}
else
{
ih264d_form_default_scaling_matrix(ps_dec);
}
/* required while reading the transform_size_8x8 u4_flag */
ps_dec->s_high_profile.u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt;
ps_dec->i1_recon_in_thread3_flag = 1;
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon;
if(ps_dec->u1_separate_parse)
{
memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag)
{
memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon,
sizeof(tfr_ctxt_t));
ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon;
}
}
ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon),
ps_dec->u2_frm_wd_in_mbs, 0);
ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic;
ps_dec->u4_cur_deblk_mb_num = 0;
ps_dec->u4_deblk_mb_x = 0;
ps_dec->u4_deblk_mb_y = 0;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
ps_dec->u4_first_slice_in_pic = 0;
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
| 10,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) {
status_t err;
if ((err = readMetaData()) != OK) {
return NULL;
}
Track *track = mFirstTrack;
while (index > 0) {
if (track == NULL) {
return NULL;
}
track = track->next;
--index;
}
if (track == NULL) {
return NULL;
}
Trex *trex = NULL;
int32_t trackId;
if (track->meta->findInt32(kKeyTrackID, &trackId)) {
for (size_t i = 0; i < mTrex.size(); i++) {
Trex *t = &mTrex.editItemAt(index);
if (t->track_ID == (uint32_t) trackId) {
trex = t;
break;
}
}
}
ALOGV("getTrack called, pssh: %zu", mPssh.size());
return new MPEG4Source(this,
track->meta, mDataSource, track->timescale, track->sampleTable,
mSidxEntries, trex, mMoofOffset);
}
Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track.
GenericSource: return error when no track exists.
SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor.
Bug: 21657957
Bug: 23705695
Bug: 22802344
Bug: 28799341
Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04
(cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13)
CWE ID: CWE-119 | sp<MediaSource> MPEG4Extractor::getTrack(size_t index) {
status_t err;
if ((err = readMetaData()) != OK) {
return NULL;
}
Track *track = mFirstTrack;
while (index > 0) {
if (track == NULL) {
return NULL;
}
track = track->next;
--index;
}
if (track == NULL) {
return NULL;
}
Trex *trex = NULL;
int32_t trackId;
if (track->meta->findInt32(kKeyTrackID, &trackId)) {
for (size_t i = 0; i < mTrex.size(); i++) {
Trex *t = &mTrex.editItemAt(index);
if (t->track_ID == (uint32_t) trackId) {
trex = t;
break;
}
}
} else {
ALOGE("b/21657957");
return NULL;
}
ALOGV("getTrack called, pssh: %zu", mPssh.size());
return new MPEG4Source(this,
track->meta, mDataSource, track->timescale, track->sampleTable,
mSidxEntries, trex, mMoofOffset);
}
| 21,002 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: htmlInitParserCtxt(htmlParserCtxtPtr ctxt)
{
htmlSAXHandler *sax;
if (ctxt == NULL) return(-1);
memset(ctxt, 0, sizeof(htmlParserCtxt));
ctxt->dict = xmlDictCreate();
if (ctxt->dict == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
return(-1);
}
sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler));
if (sax == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
return(-1);
}
else
memset(sax, 0, sizeof(htmlSAXHandler));
/* Allocate the Input stack */
ctxt->inputTab = (htmlParserInputPtr *)
xmlMalloc(5 * sizeof(htmlParserInputPtr));
if (ctxt->inputTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->inputNr = 0;
ctxt->inputMax = 5;
ctxt->input = NULL;
ctxt->version = NULL;
ctxt->encoding = NULL;
ctxt->standalone = -1;
ctxt->instate = XML_PARSER_START;
/* Allocate the Node stack */
ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr));
if (ctxt->nodeTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->nodeNr = 0;
ctxt->nodeMax = 10;
ctxt->node = NULL;
/* Allocate the Name stack */
ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));
if (ctxt->nameTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->nameNr = 0;
ctxt->nameMax = 0;
ctxt->name = NULL;
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->nameNr = 0;
ctxt->nameMax = 10;
ctxt->name = NULL;
ctxt->nodeInfoTab = NULL;
ctxt->nodeInfoNr = 0;
ctxt->nodeInfoMax = 0;
if (sax == NULL) ctxt->sax = (xmlSAXHandlerPtr) &htmlDefaultSAXHandler;
else {
ctxt->sax = sax;
memcpy(sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandlerV1));
}
ctxt->userData = ctxt;
ctxt->myDoc = NULL;
ctxt->wellFormed = 1;
ctxt->replaceEntities = 0;
ctxt->linenumbers = xmlLineNumbersDefaultValue;
ctxt->html = 1;
ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0;
ctxt->vctxt.userData = ctxt;
ctxt->vctxt.error = xmlParserValidityError;
ctxt->vctxt.warning = xmlParserValidityWarning;
ctxt->record_info = 0;
ctxt->validate = 0;
ctxt->nbChars = 0;
ctxt->checkIndex = 0;
ctxt->catalogs = NULL;
xmlInitNodeInfoSeq(&ctxt->node_seq);
return(0);
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <scottmg@chromium.org>
Commit-Queue: Dominic Cooney <dominicc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787 | htmlInitParserCtxt(htmlParserCtxtPtr ctxt)
{
htmlSAXHandler *sax;
if (ctxt == NULL) return(-1);
memset(ctxt, 0, sizeof(htmlParserCtxt));
ctxt->dict = xmlDictCreate();
if (ctxt->dict == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
return(-1);
}
sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler));
if (sax == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
return(-1);
}
else
memset(sax, 0, sizeof(htmlSAXHandler));
/* Allocate the Input stack */
ctxt->inputTab = (htmlParserInputPtr *)
xmlMalloc(5 * sizeof(htmlParserInputPtr));
if (ctxt->inputTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->inputNr = 0;
ctxt->inputMax = 5;
ctxt->input = NULL;
ctxt->version = NULL;
ctxt->encoding = NULL;
ctxt->standalone = -1;
ctxt->instate = XML_PARSER_START;
/* Allocate the Node stack */
ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr));
if (ctxt->nodeTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->nodeNr = 0;
ctxt->nodeMax = 10;
ctxt->node = NULL;
/* Allocate the Name stack */
ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));
if (ctxt->nameTab == NULL) {
htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
ctxt->nameNr = 0;
ctxt->nameMax = 0;
ctxt->name = NULL;
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->nameNr = 0;
ctxt->nameMax = 10;
ctxt->name = NULL;
ctxt->nodeInfoTab = NULL;
ctxt->nodeInfoNr = 0;
ctxt->nodeInfoMax = 0;
if (sax == NULL) ctxt->sax = (xmlSAXHandlerPtr) &htmlDefaultSAXHandler;
else {
ctxt->sax = sax;
memcpy(sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandlerV1));
}
ctxt->userData = ctxt;
ctxt->myDoc = NULL;
ctxt->wellFormed = 1;
ctxt->replaceEntities = 0;
ctxt->linenumbers = xmlLineNumbersDefaultValue;
ctxt->keepBlanks = xmlKeepBlanksDefaultValue;
ctxt->html = 1;
ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0;
ctxt->vctxt.userData = ctxt;
ctxt->vctxt.error = xmlParserValidityError;
ctxt->vctxt.warning = xmlParserValidityWarning;
ctxt->record_info = 0;
ctxt->validate = 0;
ctxt->nbChars = 0;
ctxt->checkIndex = 0;
ctxt->catalogs = NULL;
xmlInitNodeInfoSeq(&ctxt->node_seq);
return(0);
}
| 7,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: aspath_put (struct stream *s, struct aspath *as, int use32bit )
{
struct assegment *seg = as->segments;
size_t bytes = 0;
if (!seg || seg->length == 0)
return 0;
if (seg)
{
/*
* Hey, what do we do when we have > STREAM_WRITABLE(s) here?
* At the moment, we would write out a partial aspath, and our peer
* will complain and drop the session :-/
*
* The general assumption here is that many things tested will
* never happen. And, in real live, up to now, they have not.
*/
while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))
{
struct assegment *next = seg->next;
int written = 0;
int asns_packed = 0;
size_t lenp;
/* Overlength segments have to be split up */
while ( (seg->length - written) > AS_SEGMENT_MAX)
{
assegment_header_put (s, seg->type, AS_SEGMENT_MAX);
assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);
written += AS_SEGMENT_MAX;
bytes += ASSEGMENT_SIZE (written, use32bit);
}
/* write the final segment, probably is also the first */
lenp = assegment_header_put (s, seg->type, seg->length - written);
assegment_data_put (s, (seg->as + written), seg->length - written,
use32bit);
/* Sequence-type segments can be 'packed' together
* Case of a segment which was overlength and split up
* will be missed here, but that doesn't matter.
*/
while (next && ASSEGMENTS_PACKABLE (seg, next))
{
/* NB: We should never normally get here given we
* normalise aspath data when parse them. However, better
* safe than sorry. We potentially could call
* assegment_normalise here instead, but it's cheaper and
* easier to do it on the fly here rather than go through
* the segment list twice every time we write out
* aspath's.
*/
/* Next segment's data can fit in this one */
assegment_data_put (s, next->as, next->length, use32bit);
/* update the length of the segment header */
stream_putc_at (s, lenp, seg->length - written + next->length);
asns_packed += next->length;
next = next->next;
}
bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed,
use32bit);
seg = next;
}
}
return bytes;
}
Commit Message:
CWE ID: CWE-20 | aspath_put (struct stream *s, struct aspath *as, int use32bit )
{
struct assegment *seg = as->segments;
size_t bytes = 0;
if (!seg || seg->length == 0)
return 0;
if (seg)
{
/*
* Hey, what do we do when we have > STREAM_WRITABLE(s) here?
* At the moment, we would write out a partial aspath, and our peer
* will complain and drop the session :-/
*
* The general assumption here is that many things tested will
* never happen. And, in real live, up to now, they have not.
*/
while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))
{
struct assegment *next = seg->next;
int written = 0;
int asns_packed = 0;
size_t lenp;
/* Overlength segments have to be split up */
while ( (seg->length - written) > AS_SEGMENT_MAX)
{
assegment_header_put (s, seg->type, AS_SEGMENT_MAX);
assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);
written += AS_SEGMENT_MAX;
bytes += ASSEGMENT_SIZE (AS_SEGMENT_MAX, use32bit);
}
/* write the final segment, probably is also the first */
lenp = assegment_header_put (s, seg->type, seg->length - written);
assegment_data_put (s, (seg->as + written), seg->length - written,
use32bit);
/* Sequence-type segments can be 'packed' together
* Case of a segment which was overlength and split up
* will be missed here, but that doesn't matter.
*/
while (next && ASSEGMENTS_PACKABLE (seg, next))
{
/* NB: We should never normally get here given we
* normalise aspath data when parse them. However, better
* safe than sorry. We potentially could call
* assegment_normalise here instead, but it's cheaper and
* easier to do it on the fly here rather than go through
* the segment list twice every time we write out
* aspath's.
*/
/* Next segment's data can fit in this one */
assegment_data_put (s, next->as, next->length, use32bit);
/* update the length of the segment header */
stream_putc_at (s, lenp, seg->length - written + next->length);
asns_packed += next->length;
next = next->next;
}
bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed,
use32bit);
seg = next;
}
}
return bytes;
}
| 17,750 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
int n_read = r->end - r->begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i=0; i < ch; ++i)
if (!do_not_decode[i])
memset(residue_buffers[i], 0, sizeof(float) * n);
if (rtype == 2 && ch != 1) {
for (j=0; j < ch; ++j)
if (!do_not_decode[j])
break;
if (j == ch)
goto done;
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = (z & 1), p_inter = z>>1;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#else
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch == 1) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = 0, p_inter = z;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = 0;
p_inter = z;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = z % ch, p_inter = z/ch;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set=0;
while (pcount < part_read) {
if (pass == 0) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks+r->classbook;
int temp;
DECODE(temp,f,c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[j][i+pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype))
goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f,part_classdata);
#else
temp_free(f,classifications);
#endif
temp_alloc_restore(f,temp_alloc_point);
}
Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
CWE ID: CWE-119 | static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
unsigned int actual_size = rtype == 2 ? n*2 : n;
unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i=0; i < ch; ++i)
if (!do_not_decode[i])
memset(residue_buffers[i], 0, sizeof(float) * n);
if (rtype == 2 && ch != 1) {
for (j=0; j < ch; ++j)
if (!do_not_decode[j])
break;
if (j == ch)
goto done;
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = (z & 1), p_inter = z>>1;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#else
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch == 1) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = 0, p_inter = z;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = 0;
p_inter = z;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = z % ch, p_inter = z/ch;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set=0;
while (pcount < part_read) {
if (pass == 0) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks+r->classbook;
int temp;
DECODE(temp,f,c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[j][i+pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype))
goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f,part_classdata);
#else
temp_free(f,classifications);
#endif
temp_alloc_restore(f,temp_alloc_point);
}
| 29,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static int proc_keys_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key *key = rb_entry(_p, struct key, serial_node);
struct timespec now;
unsigned long timo;
key_ref_t key_ref, skey_ref;
char xbuf[16];
int rc;
struct keyring_search_context ctx = {
.index_key.type = key->type,
.index_key.description = key->description,
.cred = m->file->f_cred,
.match_data.cmp = lookup_user_key_possessed,
.match_data.raw_data = key,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
key_ref = make_key_ref(key, 0);
/* determine if the key is possessed by this process (a test we can
* skip if the key does not indicate the possessor can view it
*/
if (key->perm & KEY_POS_VIEW) {
skey_ref = search_my_process_keyrings(&ctx);
if (!IS_ERR(skey_ref)) {
key_ref_put(skey_ref);
key_ref = make_key_ref(key, 1);
}
}
/* check whether the current task is allowed to view the key */
rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
if (rc < 0)
return 0;
now = current_kernel_time();
rcu_read_lock();
/* come up with a suitable timeout value */
if (key->expiry == 0) {
memcpy(xbuf, "perm", 5);
} else if (now.tv_sec >= key->expiry) {
memcpy(xbuf, "expd", 5);
} else {
timo = key->expiry - now.tv_sec;
if (timo < 60)
sprintf(xbuf, "%lus", timo);
else if (timo < 60*60)
sprintf(xbuf, "%lum", timo / 60);
else if (timo < 60*60*24)
sprintf(xbuf, "%luh", timo / (60*60));
else if (timo < 60*60*24*7)
sprintf(xbuf, "%lud", timo / (60*60*24));
else
sprintf(xbuf, "%luw", timo / (60*60*24*7));
}
#define showflag(KEY, LETTER, FLAG) \
(test_bit(FLAG, &(KEY)->flags) ? LETTER : '-')
seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
key->serial,
showflag(key, 'I', KEY_FLAG_INSTANTIATED),
showflag(key, 'R', KEY_FLAG_REVOKED),
showflag(key, 'D', KEY_FLAG_DEAD),
showflag(key, 'Q', KEY_FLAG_IN_QUOTA),
showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT),
showflag(key, 'N', KEY_FLAG_NEGATIVE),
showflag(key, 'i', KEY_FLAG_INVALIDATED),
refcount_read(&key->usage),
xbuf,
key->perm,
from_kuid_munged(seq_user_ns(m), key->uid),
from_kgid_munged(seq_user_ns(m), key->gid),
key->type->name);
#undef showflag
if (key->type->describe)
key->type->describe(key, m);
seq_putc(m, '\n');
rcu_read_unlock();
return 0;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: stable@vger.kernel.org # v4.4+
Reported-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Reviewed-by: Eric Biggers <ebiggers@google.com>
CWE ID: CWE-20 | static int proc_keys_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key *key = rb_entry(_p, struct key, serial_node);
struct timespec now;
unsigned long timo;
key_ref_t key_ref, skey_ref;
char xbuf[16];
short state;
int rc;
struct keyring_search_context ctx = {
.index_key.type = key->type,
.index_key.description = key->description,
.cred = m->file->f_cred,
.match_data.cmp = lookup_user_key_possessed,
.match_data.raw_data = key,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
key_ref = make_key_ref(key, 0);
/* determine if the key is possessed by this process (a test we can
* skip if the key does not indicate the possessor can view it
*/
if (key->perm & KEY_POS_VIEW) {
skey_ref = search_my_process_keyrings(&ctx);
if (!IS_ERR(skey_ref)) {
key_ref_put(skey_ref);
key_ref = make_key_ref(key, 1);
}
}
/* check whether the current task is allowed to view the key */
rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
if (rc < 0)
return 0;
now = current_kernel_time();
rcu_read_lock();
/* come up with a suitable timeout value */
if (key->expiry == 0) {
memcpy(xbuf, "perm", 5);
} else if (now.tv_sec >= key->expiry) {
memcpy(xbuf, "expd", 5);
} else {
timo = key->expiry - now.tv_sec;
if (timo < 60)
sprintf(xbuf, "%lus", timo);
else if (timo < 60*60)
sprintf(xbuf, "%lum", timo / 60);
else if (timo < 60*60*24)
sprintf(xbuf, "%luh", timo / (60*60));
else if (timo < 60*60*24*7)
sprintf(xbuf, "%lud", timo / (60*60*24));
else
sprintf(xbuf, "%luw", timo / (60*60*24*7));
}
state = key_read_state(key);
#define showflag(KEY, LETTER, FLAG) \
(test_bit(FLAG, &(KEY)->flags) ? LETTER : '-')
seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
key->serial,
state != KEY_IS_UNINSTANTIATED ? 'I' : '-',
showflag(key, 'R', KEY_FLAG_REVOKED),
showflag(key, 'D', KEY_FLAG_DEAD),
showflag(key, 'Q', KEY_FLAG_IN_QUOTA),
showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT),
state < 0 ? 'N' : '-',
showflag(key, 'i', KEY_FLAG_INVALIDATED),
refcount_read(&key->usage),
xbuf,
key->perm,
from_kuid_munged(seq_user_ns(m), key->uid),
from_kgid_munged(seq_user_ns(m), key->gid),
key->type->name);
#undef showflag
if (key->type->describe)
key->type->describe(key, m);
seq_putc(m, '\n');
rcu_read_unlock();
return 0;
}
| 24,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
client->auth_user = client->db->auth_user;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
Commit Message: Remove too early set of auth_user
When query returns 0 rows (user not found),
this user stays as login user...
Should fix #69.
CWE ID: CWE-287 | static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
| 29,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. | Code: static int futex_wait(u32 __user *uaddr, int fshared,
u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct restart_block *restart;
struct futex_hash_bucket *hb;
struct futex_q q;
int ret;
if (!bitset)
return -EINVAL;
q.pi_state = NULL;
q.bitset = bitset;
q.rt_waiter = NULL;
q.requeue_pi_key = NULL;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
retry:
/* Prepare to wait on uaddr. */
ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
if (ret)
goto out;
/* queue_me and wait for wakeup, timeout, or a signal. */
futex_wait_queue_me(hb, &q, to);
/* If we were woken (and unqueued), we succeeded, whatever. */
ret = 0;
if (!unqueue_me(&q))
goto out_put_key;
ret = -ETIMEDOUT;
if (to && !to->task)
goto out_put_key;
/*
* We expect signal_pending(current), but we might be the
* victim of a spurious wakeup as well.
*/
if (!signal_pending(current)) {
put_futex_key(fshared, &q.key);
goto retry;
}
ret = -ERESTARTSYS;
if (!abs_time)
goto out_put_key;
restart = ¤t_thread_info()->restart_block;
restart->fn = futex_wait_restart;
restart->futex.uaddr = (u32 *)uaddr;
restart->futex.val = val;
restart->futex.time = abs_time->tv64;
restart->futex.bitset = bitset;
restart->futex.flags = FLAGS_HAS_TIMEOUT;
if (fshared)
restart->futex.flags |= FLAGS_SHARED;
if (clockrt)
restart->futex.flags |= FLAGS_CLOCKRT;
ret = -ERESTART_RESTARTBLOCK;
out_put_key:
put_futex_key(fshared, &q.key);
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
Commit Message: futex: Fix errors in nested key ref-counting
futex_wait() is leaking key references due to futex_wait_setup()
acquiring an additional reference via the queue_lock() routine. The
nested key ref-counting has been masking bugs and complicating code
analysis. queue_lock() is only called with a previously ref-counted
key, so remove the additional ref-counting from the queue_(un)lock()
functions.
Also futex_wait_requeue_pi() drops one key reference too many in
unqueue_me_pi(). Remove the key reference handling from
unqueue_me_pi(). This was paired with a queue_lock() in
futex_lock_pi(), so the count remains unchanged.
Document remaining nested key ref-counting sites.
Signed-off-by: Darren Hart <dvhart@linux.intel.com>
Reported-and-tested-by: Matthieu Fertré<matthieu.fertre@kerlabs.com>
Reported-by: Louis Rilling<louis.rilling@kerlabs.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Eric Dumazet <eric.dumazet@gmail.com>
Cc: John Kacur <jkacur@redhat.com>
Cc: Rusty Russell <rusty@rustcorp.com.au>
LKML-Reference: <4CBB17A8.70401@linux.intel.com>
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Cc: stable@kernel.org
CWE ID: CWE-119 | static int futex_wait(u32 __user *uaddr, int fshared,
u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct restart_block *restart;
struct futex_hash_bucket *hb;
struct futex_q q;
int ret;
if (!bitset)
return -EINVAL;
q.pi_state = NULL;
q.bitset = bitset;
q.rt_waiter = NULL;
q.requeue_pi_key = NULL;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
retry:
/*
* Prepare to wait on uaddr. On success, holds hb lock and increments
* q.key refs.
*/
ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
if (ret)
goto out;
/* queue_me and wait for wakeup, timeout, or a signal. */
futex_wait_queue_me(hb, &q, to);
/* If we were woken (and unqueued), we succeeded, whatever. */
ret = 0;
/* unqueue_me() drops q.key ref */
if (!unqueue_me(&q))
goto out;
ret = -ETIMEDOUT;
if (to && !to->task)
goto out;
/*
* We expect signal_pending(current), but we might be the
* victim of a spurious wakeup as well.
*/
if (!signal_pending(current))
goto retry;
ret = -ERESTARTSYS;
if (!abs_time)
goto out;
restart = ¤t_thread_info()->restart_block;
restart->fn = futex_wait_restart;
restart->futex.uaddr = (u32 *)uaddr;
restart->futex.val = val;
restart->futex.time = abs_time->tv64;
restart->futex.bitset = bitset;
restart->futex.flags = FLAGS_HAS_TIMEOUT;
if (fshared)
restart->futex.flags |= FLAGS_SHARED;
if (clockrt)
restart->futex.flags |= FLAGS_CLOCKRT;
ret = -ERESTART_RESTARTBLOCK;
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
| 18,275 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block)
{
OPJ_UINT32 l_data_size;
l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
(p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
/* We refer to data - 1 since below we incremented it */
opj_free(p_code_block->data - 1);
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
if (! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
/* We reserve the initial byte as a fake byte to a non-FF value */
/* and increment the data pointer, so that opj_mqc_init_enc() */
/* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
/* it. */
p_code_block->data[0] = 0;
p_code_block->data += 1; /*why +1 ?*/
}
return OPJ_TRUE;
}
Commit Message: Fix write heap buffer overflow in opj_mqc_byteout(). Discovered by Ke Liu of Tencent's Xuanwu LAB (#835)
CWE ID: CWE-119 | static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block)
{
OPJ_UINT32 l_data_size;
/* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
(p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
/* We refer to data - 1 since below we incremented it */
opj_free(p_code_block->data - 1);
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
if (! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
/* We reserve the initial byte as a fake byte to a non-FF value */
/* and increment the data pointer, so that opj_mqc_init_enc() */
/* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
/* it. */
p_code_block->data[0] = 0;
p_code_block->data += 1; /*why +1 ?*/
}
return OPJ_TRUE;
}
| 16,946 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: de_dotdot( char* file )
{
char* cp;
char* cp2;
int l;
/* Collapse any multiple / sequences. */
while ( ( cp = strstr( file, "//") ) != (char*) 0 )
{
for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
continue;
(void) strcpy( cp + 1, cp2 );
}
/* Remove leading ./ and any /./ sequences. */
while ( strncmp( file, "./", 2 ) == 0 )
(void) memmove( file, file + 2, strlen( file ) - 1 );
while ( ( cp = strstr( file, "/./") ) != (char*) 0 )
(void) memmove( cp, cp + 2, strlen( file ) - 1 );
/* Alternate between removing leading ../ and removing xxx/../ */
for (;;)
{
while ( strncmp( file, "../", 3 ) == 0 )
(void) memmove( file, file + 3, strlen( file ) - 2 );
cp = strstr( file, "/../" );
if ( cp == (char*) 0 )
break;
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
(void) strcpy( cp2 + 1, cp + 4 );
}
/* Also elide any xxx/.. at the end. */
while ( ( l = strlen( file ) ) > 3 &&
strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
{
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
if ( cp2 < file )
break;
*cp2 = '\0';
}
}
Commit Message: Fix heap buffer overflow in de_dotdot
CWE ID: CWE-119 | de_dotdot( char* file )
{
char* cp;
char* cp2;
int l;
/* Collapse any multiple / sequences. */
while ( ( cp = strstr( file, "//") ) != (char*) 0 )
{
for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
continue;
(void) strcpy( cp + 1, cp2 );
}
/* Remove leading ./ and any /./ sequences. */
while ( strncmp( file, "./", 2 ) == 0 )
(void) memmove( file, file + 2, strlen( file ) - 1 );
while ( ( cp = strstr( file, "/./") ) != (char*) 0 )
(void) memmove( cp, cp + 2, strlen( cp ) - 1 );
/* Alternate between removing leading ../ and removing xxx/../ */
for (;;)
{
while ( strncmp( file, "../", 3 ) == 0 )
(void) memmove( file, file + 3, strlen( file ) - 2 );
cp = strstr( file, "/../" );
if ( cp == (char*) 0 )
break;
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
(void) strcpy( cp2 + 1, cp + 4 );
}
/* Also elide any xxx/.. at the end. */
while ( ( l = strlen( file ) ) > 3 &&
strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
{
for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
continue;
if ( cp2 < file )
break;
*cp2 = '\0';
}
}
| 4,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: bool ContainOnlyOneKeyboardLayout(
const ImeConfigValue& value) {
return (value.type == ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
chromeos::input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ContainOnlyOneKeyboardLayout(
const input_method::ImeConfigValue& value) {
return (value.type == input_method::ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
| 23,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp
(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp,
SSL_USE_ETM(s))) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
Commit Message: Don't change the state of the ETM flags until CCS processing
Changing the ciphersuite during a renegotiation can result in a crash
leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS
so this is TLS only.
The problem is caused by changing the flag indicating whether to use ETM
or not immediately on negotiation of ETM, rather than at CCS. Therefore,
during a renegotiation, if the ETM state is changing (usually due to a
change of ciphersuite), then an error/crash will occur.
Due to the fact that there are separate CCS messages for read and write
we actually now need two flags to determine whether to use ETM or not.
CVE-2017-3733
Reviewed-by: Richard Levitte <levitte@openssl.org>
CWE ID: CWE-20 | int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size,
&comp, s->tlsext_use_etm)) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
| 19,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. | Code: struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
struct sctp_chunk *asconf)
{
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
struct sctp_chunk *asconf_ack;
__be16 err_code;
int length = 0;
int chunk_len;
__u32 serial;
int all_param_pass = 1;
chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
hdr = (sctp_addiphdr_t *)asconf->skb->data;
serial = ntohl(hdr->serial);
/* Skip the addiphdr and store a pointer to address parameter. */
length = sizeof(sctp_addiphdr_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
chunk_len -= length;
/* Skip the address parameter and store a pointer to the first
* asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
chunk_len -= length;
/* create an ASCONF_ACK chunk.
* Based on the definitions of parameters, we know that the size of
* ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
* parameters.
*/
asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
if (!asconf_ack)
goto done;
/* Process the TLVs contained within the ASCONF chunk. */
while (chunk_len > 0) {
err_code = sctp_process_asconf_param(asoc, asconf,
asconf_param);
/* ADDIP 4.1 A7)
* If an error response is received for a TLV parameter,
* all TLVs with no response before the failed TLV are
* considered successful if not reported. All TLVs after
* the failed response are considered unsuccessful unless
* a specific success indication is present for the parameter.
*/
if (SCTP_ERROR_NO_ERROR != err_code)
all_param_pass = 0;
if (!all_param_pass)
sctp_add_asconf_response(asconf_ack,
asconf_param->crr_id, err_code,
asconf_param);
/* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
* an IP address sends an 'Out of Resource' in its response, it
* MUST also fail any subsequent add or delete requests bundled
* in the ASCONF.
*/
if (SCTP_ERROR_RSRC_LOW == err_code)
goto done;
/* Move to the next ASCONF param. */
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
chunk_len -= length;
}
done:
asoc->peer.addip_serial++;
/* If we are sending a new ASCONF_ACK hold a reference to it in assoc
* after freeing the reference to old asconf ack if any.
*/
if (asconf_ack) {
sctp_chunk_hold(asconf_ack);
list_add_tail(&asconf_ack->transmitted_list,
&asoc->asconf_ack_list);
}
return asconf_ack;
}
Commit Message: net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks
Commit 6f4c618ddb0 ("SCTP : Add paramters validity check for
ASCONF chunk") added basic verification of ASCONF chunks, however,
it is still possible to remotely crash a server by sending a
special crafted ASCONF chunk, even up to pre 2.6.12 kernels:
skb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768
head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950
end:0x440 dev:<NULL>
------------[ cut here ]------------
kernel BUG at net/core/skbuff.c:129!
[...]
Call Trace:
<IRQ>
[<ffffffff8144fb1c>] skb_put+0x5c/0x70
[<ffffffffa01ea1c3>] sctp_addto_chunk+0x63/0xd0 [sctp]
[<ffffffffa01eadaf>] sctp_process_asconf+0x1af/0x540 [sctp]
[<ffffffff8152d025>] ? _read_unlock_bh+0x15/0x20
[<ffffffffa01e0038>] sctp_sf_do_asconf+0x168/0x240 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffff8147645d>] ? fib_rules_lookup+0xad/0xf0
[<ffffffffa01e6b22>] ? sctp_cmp_addr_exact+0x32/0x40 [sctp]
[<ffffffffa01e8393>] sctp_assoc_bh_rcv+0xd3/0x180 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff81496ded>] ip_local_deliver_finish+0xdd/0x2d0
[<ffffffff81497078>] ip_local_deliver+0x98/0xa0
[<ffffffff8149653d>] ip_rcv_finish+0x12d/0x440
[<ffffffff81496ac5>] ip_rcv+0x275/0x350
[<ffffffff8145c88b>] __netif_receive_skb+0x4ab/0x750
[<ffffffff81460588>] netif_receive_skb+0x58/0x60
This can be triggered e.g., through a simple scripted nmap
connection scan injecting the chunk after the handshake, for
example, ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
------------------ ASCONF; UNKNOWN ------------------>
... where ASCONF chunk of length 280 contains 2 parameters ...
1) Add IP address parameter (param length: 16)
2) Add/del IP address parameter (param length: 255)
... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the
Address Parameter in the ASCONF chunk is even missing, too.
This is just an example and similarly-crafted ASCONF chunks
could be used just as well.
The ASCONF chunk passes through sctp_verify_asconf() as all
parameters passed sanity checks, and after walking, we ended
up successfully at the chunk end boundary, and thus may invoke
sctp_process_asconf(). Parameter walking is done with
WORD_ROUND() to take padding into account.
In sctp_process_asconf()'s TLV processing, we may fail in
sctp_process_asconf_param() e.g., due to removal of the IP
address that is also the source address of the packet containing
the ASCONF chunk, and thus we need to add all TLVs after the
failure to our ASCONF response to remote via helper function
sctp_add_asconf_response(), which basically invokes a
sctp_addto_chunk() adding the error parameters to the given
skb.
When walking to the next parameter this time, we proceed
with ...
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
... instead of the WORD_ROUND()'ed length, thus resulting here
in an off-by-one that leads to reading the follow-up garbage
parameter length of 12336, and thus throwing an skb_over_panic
for the reply when trying to sctp_addto_chunk() next time,
which implicitly calls the skb_put() with that length.
Fix it by using sctp_walk_params() [ which is also used in
INIT parameter processing ] macro in the verification *and*
in ASCONF processing: it will make sure we don't spill over,
that we walk parameters WORD_ROUND()'ed. Moreover, we're being
more defensive and guard against unknown parameter types and
missized addresses.
Joint work with Vlad Yasevich.
Fixes: b896b82be4ae ("[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.")
Signed-off-by: Daniel Borkmann <dborkman@redhat.com>
Signed-off-by: Vlad Yasevich <vyasevich@gmail.com>
Acked-by: Neil Horman <nhorman@tuxdriver.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-399 | struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
struct sctp_chunk *asconf)
{
sctp_addip_chunk_t *addip = (sctp_addip_chunk_t *) asconf->chunk_hdr;
bool all_param_pass = true;
union sctp_params param;
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
sctp_addip_param_t *asconf_param;
struct sctp_chunk *asconf_ack;
__be16 err_code;
int length = 0;
int chunk_len;
__u32 serial;
chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
hdr = (sctp_addiphdr_t *)asconf->skb->data;
serial = ntohl(hdr->serial);
/* Skip the addiphdr and store a pointer to address parameter. */
length = sizeof(sctp_addiphdr_t);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
chunk_len -= length;
/* Skip the address parameter and store a pointer to the first
* asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
chunk_len -= length;
/* create an ASCONF_ACK chunk.
* Based on the definitions of parameters, we know that the size of
* ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
* parameters.
*/
asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
if (!asconf_ack)
goto done;
/* Process the TLVs contained within the ASCONF chunk. */
sctp_walk_params(param, addip, addip_hdr.params) {
/* Skip preceeding address parameters. */
if (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
param.p->type == SCTP_PARAM_IPV6_ADDRESS)
continue;
err_code = sctp_process_asconf_param(asoc, asconf,
param.addip);
/* ADDIP 4.1 A7)
* If an error response is received for a TLV parameter,
* all TLVs with no response before the failed TLV are
* considered successful if not reported. All TLVs after
* the failed response are considered unsuccessful unless
* a specific success indication is present for the parameter.
*/
if (err_code != SCTP_ERROR_NO_ERROR)
all_param_pass = false;
if (!all_param_pass)
sctp_add_asconf_response(asconf_ack, param.addip->crr_id,
err_code, param.addip);
/* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
* an IP address sends an 'Out of Resource' in its response, it
* MUST also fail any subsequent add or delete requests bundled
* in the ASCONF.
*/
if (err_code == SCTP_ERROR_RSRC_LOW)
goto done;
}
done:
asoc->peer.addip_serial++;
/* If we are sending a new ASCONF_ACK hold a reference to it in assoc
* after freeing the reference to old asconf ack if any.
*/
if (asconf_ack) {
sctp_chunk_hold(asconf_ack);
list_add_tail(&asconf_ack->transmitted_list,
&asoc->asconf_ack_list);
}
return asconf_ack;
}
| 20,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: static __init int seqgen_init(void)
{
rekey_seq_generator(NULL);
return 0;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <dan@doxpara.com>
Tested-by: Willy Tarreau <w@1wt.eu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: | static __init int seqgen_init(void)
get_random_bytes(random_int_secret, sizeof(random_int_secret));
return 0;
}
| 16,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. | Code: PageInfoUI::IdentityInfo::IdentityInfo()
: identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN),
safe_browsing_status(PageInfo::SAFE_BROWSING_STATUS_NONE),
connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN),
show_ssl_decision_revoke_button(false),
show_change_password_buttons(false) {}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <meacer@chromium.org>
> Reviewed-by: Bret Sepulveda <bsep@chromium.org>
> Auto-Submit: Joe DeBlasio <jdeblasio@chromium.org>
> Commit-Queue: Joe DeBlasio <jdeblasio@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#671847}
TBR=meacer@chromium.org,bsep@chromium.org,jdeblasio@chromium.org
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <tasak@google.com>
Commit-Queue: Takashi Sakamoto <tasak@google.com>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311 | PageInfoUI::IdentityInfo::IdentityInfo()
: identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN),
connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN),
show_ssl_decision_revoke_button(false),
show_change_password_buttons(false) {}
| 9,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. | Code: void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) {
FrameLoadRequest frame_request(passed_request);
FrameLoader::SetReferrerForFrameRequest(frame_request);
FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(),
frame_request.OriginDocument());
frame_request.GetResourceRequest().SetHasUserGesture(
Frame::HasTransientUserActivation(this));
Client()->Navigate(frame_request.GetResourceRequest(),
frame_request.ReplacesCurrentItem());
}
Commit Message: Move user activation check to RemoteFrame::Navigate's callers.
Currently RemoteFrame::Navigate is the user of
Frame::HasTransientUserActivation that passes a RemoteFrame*, and
it seems wrong because the user activation (user gesture) needed by
the navigation should belong to the LocalFrame that initiated the
navigation.
Follow-up CLs after this one will update UserActivation code in
Frame to take a LocalFrame* instead of a Frame*, and get rid of
redundant IPCs.
Bug: 811414
Change-Id: I771c1694043edb54374a44213d16715d9c7da704
Reviewed-on: https://chromium-review.googlesource.com/914736
Commit-Queue: Mustaq Ahmed <mustaq@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#536728}
CWE ID: CWE-190 | void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) {
FrameLoadRequest frame_request(passed_request);
FrameLoader::SetReferrerForFrameRequest(frame_request);
FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(),
frame_request.OriginDocument());
Client()->Navigate(frame_request.GetResourceRequest(),
frame_request.ReplacesCurrentItem());
}
| 7,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: png_get_int_32(png_bytep buf)
{
png_int_32 i = ((png_int_32)(*buf) << 24) +
((png_int_32)(*(buf + 1)) << 16) +
((png_int_32)(*(buf + 2)) << 8) +
(png_int_32)(*(buf + 3));
return (i);
}
Commit Message: third_party/libpng: update to 1.2.54
TBR=darin@chromium.org
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_int_32(png_bytep buf)
{
png_int_32 i = ((png_int_32)((*(buf )) & 0xff) << 24) +
((png_int_32)((*(buf + 1)) & 0xff) << 16) +
((png_int_32)((*(buf + 2)) & 0xff) << 8) +
((png_int_32)((*(buf + 3)) & 0xff) );
return (i);
}
| 24,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: log2vis_utf8 (PyObject * string, int unicode_length,
FriBidiParType base_direction, int clean, int reordernsm)
{
FriBidiChar *logical = NULL; /* input fribidi unicode buffer */
FriBidiChar *visual = NULL; /* output fribidi unicode buffer */
char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */
FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */
PyObject *result = NULL; /* failure */
/* Allocate fribidi unicode buffers */
logical = PyMem_New (FriBidiChar, unicode_length + 1);
if (logical == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate unicode buffer");
goto cleanup;
}
visual = PyMem_New (FriBidiChar, unicode_length + 1);
if (visual == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate unicode buffer");
goto cleanup;
}
/* Convert to unicode and order visually */
fribidi_set_reorder_nsm(reordernsm);
fribidi_utf8_to_unicode (PyString_AS_STRING (string),
PyString_GET_SIZE (string), logical);
if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual,
NULL, NULL, NULL))
{
PyErr_SetString (PyExc_RuntimeError,
"fribidi failed to order string");
goto cleanup;
}
/* Cleanup the string if requested */
if (clean)
fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL);
/* Allocate fribidi UTF-8 buffer */
visual_utf8 = PyMem_New(char, (unicode_length * 4)+1);
if (visual_utf8 == NULL)
{
PyErr_SetString (PyExc_MemoryError,
"failed to allocate UTF-8 buffer");
goto cleanup;
}
/* Encode the reordered string and create result string */
new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8);
result = PyString_FromStringAndSize (visual_utf8, new_len);
if (result == NULL)
/* XXX does it raise any error? */
goto cleanup;
cleanup:
/* Delete unicode buffers */
PyMem_Del (logical);
PyMem_Del (visual);
PyMem_Del (visual_utf8);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | log2vis_utf8 (PyObject * string, int unicode_length,
| 14,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. | Code: vbf_stp_error(struct worker *wrk, struct busyobj *bo)
{
ssize_t l, ll, o;
double now;
uint8_t *ptr;
struct vsb *synth_body;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
AN(bo->fetch_objcore->flags & OC_F_BUSY);
assert(bo->director_state == DIR_S_NULL);
wrk->stats->fetch_failed++;
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Error", now);
if (bo->fetch_objcore->stobj->stevedore != NULL)
ObjFreeObj(bo->wrk, bo->fetch_objcore);
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed");
http_TimeHeader(bo->beresp, "Date: ", now);
http_SetHeader(bo->beresp, "Server: Varnish");
bo->fetch_objcore->t_origin = now;
if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) {
/*
* If there is a waitinglist, it means that there is no
* grace-able object, so cache the error return for a
* short time, so the waiting list can drain, rather than
* each objcore on the waiting list sequentially attempt
* to fetch from the backend.
*/
bo->fetch_objcore->ttl = 1;
bo->fetch_objcore->grace = 5;
bo->fetch_objcore->keep = 5;
} else {
bo->fetch_objcore->ttl = 0;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
}
synth_body = VSB_new_auto();
AN(synth_body);
VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body);
AZ(VSB_finish(synth_body));
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
VSB_destroy(&synth_body);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing");
return (F_STP_FAIL);
}
assert(wrk->handling == VCL_RET_DELIVER);
bo->vfc->bo = bo;
bo->vfc->wrk = bo->wrk;
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->http = bo->beresp;
bo->vfc->esi_req = bo->bereq;
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
ll = VSB_len(synth_body);
o = 0;
while (ll > 0) {
l = ll;
if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK)
break;
memcpy(ptr, VSB_data(synth_body) + o, l);
VFP_Extend(bo->vfc, l);
ll -= l;
o += l;
}
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o));
VSB_destroy(&synth_body);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
return (F_STP_DONE);
}
Commit Message: Avoid buffer read overflow on vcl_error and -sfile
The file stevedore may return a buffer larger than asked for when
requesting storage. Due to lack of check for this condition, the code
to copy the synthetic error memory buffer from vcl_error would overrun
the buffer.
Patch by @shamger
Fixes: #2429
CWE ID: CWE-119 | vbf_stp_error(struct worker *wrk, struct busyobj *bo)
{
ssize_t l, ll, o;
double now;
uint8_t *ptr;
struct vsb *synth_body;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
AN(bo->fetch_objcore->flags & OC_F_BUSY);
assert(bo->director_state == DIR_S_NULL);
wrk->stats->fetch_failed++;
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Error", now);
if (bo->fetch_objcore->stobj->stevedore != NULL)
ObjFreeObj(bo->wrk, bo->fetch_objcore);
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed");
http_TimeHeader(bo->beresp, "Date: ", now);
http_SetHeader(bo->beresp, "Server: Varnish");
bo->fetch_objcore->t_origin = now;
if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) {
/*
* If there is a waitinglist, it means that there is no
* grace-able object, so cache the error return for a
* short time, so the waiting list can drain, rather than
* each objcore on the waiting list sequentially attempt
* to fetch from the backend.
*/
bo->fetch_objcore->ttl = 1;
bo->fetch_objcore->grace = 5;
bo->fetch_objcore->keep = 5;
} else {
bo->fetch_objcore->ttl = 0;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
}
synth_body = VSB_new_auto();
AN(synth_body);
VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body);
AZ(VSB_finish(synth_body));
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
VSB_destroy(&synth_body);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing");
return (F_STP_FAIL);
}
assert(wrk->handling == VCL_RET_DELIVER);
bo->vfc->bo = bo;
bo->vfc->wrk = bo->wrk;
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->http = bo->beresp;
bo->vfc->esi_req = bo->bereq;
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
ll = VSB_len(synth_body);
o = 0;
while (ll > 0) {
l = ll;
if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK)
break;
if (l > ll)
l = ll;
memcpy(ptr, VSB_data(synth_body) + o, l);
VFP_Extend(bo->vfc, l);
ll -= l;
o += l;
}
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o));
VSB_destroy(&synth_body);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
return (F_STP_DONE);
}
| 10,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. | Code: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
}
Commit Message: xkbcomp: fix crash when parsing an xkb_geometry section
xkb_geometry sections are ignored; previously the had done so by
returning NULL for the section's XkbFile, however some sections of the
code do not expect this. Instead, create an XkbFile for it, it will
never be processes and discarded later.
Caught with the afl fuzzer.
Signed-off-by: Ran Benita <ran234@gmail.com>
CWE ID: CWE-476 | CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
if (file->file_type == FILE_TYPE_GEOMETRY) {
log_vrb(ctx, 1,
"Geometry sections are not supported; ignoring\n");
} else {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
}
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
}
| 5,751 |