instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cssp_read_tsrequest(STREAM token, STREAM pubkey)
{
STREAM s;
int length;
int tagval;
s = tcp_recv(NULL, 4);
if (s == NULL)
return False;
if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
{
logger(Protocol, Error,
"cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x",
s->p[0]);
return False;
}
if (s->p[1] < 0x80)
length = s->p[1] - 2;
else if (s->p[1] == 0x81)
length = s->p[2] - 1;
else if (s->p[1] == 0x82)
length = (s->p[2] << 8) | s->p[3];
else
return False;
s = tcp_recv(s, length);
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
in_uint8s(s, length);
if (token)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
token->end = token->p = token->data;
out_uint8p(token, s->p, length);
s_mark_end(token);
}
if (pubkey)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
pubkey->data = pubkey->p = s->p;
pubkey->end = pubkey->data + length;
pubkey->size = length;
}
return True;
}
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 | cssp_read_tsrequest(STREAM token, STREAM pubkey)
{
STREAM s;
int length;
int tagval;
struct stream packet;
s = tcp_recv(NULL, 4);
if (s == NULL)
return False;
if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
{
logger(Protocol, Error,
"cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x",
s->p[0]);
return False;
}
if (s->p[1] < 0x80)
length = s->p[1] - 2;
else if (s->p[1] == 0x81)
length = s->p[2] - 1;
else if (s->p[1] == 0x82)
length = (s->p[2] << 8) | s->p[3];
else
return False;
s = tcp_recv(s, length);
packet = *s;
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
if (!s_check_rem(s, length))
{
rdp_protocol_error("cssp_read_tsrequest(), consume of version from stream would overrun",
&packet);
}
in_uint8s(s, length);
if (token)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
if (!s_check_rem(s, length))
{
rdp_protocol_error("cssp_read_tsrequest(), consume of token from stream would overrun",
&packet);
}
s_realloc(token, length);
s_reset(token);
out_uint8p(token, s->p, length);
s_mark_end(token);
}
if (pubkey)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
pubkey->data = pubkey->p = s->p;
pubkey->end = pubkey->data + length;
pubkey->size = length;
}
return True;
}
| 169,797 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static PHP_GINIT_FUNCTION(libxml)
{
libxml_globals->stream_context = NULL;
libxml_globals->error_buffer.c = NULL;
libxml_globals->error_list = NULL;
}
Commit Message:
CWE ID: CWE-200 | static PHP_GINIT_FUNCTION(libxml)
{
libxml_globals->stream_context = NULL;
libxml_globals->error_buffer.c = NULL;
libxml_globals->error_list = NULL;
libxml_globals->entity_loader_disabled = 0;
}
| 164,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_get_value (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_get_value (MyObject *obj, guint *ret, GError **error)
| 165,104 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; "
"т > t; [шщ] > w; ട > s;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add more confusable character map entries
When comparing domain names with top 10k domain names for confusability,
characters with diacritics are decomposed into base + diacritic marks
(Unicode Normalization Form D) and diacritics are dropped before
calculating the confusability skeleton because two characters with and
without a diacritics is NOT regarded as confusable.
However, there are a dozen of characters (most of them are Cyrillic)
with a diacritic-like mark attached but they are not decomposed into
base + diacritics by NFD (e.g. U+049B, қ; Cyrillic Small Letter Ka
with Descender). This CL treats them the same way as their "base"
characters. For instance, қ (U+049B) is treated as confusable with
Latin k because к (U+043A; Cyrillic Small Letter Ka) is.
They're curated from the following sets:
[:IdentifierStatus=Allowed:] & [:Ll:] &
[[:sc=Cyrillic:] -
[[\u01cd-\u01dc][\u1c80-\u1c8f][\u1e00-\u1e9b][\u1f00-\u1fff]
[\ua640-\ua69f][\ua720-\ua7ff]]] &
[:NFD_Inert=Yes:]
[:IdentifierStatus=Allowed:] & [:Ll:] &
[[:sc=Latin:] - [[\u01cd-\u01dc][\u1e00-\u1e9b][\ua720-\ua7ff]]] &
[:NFD_Inert=Yes:]
[:IdentifierStatus=Allowed:] & [:Ll:] & [[:sc=Greek:]] &
[:NFD_Inert=Yes:]
Bug: 793628,798892
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I20c6af13defa295f6952f33d75987e87ce1853d0
Reviewed-on: https://chromium-review.googlesource.com/860567
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Eric Lawrence <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529129}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+00FE (þ), U+03FC (ϼ), U+048F (ҏ)} => p
// - {U+0127 (ħ), U+043D (н), U+045B (ћ), U+04A3 (ң), U+04A5 (ҥ),
// U+04C8 (ӈ), U+0527 (ԧ), U+0529 (ԩ)} => h
// - {U+0138 (ĸ), U+03BA (κ), U+043A (к), U+049B (қ), U+049D (ҝ),
// U+049F (ҟ), U+04A1(ҡ), U+04C4 (ӄ), U+051F (ԟ)} => k
// - {U+0167 (ŧ), U+0442 (т), U+04AD (ҭ)} => t
// - {U+0185 (ƅ), U+044C (ь), U+048D (ҍ), U+0432 (в)} => b
// - {U+03C9 (ω), U+0448 (ш), U+0449 (щ)} => w
// - {U+043C (м), U+04CE (ӎ)} => m
// - U+0491 (ґ) => r
// - U+0493 (ғ) => f
// - U+04AB (ҫ) => c
// - U+04B1 (ұ) => y
// - U+03C7 (χ), U+04B3 (ҳ), U+04FD (ӽ), U+04FF (ӿ) => x
// - U+04BD (ҽ), U+04BF (ҿ) => e
// - U+04CF (ӏ) => l
// - U+0503 (ԃ) => d
// - U+050D (ԍ) => g
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;"
"п > n; ћ > h; ґ > r; ғ > f; ҫ > c;"
"ұ > y; [χҳӽӿ] > x; [ҽҿ] > e; ӏ > l;"
"ԃ > d; ԍ > g; ട > s"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int er_supported(ERContext *s)
{
if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice ||
!s->cur_pic.f ||
s->cur_pic.field_picture ||
s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO
)
return 0;
return 1;
}
Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile
The profile field is changed by code inside and outside the decoder,
its not a reliable indicator of the internal codec state.
Maintaining it consistency with studio_profile is messy.
Its easier to just avoid it and use only studio_profile
Fixes: assertion failure
Fixes: ffmpeg_crash_9.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-617 | static int er_supported(ERContext *s)
{
if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice ||
!s->cur_pic.f ||
s->cur_pic.field_picture
)
return 0;
return 1;
}
| 169,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nautilus_file_mark_desktop_file_trusted (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_trusted_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_trusted_task_thread_func);
g_object_unref (task);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | nautilus_file_mark_desktop_file_trusted (GFile *file,
nautilus_file_mark_desktop_file_executable (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_desktop_file_executable_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_desktop_file_executable_task_thread_func);
g_object_unref (task);
}
| 167,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void timer_config_save(UNUSED_ATTR void *data) {
assert(config != NULL);
assert(alarm_timer != NULL);
static const size_t CACHE_MAX = 256;
const char *keys[CACHE_MAX];
size_t num_keys = 0;
size_t total_candidates = 0;
pthread_mutex_lock(&lock);
for (const config_section_node_t *snode = config_section_begin(config); snode != config_section_end(config); snode = config_section_next(snode)) {
const char *section = config_section_name(snode);
if (!string_is_bdaddr(section))
continue;
if (config_has_key(config, section, "LinkKey") ||
config_has_key(config, section, "LE_KEY_PENC") ||
config_has_key(config, section, "LE_KEY_PID") ||
config_has_key(config, section, "LE_KEY_PCSRK") ||
config_has_key(config, section, "LE_KEY_LENC") ||
config_has_key(config, section, "LE_KEY_LCSRK"))
continue;
if (num_keys < CACHE_MAX)
keys[num_keys++] = section;
++total_candidates;
}
if (total_candidates > CACHE_MAX * 2)
while (num_keys > 0)
config_remove_section(config, keys[--num_keys]);
config_save(config, CONFIG_FILE_PATH);
pthread_mutex_unlock(&lock);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | static void timer_config_save(UNUSED_ATTR void *data) {
static void timer_config_save_cb(UNUSED_ATTR void *data) {
btif_config_write();
}
static void btif_config_write(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
btif_config_devcache_cleanup();
pthread_mutex_lock(&lock);
config_save(config, CONFIG_FILE_PATH);
pthread_mutex_unlock(&lock);
}
| 173,931 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
PROFILER_ENTER(context->priv->prof_nsc_decode)
context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
rc = nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
if (!rc)
return FALSE;
}
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_decode)
rc = context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!rc)
return FALSE;
}
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
| 169,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. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add confusability mapping entries for Myanmar and Georgian
U+10D5 (ვ), U+1012 (ဒ) => 3
Bug: 847242, 849398
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I9abb8560cf1c9e8e5e8d89980780b89461f7be52
Reviewed-on: https://chromium-review.googlesource.com/1091430
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565709}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0437 (з), U+0499 (ҙ), U+04E1 (ӡ), U+10D5 (ვ), U+1012 (ဒ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,152 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char *pool_strdup(const char *s)
{
char *r = pool_alloc(strlen(s) + 1);
strcpy(r, s);
return r;
}
Commit Message: prefer memcpy to strcpy
When we already know the length of a string (e.g., because
we just malloc'd to fit it), it's nicer to use memcpy than
strcpy, as it makes it more obvious that we are not going to
overflow the buffer (because the size we pass matches the
size in the allocation).
This also eliminates calls to strcpy, which make auditing
the code base harder.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static char *pool_strdup(const char *s)
{
size_t len = strlen(s) + 1;
char *r = pool_alloc(len);
memcpy(r, s, len);
return r;
}
| 167,428 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserPolicyConnector::SetDeviceCredentials(
const std::string& owner_email,
const std::string& token,
TokenType token_type) {
#if defined(OS_CHROMEOS)
if (device_data_store_.get()) {
device_data_store_->set_user_name(owner_email);
switch (token_type) {
case TOKEN_TYPE_OAUTH:
device_data_store_->SetOAuthToken(token);
break;
case TOKEN_TYPE_GAIA:
device_data_store_->SetGaiaToken(token);
break;
default:
NOTREACHED() << "Invalid token type " << token_type;
}
}
#endif
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void BrowserPolicyConnector::SetDeviceCredentials(
void BrowserPolicyConnector::RegisterForDevicePolicy(
const std::string& owner_email,
const std::string& token,
TokenType token_type) {
#if defined(OS_CHROMEOS)
if (device_data_store_.get()) {
device_data_store_->set_user_name(owner_email);
switch (token_type) {
case TOKEN_TYPE_OAUTH:
device_data_store_->SetOAuthToken(token);
break;
case TOKEN_TYPE_GAIA:
device_data_store_->SetGaiaToken(token);
break;
default:
NOTREACHED() << "Invalid token type " << token_type;
}
}
#endif
}
| 170,280 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() {
CHECK(mHandle != NULL);
memset(mHandle, 0, sizeof(tagvideoEncControls));
CHECK(mEncParams != NULL);
memset(mEncParams, 0, sizeof(tagvideoEncOptions));
if (!PVGetDefaultEncOption(mEncParams, 0)) {
ALOGE("Failed to get default encoding parameters");
return OMX_ErrorUndefined;
}
mEncParams->encMode = mEncodeMode;
mEncParams->encWidth[0] = mWidth;
mEncParams->encHeight[0] = mHeight;
mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format
mEncParams->rcType = VBR_1;
mEncParams->vbvDelay = 5.0f;
mEncParams->profile_level = CORE_PROFILE_LEVEL2;
mEncParams->packetSize = 32;
mEncParams->rvlcEnable = PV_OFF;
mEncParams->numLayers = 1;
mEncParams->timeIncRes = 1000;
mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate;
mEncParams->bitRate[0] = mBitrate;
mEncParams->iQuant[0] = 15;
mEncParams->pQuant[0] = 12;
mEncParams->quantType[0] = 0;
mEncParams->noFrameSkipped = PV_OFF;
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mInputFrameData);
mInputFrameData =
(uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1);
CHECK(mInputFrameData != NULL);
}
if (mWidth % 16 != 0 || mHeight % 16 != 0) {
ALOGE("Video frame size %dx%d must be a multiple of 16",
mWidth, mHeight);
return OMX_ErrorBadParameter;
}
if (mIDRFrameRefreshIntervalInSec < 0) {
mEncParams->intraPeriod = -1;
} else if (mIDRFrameRefreshIntervalInSec == 0) {
mEncParams->intraPeriod = 1; // All I frames
} else {
mEncParams->intraPeriod =
(mIDRFrameRefreshIntervalInSec * mFramerate) >> 16;
}
mEncParams->numIntraMB = 0;
mEncParams->sceneDetect = PV_ON;
mEncParams->searchRange = 16;
mEncParams->mv8x8Enable = PV_OFF;
mEncParams->gobHeaderInterval = 0;
mEncParams->useACPred = PV_ON;
mEncParams->intraDCVlcTh = 0;
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder.
Bug: 25812794
Change-Id: I96dc74734380d462583f6efa33d09946f9532809
(cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba)
(cherry picked from commit 0462975291796e414891e04bcec9da993914e458)
CWE ID: CWE-119 | OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() {
CHECK(mHandle != NULL);
memset(mHandle, 0, sizeof(tagvideoEncControls));
CHECK(mEncParams != NULL);
memset(mEncParams, 0, sizeof(tagvideoEncOptions));
if (!PVGetDefaultEncOption(mEncParams, 0)) {
ALOGE("Failed to get default encoding parameters");
return OMX_ErrorUndefined;
}
mEncParams->encMode = mEncodeMode;
mEncParams->encWidth[0] = mWidth;
mEncParams->encHeight[0] = mHeight;
mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format
mEncParams->rcType = VBR_1;
mEncParams->vbvDelay = 5.0f;
mEncParams->profile_level = CORE_PROFILE_LEVEL2;
mEncParams->packetSize = 32;
mEncParams->rvlcEnable = PV_OFF;
mEncParams->numLayers = 1;
mEncParams->timeIncRes = 1000;
mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate;
mEncParams->bitRate[0] = mBitrate;
mEncParams->iQuant[0] = 15;
mEncParams->pQuant[0] = 12;
mEncParams->quantType[0] = 0;
mEncParams->noFrameSkipped = PV_OFF;
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mInputFrameData);
mInputFrameData = NULL;
if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) {
ALOGE("b/25812794, Buffer size is too big.");
return OMX_ErrorBadParameter;
}
mInputFrameData =
(uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1);
CHECK(mInputFrameData != NULL);
}
if (mWidth % 16 != 0 || mHeight % 16 != 0) {
ALOGE("Video frame size %dx%d must be a multiple of 16",
mWidth, mHeight);
return OMX_ErrorBadParameter;
}
if (mIDRFrameRefreshIntervalInSec < 0) {
mEncParams->intraPeriod = -1;
} else if (mIDRFrameRefreshIntervalInSec == 0) {
mEncParams->intraPeriod = 1; // All I frames
} else {
mEncParams->intraPeriod =
(mIDRFrameRefreshIntervalInSec * mFramerate) >> 16;
}
mEncParams->numIntraMB = 0;
mEncParams->sceneDetect = PV_ON;
mEncParams->searchRange = 16;
mEncParams->mv8x8Enable = PV_OFF;
mEncParams->gobHeaderInterval = 0;
mEncParams->useACPred = PV_ON;
mEncParams->intraDCVlcTh = 0;
return OMX_ErrorNone;
}
| 173,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in which
* case, we'll have missed the might_sleep() from down_read().
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the initial
* attempt. If we go through a retry, it is extremely likely that the
* page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
Commit Message: Revert "arm64: Introduce execute-only page access permissions"
This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08.
While the aim is increased security for --x memory maps, it does not
protect against kernel level reads. Until SECCOMP is implemented for
arm64, revert this patch to avoid giving a false idea of execute-only
mappings.
Signed-off-by: Catalin Marinas <[email protected]>
CWE ID: CWE-19 | static int __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE | VM_EXEC;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in which
* case, we'll have missed the might_sleep() from down_read().
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the initial
* attempt. If we go through a retry, it is extremely likely that the
* page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
| 167,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __init files_init(unsigned long mempages)
{
unsigned long n;
filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
/*
* One file with associated inode and dcache is very roughly 1K.
* Per default don't use more than 10% of our memory for files.
*/
n = (mempages * (PAGE_SIZE / 1024)) / 10;
files_stat.max_files = max_t(unsigned long, n, NR_FILE);
files_defer_init();
lg_lock_init(&files_lglock, "files_lglock");
percpu_counter_init(&nr_files, 0);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void __init files_init(unsigned long mempages)
{
unsigned long n;
filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
/*
* One file with associated inode and dcache is very roughly 1K.
* Per default don't use more than 10% of our memory for files.
*/
n = (mempages * (PAGE_SIZE / 1024)) / 10;
files_stat.max_files = max_t(unsigned long, n, NR_FILE);
files_defer_init();
percpu_counter_init(&nr_files, 0);
}
| 166,800 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SvcTest()
: codec_iface_(0),
test_file_name_("hantro_collage_w352h288.yuv"),
stats_file_name_("hantro_collage_w352h288.stat"),
codec_initialized_(false),
decoder_(0) {
memset(&svc_, 0, sizeof(svc_));
memset(&codec_, 0, sizeof(codec_));
memset(&codec_enc_, 0, sizeof(codec_enc_));
}
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 | SvcTest()
: codec_iface_(0),
test_file_name_("hantro_collage_w352h288.yuv"),
codec_initialized_(false),
decoder_(0) {
memset(&svc_, 0, sizeof(svc_));
memset(&codec_, 0, sizeof(codec_));
memset(&codec_enc_, 0, sizeof(codec_enc_));
}
| 174,581 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)
{
u_int proto;
proto = EXTRACT_16BITS(&p[2]);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ",
tok2str(chdlc_cast_values, "0x%02x", p[0]),
tok2str(ethertype_values, "Unknown", proto),
proto,
length));
}
length -= CHDLC_HDRLEN;
p += CHDLC_HDRLEN;
switch (proto) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
break;
case CHDLC_TYPE_SLARP:
chdlc_slarp_print(ndo, p, length);
break;
#if 0
case CHDLC_TYPE_CDP:
chdlc_cdp_print(p, length);
break;
#endif
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
break;
case ETHERTYPE_ISO:
/* is the fudge byte set ? lets verify by spotting ISO headers */
if (*(p+1) == 0x81 ||
*(p+1) == 0x82 ||
*(p+1) == 0x83)
isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1);
else
isoclns_print(ndo, p, length, ndo->ndo_snapend - p);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto));
break;
}
return (CHDLC_HDRLEN);
}
Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks.
Prevent a possible buffer overread in chdlc_print() and replace the
custom check in chdlc_if_print() with a standard check in chdlc_print()
so that the latter certainly does not over-read even when reached via
juniper_chdlc_print(). Add length checks.
CWE ID: CWE-125 | chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)
{
u_int proto;
const u_char *bp = p;
if (length < CHDLC_HDRLEN)
goto trunc;
ND_TCHECK2(*p, CHDLC_HDRLEN);
proto = EXTRACT_16BITS(&p[2]);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ",
tok2str(chdlc_cast_values, "0x%02x", p[0]),
tok2str(ethertype_values, "Unknown", proto),
proto,
length));
}
length -= CHDLC_HDRLEN;
p += CHDLC_HDRLEN;
switch (proto) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
break;
case CHDLC_TYPE_SLARP:
chdlc_slarp_print(ndo, p, length);
break;
#if 0
case CHDLC_TYPE_CDP:
chdlc_cdp_print(p, length);
break;
#endif
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
break;
case ETHERTYPE_ISO:
/* is the fudge byte set ? lets verify by spotting ISO headers */
if (length < 2)
goto trunc;
ND_TCHECK_16BITS(p);
if (*(p+1) == 0x81 ||
*(p+1) == 0x82 ||
*(p+1) == 0x83)
isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1);
else
isoclns_print(ndo, p, length, ndo->ndo_snapend - p);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto));
break;
}
return (CHDLC_HDRLEN);
trunc:
ND_PRINT((ndo, "[|chdlc]"));
return ndo->ndo_snapend - bp;
}
| 170,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_iget_cache_miss(
struct xfs_mount *mp,
struct xfs_perag *pag,
xfs_trans_t *tp,
xfs_ino_t ino,
struct xfs_inode **ipp,
int flags,
int lock_flags)
{
struct xfs_inode *ip;
int error;
xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino);
int iflags;
ip = xfs_inode_alloc(mp, ino);
if (!ip)
return -ENOMEM;
error = xfs_iread(mp, tp, ip, flags);
if (error)
goto out_destroy;
if (!xfs_inode_verify_forks(ip)) {
error = -EFSCORRUPTED;
goto out_destroy;
}
trace_xfs_iget_miss(ip);
/*
* If we are allocating a new inode, then check what was returned is
* actually a free, empty inode. If we are not allocating an inode,
* the check we didn't find a free inode.
*/
if (flags & XFS_IGET_CREATE) {
if (VFS_I(ip)->i_mode != 0) {
xfs_warn(mp,
"Corruption detected! Free inode 0x%llx not marked free on disk",
ino);
error = -EFSCORRUPTED;
goto out_destroy;
}
if (ip->i_d.di_nblocks != 0) {
xfs_warn(mp,
"Corruption detected! Free inode 0x%llx has blocks allocated!",
ino);
error = -EFSCORRUPTED;
goto out_destroy;
}
} else if (VFS_I(ip)->i_mode == 0) {
error = -ENOENT;
goto out_destroy;
}
/*
* Preload the radix tree so we can insert safely under the
* write spinlock. Note that we cannot sleep inside the preload
* region. Since we can be called from transaction context, don't
* recurse into the file system.
*/
if (radix_tree_preload(GFP_NOFS)) {
error = -EAGAIN;
goto out_destroy;
}
/*
* Because the inode hasn't been added to the radix-tree yet it can't
* be found by another thread, so we can do the non-sleeping lock here.
*/
if (lock_flags) {
if (!xfs_ilock_nowait(ip, lock_flags))
BUG();
}
/*
* These values must be set before inserting the inode into the radix
* tree as the moment it is inserted a concurrent lookup (allowed by the
* RCU locking mechanism) can find it and that lookup must see that this
* is an inode currently under construction (i.e. that XFS_INEW is set).
* The ip->i_flags_lock that protects the XFS_INEW flag forms the
* memory barrier that ensures this detection works correctly at lookup
* time.
*/
iflags = XFS_INEW;
if (flags & XFS_IGET_DONTCACHE)
iflags |= XFS_IDONTCACHE;
ip->i_udquot = NULL;
ip->i_gdquot = NULL;
ip->i_pdquot = NULL;
xfs_iflags_set(ip, iflags);
/* insert the new inode */
spin_lock(&pag->pag_ici_lock);
error = radix_tree_insert(&pag->pag_ici_root, agino, ip);
if (unlikely(error)) {
WARN_ON(error != -EEXIST);
XFS_STATS_INC(mp, xs_ig_dup);
error = -EAGAIN;
goto out_preload_end;
}
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
*ipp = ip;
return 0;
out_preload_end:
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
if (lock_flags)
xfs_iunlock(ip, lock_flags);
out_destroy:
__destroy_inode(VFS_I(ip));
xfs_inode_free(ip);
return error;
}
Commit Message: xfs: validate cached inodes are free when allocated
A recent fuzzed filesystem image cached random dcache corruption
when the reproducer was run. This often showed up as panics in
lookup_slow() on a null inode->i_ops pointer when doing pathwalks.
BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
....
Call Trace:
lookup_slow+0x44/0x60
walk_component+0x3dd/0x9f0
link_path_walk+0x4a7/0x830
path_lookupat+0xc1/0x470
filename_lookup+0x129/0x270
user_path_at_empty+0x36/0x40
path_listxattr+0x98/0x110
SyS_listxattr+0x13/0x20
do_syscall_64+0xf5/0x280
entry_SYSCALL_64_after_hwframe+0x42/0xb7
but had many different failure modes including deadlocks trying to
lock the inode that was just allocated or KASAN reports of
use-after-free violations.
The cause of the problem was a corrupt INOBT on a v4 fs where the
root inode was marked as free in the inobt record. Hence when we
allocated an inode, it chose the root inode to allocate, found it in
the cache and re-initialised it.
We recently fixed a similar inode allocation issue caused by inobt
record corruption problem in xfs_iget_cache_miss() in commit
ee457001ed6c ("xfs: catch inode allocation state mismatch
corruption"). This change adds similar checks to the cache-hit path
to catch it, and turns the reproducer into a corruption shutdown
situation.
Reported-by: Wen Xu <[email protected]>
Signed-Off-By: Dave Chinner <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Carlos Maiolino <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
[darrick: fix typos in comment]
Signed-off-by: Darrick J. Wong <[email protected]>
CWE ID: CWE-476 | xfs_iget_cache_miss(
struct xfs_mount *mp,
struct xfs_perag *pag,
xfs_trans_t *tp,
xfs_ino_t ino,
struct xfs_inode **ipp,
int flags,
int lock_flags)
{
struct xfs_inode *ip;
int error;
xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino);
int iflags;
ip = xfs_inode_alloc(mp, ino);
if (!ip)
return -ENOMEM;
error = xfs_iread(mp, tp, ip, flags);
if (error)
goto out_destroy;
if (!xfs_inode_verify_forks(ip)) {
error = -EFSCORRUPTED;
goto out_destroy;
}
trace_xfs_iget_miss(ip);
/*
* Check the inode free state is valid. This also detects lookup
* racing with unlinks.
*/
error = xfs_iget_check_free_state(ip, flags);
if (error)
goto out_destroy;
/*
* Preload the radix tree so we can insert safely under the
* write spinlock. Note that we cannot sleep inside the preload
* region. Since we can be called from transaction context, don't
* recurse into the file system.
*/
if (radix_tree_preload(GFP_NOFS)) {
error = -EAGAIN;
goto out_destroy;
}
/*
* Because the inode hasn't been added to the radix-tree yet it can't
* be found by another thread, so we can do the non-sleeping lock here.
*/
if (lock_flags) {
if (!xfs_ilock_nowait(ip, lock_flags))
BUG();
}
/*
* These values must be set before inserting the inode into the radix
* tree as the moment it is inserted a concurrent lookup (allowed by the
* RCU locking mechanism) can find it and that lookup must see that this
* is an inode currently under construction (i.e. that XFS_INEW is set).
* The ip->i_flags_lock that protects the XFS_INEW flag forms the
* memory barrier that ensures this detection works correctly at lookup
* time.
*/
iflags = XFS_INEW;
if (flags & XFS_IGET_DONTCACHE)
iflags |= XFS_IDONTCACHE;
ip->i_udquot = NULL;
ip->i_gdquot = NULL;
ip->i_pdquot = NULL;
xfs_iflags_set(ip, iflags);
/* insert the new inode */
spin_lock(&pag->pag_ici_lock);
error = radix_tree_insert(&pag->pag_ici_root, agino, ip);
if (unlikely(error)) {
WARN_ON(error != -EEXIST);
XFS_STATS_INC(mp, xs_ig_dup);
error = -EAGAIN;
goto out_preload_end;
}
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
*ipp = ip;
return 0;
out_preload_end:
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
if (lock_flags)
xfs_iunlock(ip, lock_flags);
out_destroy:
__destroy_inode(VFS_I(ip));
xfs_inode_free(ip);
return error;
}
| 169,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg,
int /* flags */) {
if (msg->iov_length != 1)
return -1;
msg->ndesc_length = 0; // Messages with descriptors aren't supported yet.
return static_cast<ssize_t>(
ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base),
msg->iov[0].length));
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg,
int /* flags */) {
if (msg->iov_length != 1)
return -1;
return static_cast<ssize_t>(
ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base),
msg->iov[0].length));
}
| 170,730 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
{
struct iphdr *iph;
int room;
struct icmp_bxm icmp_param;
struct rtable *rt = skb_rtable(skb_in);
struct ipcm_cookie ipc;
__be32 saddr;
u8 tos;
struct net *net;
struct sock *sk;
if (!rt)
goto out;
net = dev_net(rt->dst.dev);
/*
* Find the original header. It is expected to be valid, of course.
* Check this, icmp_send is called from the most obscure devices
* sometimes.
*/
iph = ip_hdr(skb_in);
if ((u8 *)iph < skb_in->head ||
(skb_in->network_header + sizeof(*iph)) > skb_in->tail)
goto out;
/*
* No replies to physical multicast/broadcast
*/
if (skb_in->pkt_type != PACKET_HOST)
goto out;
/*
* Now check at the protocol level
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto out;
/*
* Only reply to fragment 0. We byte re-order the constant
* mask for efficiency.
*/
if (iph->frag_off & htons(IP_OFFSET))
goto out;
/*
* If we send an ICMP error to an ICMP error a mess would result..
*/
if (icmp_pointers[type].error) {
/*
* We are an error, check if we are replying to an
* ICMP error
*/
if (iph->protocol == IPPROTO_ICMP) {
u8 _inner_type, *itp;
itp = skb_header_pointer(skb_in,
skb_network_header(skb_in) +
(iph->ihl << 2) +
offsetof(struct icmphdr,
type) -
skb_in->data,
sizeof(_inner_type),
&_inner_type);
if (itp == NULL)
goto out;
/*
* Assume any unknown ICMP type is an error. This
* isn't specified by the RFC, but think about it..
*/
if (*itp > NR_ICMP_TYPES ||
icmp_pointers[*itp].error)
goto out;
}
}
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
/*
* Construct source address and options.
*/
saddr = iph->daddr;
if (!(rt->rt_flags & RTCF_LOCAL)) {
struct net_device *dev = NULL;
rcu_read_lock();
if (rt_is_input_route(rt) &&
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
dev = dev_get_by_index_rcu(net, rt->rt_iif);
if (dev)
saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
else
saddr = 0;
rcu_read_unlock();
}
tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
IPTOS_PREC_INTERNETCONTROL) :
iph->tos;
if (ip_options_echo(&icmp_param.replyopts, skb_in))
goto out_unlock;
/*
* Prepare data for ICMP header.
*/
icmp_param.data.icmph.type = type;
icmp_param.data.icmph.code = code;
icmp_param.data.icmph.un.gateway = info;
icmp_param.data.icmph.checksum = 0;
icmp_param.skb = skb_in;
icmp_param.offset = skb_network_offset(skb_in);
inet_sk(sk)->tos = tos;
ipc.addr = iph->saddr;
ipc.opt = &icmp_param.replyopts;
ipc.tx_flags = 0;
rt = icmp_route_lookup(net, skb_in, iph, saddr, tos,
type, code, &icmp_param);
if (IS_ERR(rt))
goto out_unlock;
if (!icmpv4_xrlim_allow(net, rt, type, code))
goto ende;
/* RFC says return as much as we can without exceeding 576 bytes. */
room = dst_mtu(&rt->dst);
if (room > 576)
room = 576;
room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen;
room -= sizeof(struct icmphdr);
icmp_param.data_len = skb_in->len - icmp_param.offset;
if (icmp_param.data_len > room)
icmp_param.data_len = room;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_push_reply(&icmp_param, &ipc, &rt);
ende:
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
out:;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
{
struct iphdr *iph;
int room;
struct icmp_bxm icmp_param;
struct rtable *rt = skb_rtable(skb_in);
struct ipcm_cookie ipc;
__be32 saddr;
u8 tos;
struct net *net;
struct sock *sk;
if (!rt)
goto out;
net = dev_net(rt->dst.dev);
/*
* Find the original header. It is expected to be valid, of course.
* Check this, icmp_send is called from the most obscure devices
* sometimes.
*/
iph = ip_hdr(skb_in);
if ((u8 *)iph < skb_in->head ||
(skb_in->network_header + sizeof(*iph)) > skb_in->tail)
goto out;
/*
* No replies to physical multicast/broadcast
*/
if (skb_in->pkt_type != PACKET_HOST)
goto out;
/*
* Now check at the protocol level
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto out;
/*
* Only reply to fragment 0. We byte re-order the constant
* mask for efficiency.
*/
if (iph->frag_off & htons(IP_OFFSET))
goto out;
/*
* If we send an ICMP error to an ICMP error a mess would result..
*/
if (icmp_pointers[type].error) {
/*
* We are an error, check if we are replying to an
* ICMP error
*/
if (iph->protocol == IPPROTO_ICMP) {
u8 _inner_type, *itp;
itp = skb_header_pointer(skb_in,
skb_network_header(skb_in) +
(iph->ihl << 2) +
offsetof(struct icmphdr,
type) -
skb_in->data,
sizeof(_inner_type),
&_inner_type);
if (itp == NULL)
goto out;
/*
* Assume any unknown ICMP type is an error. This
* isn't specified by the RFC, but think about it..
*/
if (*itp > NR_ICMP_TYPES ||
icmp_pointers[*itp].error)
goto out;
}
}
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
/*
* Construct source address and options.
*/
saddr = iph->daddr;
if (!(rt->rt_flags & RTCF_LOCAL)) {
struct net_device *dev = NULL;
rcu_read_lock();
if (rt_is_input_route(rt) &&
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
dev = dev_get_by_index_rcu(net, rt->rt_iif);
if (dev)
saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
else
saddr = 0;
rcu_read_unlock();
}
tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
IPTOS_PREC_INTERNETCONTROL) :
iph->tos;
if (ip_options_echo(&icmp_param.replyopts.opt.opt, skb_in))
goto out_unlock;
/*
* Prepare data for ICMP header.
*/
icmp_param.data.icmph.type = type;
icmp_param.data.icmph.code = code;
icmp_param.data.icmph.un.gateway = info;
icmp_param.data.icmph.checksum = 0;
icmp_param.skb = skb_in;
icmp_param.offset = skb_network_offset(skb_in);
inet_sk(sk)->tos = tos;
ipc.addr = iph->saddr;
ipc.opt = &icmp_param.replyopts.opt;
ipc.tx_flags = 0;
rt = icmp_route_lookup(net, skb_in, iph, saddr, tos,
type, code, &icmp_param);
if (IS_ERR(rt))
goto out_unlock;
if (!icmpv4_xrlim_allow(net, rt, type, code))
goto ende;
/* RFC says return as much as we can without exceeding 576 bytes. */
room = dst_mtu(&rt->dst);
if (room > 576)
room = 576;
room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
room -= sizeof(struct icmphdr);
icmp_param.data_len = skb_in->len - icmp_param.offset;
if (icmp_param.data_len > room)
icmp_param.data_len = room;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_push_reply(&icmp_param, &ipc, &rt);
ende:
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
out:;
}
| 165,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MockWebRTCPeerConnectionHandler::setLocalDescription(const WebRTCVoidRequest& request, const WebRTCSessionDescriptionDescriptor& localDescription)
{
if (!localDescription.isNull() && localDescription.type() == "offer") {
m_localDescription = localDescription;
postTask(new RTCVoidRequestTask(this, request, true));
} else
postTask(new RTCVoidRequestTask(this, request, false));
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void MockWebRTCPeerConnectionHandler::setLocalDescription(const WebRTCVoidRequest& request, const WebRTCSessionDescriptionDescriptor& localDescription)
| 170,362 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
Commit Message: Fix build
Change-Id: I96a9c437eec53a285ac96794cc1ad0c8954b27e0
CWE ID: CWE-264 | void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
| 174,157 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle,
PageLoadTracker* committed_load) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture());
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <[email protected]>
Reviewed-by: Bryan McQuade <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630870}
CWE ID: CWE-79 | UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle,
PageLoadTracker* committed_load) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture(),
!navigation_handle->NavigationInputStart().is_null());
}
| 172,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_start_timecode);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
| 174,355 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
Commit Message:
CWE ID: CWE-119 | static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
| 164,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_default_root(pool *p, int allow_symlinks, char **root) {
config_rec *c = NULL;
char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir) {
char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
struct stat st;
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = dir;
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
pr_fs_clear_cache();
res = pr_fsio_lstat(path, &st);
if (res < 0) {
xerrno = errno;
pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path,
strerror(xerrno));
errno = xerrno;
return -1;
}
if (S_ISLNK(st.st_mode)) {
pr_log_pri(PR_LOG_WARNING,
"error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks "
"config)", path);
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
Commit Message: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks
is off, to 1.3.5 branch.
CWE ID: CWE-59 | static int get_default_root(pool *p, int allow_symlinks, char **root) {
config_rec *c = NULL;
char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir) {
char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = dir;
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
res = is_symlink_path(p, path, pathlen);
if (res < 0) {
if (errno == EPERM) {
pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink "
"(denied by AllowChrootSymlinks config)", path);
}
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
| 170,070 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
Commit Message: Fix issue #674. Move regexp limits to limits.h.
CWE ID: CWE-674 | int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->levels = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
| 168,102 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
if (!is_hidden_)
return;
TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
is_hidden_ = false;
if (new_content_rendering_timeout_ &&
new_content_rendering_timeout_->IsRunning()) {
new_content_rendering_timeout_->Stop();
ClearDisplayedGraphics();
}
SendScreenRects();
RestartHangMonitorTimeoutIfNecessary();
bool needs_repainting = true;
needs_repainting_on_restore_ = false;
Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
process_->WidgetRestored();
bool is_visible = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
Source<RenderWidgetHost>(this),
Details<bool>(&is_visible));
WasResized();
}
Commit Message: Force a flush of drawing to the widget when a dialog is shown.
BUG=823353
TEST=as in bug
Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260
Reviewed-on: https://chromium-review.googlesource.com/971661
Reviewed-by: Ken Buchanan <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544518}
CWE ID: | void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
if (!is_hidden_)
return;
TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
is_hidden_ = false;
ForceFirstFrameAfterNavigationTimeout();
SendScreenRects();
RestartHangMonitorTimeoutIfNecessary();
bool needs_repainting = true;
needs_repainting_on_restore_ = false;
Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
process_->WidgetRestored();
bool is_visible = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
Source<RenderWidgetHost>(this),
Details<bool>(&is_visible));
WasResized();
}
| 173,226 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES];
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
struct page *localpage = NULL;
int ret;
if (buflen < PAGE_SIZE) {
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
localpage = alloc_page(GFP_KERNEL);
resp_buf = page_address(localpage);
if (localpage == NULL)
return -ENOMEM;
args.acl_pages[0] = localpage;
args.acl_pgbase = 0;
args.acl_len = PAGE_SIZE;
} else {
resp_buf = buf;
buf_to_pages(buf, buflen, args.acl_pages, &args.acl_pgbase);
}
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
if (res.acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, res.acl_len);
else
nfs4_write_cached_acl(inode, resp_buf, res.acl_len);
if (buf) {
ret = -ERANGE;
if (res.acl_len > buflen)
goto out_free;
if (localpage)
memcpy(buf, resp_buf, res.acl_len);
}
ret = res.acl_len;
out_free:
if (localpage)
__free_page(localpage);
return ret;
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189 | static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
int ret = -ENOMEM, npages, i, acl_len = 0;
npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
if (npages > 1) {
/* for decoding across pages */
args.acl_scratch = alloc_page(GFP_KERNEL);
if (!args.acl_scratch)
goto out_free;
}
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
/* Let decode_getfacl know not to fail if the ACL data is larger than
* the page we send as a guess */
if (buf == NULL)
res.acl_flags |= NFS4_ACL_LEN_REQUEST;
resp_buf = page_address(pages[0]);
dprintk("%s buf %p buflen %ld npages %d args.acl_len %ld\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
acl_len = res.acl_len - res.acl_data_offset;
if (acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, acl_len);
else
nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset,
acl_len);
if (buf) {
ret = -ERANGE;
if (acl_len > buflen)
goto out_free;
_copy_from_pages(buf, pages, res.acl_data_offset,
res.acl_len);
}
ret = acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (args.acl_scratch)
__free_page(args.acl_scratch);
return ret;
}
| 165,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: size_t NormalPage::objectPayloadSizeForTesting() {
size_t objectPayloadSize = 0;
Address headerAddress = payload();
markAsSwept();
ASSERT(headerAddress != payloadEnd());
do {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(headerAddress);
if (!header->isFree()) {
ASSERT(header->checkHeader());
objectPayloadSize += header->payloadSize();
}
ASSERT(header->size() < blinkPagePayloadSize());
headerAddress += header->size();
ASSERT(headerAddress <= payloadEnd());
} while (headerAddress < payloadEnd());
return objectPayloadSize;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | size_t NormalPage::objectPayloadSizeForTesting() {
size_t objectPayloadSize = 0;
Address headerAddress = payload();
markAsSwept();
ASSERT(headerAddress != payloadEnd());
do {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(headerAddress);
if (!header->isFree()) {
header->checkHeader();
objectPayloadSize += header->payloadSize();
}
ASSERT(header->size() < blinkPagePayloadSize());
headerAddress += header->size();
ASSERT(headerAddress <= payloadEnd());
} while (headerAddress < payloadEnd());
return objectPayloadSize;
}
| 172,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. Remember, I want response with just the fixed code only, No explanation. | Code: int main(void)
{
FILE *f;
char *tmpname;
f = xfmkstemp(&tmpname, NULL);
unlink(tmpname);
free(tmpname);
fclose(f);
return EXIT_FAILURE;
}
Commit Message: chsh, chfn, vipw: fix filenames collision
The utils when compiled WITHOUT libuser then mkostemp()ing
"/etc/%s.XXXXXX" where the filename prefix is argv[0] basename.
An attacker could repeatedly execute the util with modified argv[0]
and after many many attempts mkostemp() may generate suffix which
makes sense. The result maybe temporary file with name like rc.status
ld.so.preload or krb5.keytab, etc.
Note that distros usually use libuser based ch{sh,fn} or stuff from
shadow-utils.
It's probably very minor security bug.
Addresses: CVE-2015-5224
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-264 | int main(void)
{
FILE *f;
char *tmpname;
f = xfmkstemp(&tmpname, NULL, "test");
unlink(tmpname);
free(tmpname);
fclose(f);
return EXIT_FAILURE;
}
| 168,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
}
Commit Message: Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200 | usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
}
| 168,984 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels,
float source_sample_rate) {
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != source_sample_rate_) {
if (!number_of_channels ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
DLOG(ERROR) << "setFormat(" << number_of_channels << ", "
<< source_sample_rate << ") - unhandled format change";
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = 0;
source_sample_rate_ = 0;
return;
}
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = number_of_channels;
source_sample_rate_ = source_sample_rate;
if (source_sample_rate != Context()->sampleRate()) {
double scale_factor = source_sample_rate / Context()->sampleRate();
multi_channel_resampler_ = std::make_unique<MultiChannelResampler>(
scale_factor, number_of_channels);
} else {
multi_channel_resampler_.reset();
}
{
BaseAudioContext::GraphAutoLocker context_locker(Context());
Output(0).SetNumberOfChannels(number_of_channels);
}
}
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Hongchan Choi <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20 | void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels,
float source_sample_rate) {
bool is_tainted = WouldTaintOrigin();
if (is_tainted) {
PrintCORSMessage(MediaElement()->currentSrc().GetString());
}
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != source_sample_rate_) {
if (!number_of_channels ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
DLOG(ERROR) << "setFormat(" << number_of_channels << ", "
<< source_sample_rate << ") - unhandled format change";
Locker<MediaElementAudioSourceHandler> locker(*this);
source_number_of_channels_ = 0;
source_sample_rate_ = 0;
is_origin_tainted_ = is_tainted;
return;
}
// Synchronize with process() to protect |source_number_of_channels_|,
// |source_sample_rate_|, |multi_channel_resampler_|. and
// |is_origin_tainted_|.
Locker<MediaElementAudioSourceHandler> locker(*this);
is_origin_tainted_ = is_tainted;
source_number_of_channels_ = number_of_channels;
source_sample_rate_ = source_sample_rate;
if (source_sample_rate != Context()->sampleRate()) {
double scale_factor = source_sample_rate / Context()->sampleRate();
multi_channel_resampler_ = std::make_unique<MultiChannelResampler>(
scale_factor, number_of_channels);
} else {
multi_channel_resampler_.reset();
}
{
BaseAudioContext::GraphAutoLocker context_locker(Context());
Output(0).SetNumberOfChannels(number_of_channels);
}
}
}
| 173,150 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: make_transform_images(png_store *ps)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* This is in case of errors. */
safecat(ps->test, sizeof ps->test, 0, "make standard images");
/* Use next_format to enumerate all the combinations we test, including
* generating multiple low bit depth palette images.
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 0))
{
int interlace_type;
for (interlace_type = PNG_INTERLACE_NONE;
interlace_type < INTERLACE_LAST; ++interlace_type)
{
char name[FILE_NAME_SIZE];
standard_name(name, sizeof name, 0, colour_type, bit_depth,
palette_number, interlace_type, 0, 0, 0);
make_transform_image(ps, colour_type, bit_depth, palette_number,
interlace_type, name);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | make_transform_images(png_store *ps)
make_transform_images(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* This is in case of errors. */
safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
/* Use next_format to enumerate all the combinations we test, including
* generating multiple low bit depth palette images. Non-A images (palette
* and direct) are created with and without tRNS chunks.
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
{
int interlace_type;
for (interlace_type = PNG_INTERLACE_NONE;
interlace_type < INTERLACE_LAST; ++interlace_type)
{
char name[FILE_NAME_SIZE];
standard_name(name, sizeof name, 0, colour_type, bit_depth,
palette_number, interlace_type, 0, 0, do_own_interlace);
make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
interlace_type, name);
}
}
}
| 173,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void TearDown() {
delete[] src_;
delete[] ref_;
libvpx_test::ClearSystemState();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void TearDown() {
if (!use_high_bit_depth_) {
vpx_free(src_);
delete[] ref_;
#if CONFIG_VP9_HIGHBITDEPTH
} else {
vpx_free(CONVERT_TO_SHORTPTR(src_));
delete[] CONVERT_TO_SHORTPTR(ref_);
#endif // CONFIG_VP9_HIGHBITDEPTH
}
libvpx_test::ClearSystemState();
}
| 174,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) {
last_touch_event_flags_ = event.flags();
bool pointer_id_is_active = false;
for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) {
if (event.touch_id() != pointer_state_.GetPointerId(i))
continue;
pointer_id_is_active = true;
break;
}
if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) {
return false;
} else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) {
return false;
}
pointer_state_.OnTouch(event);
bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_);
pointer_state_.CleanupRemovedTouchPoints(event);
return result;
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) {
bool pointer_id_is_active = false;
for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) {
if (event.touch_id() != pointer_state_.GetPointerId(i))
continue;
pointer_id_is_active = true;
break;
}
if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) {
return false;
} else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) {
return false;
}
last_touch_event_flags_ = event.flags();
last_touch_event_latency_info_ = *event.latency();
pointer_state_.OnTouch(event);
bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_);
pointer_state_.CleanupRemovedTouchPoints(event);
return result;
}
| 171,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() {
PaintLayerCompositor* compositor = GetLayoutBox()->View()->Compositor();
if (!compositor->InCompositingMode())
return;
if (UsesCompositedScrolling()) {
DCHECK(Layer()->HasCompositedLayerMapping());
ScrollingCoordinator* scrolling_coordinator = GetScrollingCoordinator();
bool handled_scroll =
Layer()->IsRootLayer() && scrolling_coordinator &&
scrolling_coordinator->UpdateCompositedScrollOffset(this);
if (!handled_scroll) {
if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
Layer()->GetCompositedLayerMapping()->SetNeedsGraphicsLayerUpdate(
kGraphicsLayerUpdateSubtree);
}
compositor->SetNeedsCompositingUpdate(
kCompositingUpdateAfterGeometryChange);
}
if (Layer()->IsRootLayer()) {
LocalFrame* frame = GetLayoutBox()->GetFrame();
if (frame && frame->View() &&
frame->View()->HasViewportConstrainedObjects()) {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
} else {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79 | void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() {
PaintLayerCompositor* compositor = GetLayoutBox()->View()->Compositor();
if (!compositor->InCompositingMode())
return;
if (UsesCompositedScrolling()) {
DCHECK(Layer()->HasCompositedLayerMapping());
ScrollingCoordinator* scrolling_coordinator = GetScrollingCoordinator();
bool handled_scroll =
(Layer()->IsRootLayer() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) &&
scrolling_coordinator &&
scrolling_coordinator->UpdateCompositedScrollOffset(this);
if (!handled_scroll) {
if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
Layer()->GetCompositedLayerMapping()->SetNeedsGraphicsLayerUpdate(
kGraphicsLayerUpdateSubtree);
}
compositor->SetNeedsCompositingUpdate(
kCompositingUpdateAfterGeometryChange);
}
if (Layer()->IsRootLayer()) {
LocalFrame* frame = GetLayoutBox()->GetFrame();
if (frame && frame->View() &&
frame->View()->HasViewportConstrainedObjects()) {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
} else {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
| 172,047 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_generic_init)
{
char *key, *iv;
int key_len, iv_len;
zval *mcryptind;
unsigned char *key_s, *iv_s;
int max_key_size, key_size, iv_size;
php_mcrypt *pm;
int result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
max_key_size = mcrypt_enc_get_key_size(pm->td);
iv_size = mcrypt_enc_get_iv_size(pm->td);
if (key_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
}
key_s = emalloc(key_len);
memset(key_s, 0, key_len);
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
if (key_len > max_key_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
key_size = max_key_size;
} else {
key_size = key_len;
}
memcpy(key_s, key, key_len);
if (iv_len != iv_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
if (iv_len > iv_size) {
iv_len = iv_size;
}
}
memcpy(iv_s, iv, iv_len);
mcrypt_generic_deinit(pm->td);
result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
zend_list_delete(Z_LVAL_P(mcryptind));
switch (result) {
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
break;
case -1:
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
break;
}
} else {
pm->init = 1;
}
RETVAL_LONG(result);
efree(iv_s);
efree(key_s);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_generic_init)
{
char *key, *iv;
int key_len, iv_len;
zval *mcryptind;
unsigned char *key_s, *iv_s;
int max_key_size, key_size, iv_size;
php_mcrypt *pm;
int result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
max_key_size = mcrypt_enc_get_key_size(pm->td);
iv_size = mcrypt_enc_get_iv_size(pm->td);
if (key_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
}
key_s = emalloc(key_len);
memset(key_s, 0, key_len);
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
if (key_len > max_key_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
key_size = max_key_size;
} else {
key_size = key_len;
}
memcpy(key_s, key, key_len);
if (iv_len != iv_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
if (iv_len > iv_size) {
iv_len = iv_size;
}
}
memcpy(iv_s, iv, iv_len);
mcrypt_generic_deinit(pm->td);
result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
zend_list_delete(Z_LVAL_P(mcryptind));
switch (result) {
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
break;
case -1:
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
break;
}
} else {
pm->init = 1;
}
RETVAL_LONG(result);
efree(iv_s);
efree(key_s);
}
| 167,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost())
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost() ||
!framebuffer->Validate(ContextGroup(), this))
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
| 173,129 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int wvlan_uil_put_info(struct uilreq *urq, struct wl_private *lp)
{
int result = 0;
ltv_t *pLtv;
bool_t ltvAllocated = FALSE;
ENCSTRCT sEncryption;
#ifdef USE_WDS
hcf_16 hcfPort = HCF_PORT_0;
#endif /* USE_WDS */
/*------------------------------------------------------------------------*/
DBG_FUNC("wvlan_uil_put_info");
DBG_ENTER(DbgInfo);
if (urq->hcfCtx == &(lp->hcfCtx)) {
if (capable(CAP_NET_ADMIN)) {
if ((urq->data != NULL) && (urq->len != 0)) {
/* Make sure that we have at least a command and length to send. */
if (urq->len < (sizeof(hcf_16) * 2)) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "No Length/Type in LTV!!!\n");
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Verify the user buffer */
result = verify_area(VERIFY_READ, urq->data, urq->len);
if (result != 0) {
urq->result = UIL_FAILURE;
DBG_ERROR(DbgInfo, "verify_area(), VERIFY_READ FAILED\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Get only the command and length information. */
copy_from_user(&(lp->ltvRecord), urq->data, sizeof(hcf_16) * 2);
/* Make sure the incoming LTV record length is within the bounds of the
IOCTL length */
if (((lp->ltvRecord.len + 1) * sizeof(hcf_16)) > urq->len) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* If the requested length is greater than the size of our local
LTV record, try to allocate it from the kernel stack.
Otherwise, we just use our local LTV record. */
if (urq->len > sizeof(lp->ltvRecord)) {
pLtv = kmalloc(urq->len, GFP_KERNEL);
if (pLtv != NULL) {
ltvAllocated = TRUE;
} else {
DBG_ERROR(DbgInfo, "Alloc FAILED\n");
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
result = -ENOMEM;
DBG_LEAVE(DbgInfo);
return result;
}
} else {
pLtv = &(lp->ltvRecord);
}
/* Copy the data from the user's buffer into the local LTV
record data area. */
copy_from_user(pLtv, urq->data, urq->len);
/* We need to snoop the commands to see if there is anything we
need to store for the purposes of a reset or start/stop
sequence. Perform endian translation as needed */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
lp->PortType = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_MAC_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_OWN_CHANNEL:
lp->Channel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* CFG_CNF_OWN_SSID currently same as CNF_DESIRED_SSID. Do we
need separate storage for this? */
/* case CFG_CNF_OWN_SSID: */
case CFG_CNF_OWN_ATIM_WINDOW:
lp->atimWindow = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_SYSTEM_SCALE:
lp->DistanceBetweenAPs = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
case CFG_CNF_MAX_DATA_LEN:
/* TODO: determine if we are going to store anything based
on this */
break;
case CFG_CNF_PM_ENABLED:
lp->PMEnabled = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MCAST_RX:
lp->MulticastReceive = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MAX_SLEEP_DURATION:
lp->MaxSleepDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_HOLDOVER_DURATION:
lp->holdoverDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_NAME:
memset(lp->StationName, 0, sizeof(lp->StationName));
memcpy((void *)lp->StationName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_LOAD_BALANCING:
lp->loadBalancing = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MEDIUM_DISTRIBUTION:
lp->mediumDistribution = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
lp->txPowLevel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_CNF_SHORT_RETRY_LIMIT: */ /* Short Retry Limit */
/* case 0xFC33: */ /* Long Retry Limit */
case CFG_SUPPORTED_RATE_SET_CNTL: /* Supported Rate Set Control */
lp->srsc[0] = pLtv->u.u16[0];
lp->srsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_BASIC_RATE_SET_CNTL: /* Basic Rate Set Control */
lp->brsc[0] = pLtv->u.u16[0];
lp->brsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_CNF_CONNECTION_CNTL:
lp->connectionControl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
lp->DTIMPeriod = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
lp->ownBeaconInterval = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif /* WARP */
case CFG_COEXISTENSE_BEHAVIOUR: /* Coexistence behavior */
lp->coexistence = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
memcpy(&lp->wds_port[0].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_1;
break;
case CFG_CNF_WDS_ADDR2:
memcpy(&lp->wds_port[1].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_2;
break;
case CFG_CNF_WDS_ADDR3:
memcpy(&lp->wds_port[2].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_3;
break;
case CFG_CNF_WDS_ADDR4:
memcpy(&lp->wds_port[3].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_4;
break;
case CFG_CNF_WDS_ADDR5:
memcpy(&lp->wds_port[4].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_5;
break;
case CFG_CNF_WDS_ADDR6:
memcpy(&lp->wds_port[5].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
case CFG_CNF_MCAST_PM_BUF:
lp->multicastPMBuffering = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_REJECT_ANY:
lp->RejectAny = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_ENCRYPTION:
lp->EnableEncryption = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_AUTHENTICATION:
lp->authentication = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
/* case CFG_CNF_EXCL_UNENCRYPTED:
lp->ExcludeUnencrypted = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break; */
case CFG_CNF_MCAST_RATE:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_INTRA_BSS_RELAY:
lp->intraBSSRelay = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_MICRO_WAVE:
/* TODO: determine if we are going to store anything based on this */
break;
/*case CFG_CNF_LOAD_BALANCING:*/
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_COUNTRY_INFO: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
case CFG_CNF_OWN_SSID:
/* case CNF_DESIRED_SSID: */
case CFG_DESIRED_SSID:
memset(lp->NetworkName, 0, sizeof(lp->NetworkName));
memcpy((void *)lp->NetworkName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
/* take care of the special network name "ANY" case */
if ((strlen(&pLtv->u.u8[2]) == 0) ||
(strcmp(&pLtv->u.u8[2], "ANY") == 0) ||
(strcmp(&pLtv->u.u8[2], "any") == 0)) {
/* set the SSID_STRCT llen field (u16[0]) to zero, and the
effectually null the string u8[2] */
pLtv->u.u16[0] = 0;
pLtv->u.u8[2] = 0;
}
break;
case CFG_GROUP_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CREATE_IBSS:
lp->CreateIBSS = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_RTS_THRH:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL:
lp->TxRateControl[0] = pLtv->u.u16[0];
lp->TxRateControl[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_PROMISCUOUS_MODE:
/* TODO: determine if we are going to store anything based on this */
break;
/* case CFG_WAKE_ON_LAN: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
#if 1 /* ;? #if (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_RTS_THRH0:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL0:
/*;?no idea what this should be, get going so comment it out lp->TxRateControl = pLtv->u.u16[0];*/
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_RTS_THRH1:
lp->wds_port[0].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_RTS_THRH2:
lp->wds_port[1].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_RTS_THRH3:
lp->wds_port[2].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_RTS_THRH4:
lp->wds_port[3].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_RTS_THRH5:
lp->wds_port[4].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_RTS_THRH6:
lp->wds_port[5].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
case CFG_TX_RATE_CNTL1:
lp->wds_port[0].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_TX_RATE_CNTL2:
lp->wds_port[1].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_TX_RATE_CNTL3:
lp->wds_port[2].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_TX_RATE_CNTL4:
lp->wds_port[3].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_TX_RATE_CNTL5:
lp->wds_port[4].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_TX_RATE_CNTL6:
lp->wds_port[5].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
#endif /* (HCF_TYPE) & HCF_TYPE_AP */
case CFG_DEFAULT_KEYS:
{
CFG_DEFAULT_KEYS_STRCT *pKeys = (CFG_DEFAULT_KEYS_STRCT *)pLtv;
pKeys->key[0].len = CNV_INT_TO_LITTLE(pKeys->key[0].len);
pKeys->key[1].len = CNV_INT_TO_LITTLE(pKeys->key[1].len);
pKeys->key[2].len = CNV_INT_TO_LITTLE(pKeys->key[2].len);
pKeys->key[3].len = CNV_INT_TO_LITTLE(pKeys->key[3].len);
memcpy((void *)&(lp->DefaultKeys), (void *)pKeys,
sizeof(CFG_DEFAULT_KEYS_STRCT));
}
break;
case CFG_TX_KEY_ID:
lp->TransmitKeyID = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SCAN_SSID:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_TICK_TIME:
/* TODO: determine if we are going to store anything based on this */
break;
/* these RIDS are Info RIDs, and should they be allowed for puts??? */
case CFG_MAX_LOAD_TIME:
case CFG_DL_BUF:
/* case CFG_HSI_SUP_RANGE: */
case CFG_NIC_SERIAL_NUMBER:
case CFG_NIC_IDENTITY:
case CFG_NIC_MFI_SUP_RANGE:
case CFG_NIC_CFI_SUP_RANGE:
case CFG_NIC_TEMP_TYPE:
case CFG_NIC_PROFILE:
case CFG_FW_IDENTITY:
case CFG_FW_SUP_RANGE:
case CFG_MFI_ACT_RANGES_STA:
case CFG_CFI_ACT_RANGES_STA:
case CFG_PORT_STAT:
case CFG_CUR_SSID:
case CFG_CUR_BSSID:
case CFG_COMMS_QUALITY:
case CFG_CUR_TX_RATE:
case CFG_CUR_BEACON_INTERVAL:
case CFG_CUR_SCALE_THRH:
case CFG_PROTOCOL_RSP_TIME:
case CFG_CUR_SHORT_RETRY_LIMIT:
case CFG_CUR_LONG_RETRY_LIMIT:
case CFG_MAX_TX_LIFETIME:
case CFG_MAX_RX_LIFETIME:
case CFG_CF_POLLABLE:
case CFG_AUTHENTICATION_ALGORITHMS:
case CFG_PRIVACY_OPT_IMPLEMENTED:
/* case CFG_CURRENT_REMOTE_RATES: */
/* case CFG_CURRENT_USED_RATES: */
/* case CFG_CURRENT_SYSTEM_SCALE: */
/* case CFG_CURRENT_TX_RATE1: */
/* case CFG_CURRENT_TX_RATE2: */
/* case CFG_CURRENT_TX_RATE3: */
/* case CFG_CURRENT_TX_RATE4: */
/* case CFG_CURRENT_TX_RATE5: */
/* case CFG_CURRENT_TX_RATE6: */
case CFG_NIC_MAC_ADDR:
case CFG_PCF_INFO:
/* case CFG_CURRENT_COUNTRY_INFO: */
case CFG_PHY_TYPE:
case CFG_CUR_CHANNEL:
/* case CFG_CURRENT_POWER_STATE: */
/* case CFG_CCAMODE: */
case CFG_SUPPORTED_DATA_RATES:
break;
case CFG_AP_MODE:
/*;? lp->DownloadFirmware = (pLtv->u.u16[0]) + 1; */
DBG_ERROR(DbgInfo, "set CFG_AP_MODE no longer supported\n");
break;
case CFG_ENCRYPT_STRING:
/* TODO: ENDIAN TRANSLATION HERE??? */
memset(lp->szEncryption, 0, sizeof(lp->szEncryption));
memcpy((void *)lp->szEncryption, (void *)&pLtv->u.u8[0],
(pLtv->len * sizeof(hcf_16)));
wl_wep_decode(CRYPT_CODE, &sEncryption,
lp->szEncryption);
/* the Linux driver likes to use 1-4 for the key IDs, and then
convert to 0-3 when sending to the card. The Windows code
base used 0-3 in the API DLL, which was ported to Linux. For
the sake of the user experience, we decided to keep 0-3 as the
numbers used in the DLL; and will perform the +1 conversion here.
We could have converted the entire Linux driver, but this is
less obtrusive. This may be a "todo" to convert the whole driver */
lp->TransmitKeyID = sEncryption.wTxKeyID + 1;
lp->EnableEncryption = sEncryption.wEnabled;
memcpy(&lp->DefaultKeys, &sEncryption.EncStr,
sizeof(CFG_DEFAULT_KEYS_STRCT));
break;
/*case CFG_COUNTRY_STRING:
memset(lp->countryString, 0, sizeof(lp->countryString));
memcpy((void *)lp->countryString, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
break;
*/
case CFG_DRIVER_ENABLE:
lp->driverEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_WOLAS_ENABLE:
lp->wolasEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SET_WPA_AUTH_KEY_MGMT_SUITE:
lp->AuthKeyMgmtSuite = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_DISASSOCIATE_ADDR:
pLtv->u.u16[ETH_ALEN / 2] = CNV_INT_TO_LITTLE(pLtv->u.u16[ETH_ALEN / 2]);
break;
case CFG_ADD_TKIP_DEFAULT_KEY:
case CFG_REMOVE_TKIP_DEFAULT_KEY:
/* Endian convert the Tx Key Information */
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_ADD_TKIP_MAPPED_KEY:
break;
case CFG_REMOVE_TKIP_MAPPED_KEY:
break;
/* some RIDs just can't be put */
case CFG_MB_INFO:
case CFG_IFB:
default:
break;
}
/* This code will prevent Static Configuration Entities from
being sent to the card, as they require a call to
UIL_ACT_APPLY to take effect. Dynamic Entities will be sent
immediately */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
case CFG_CNF_OWN_MAC_ADDR:
case CFG_CNF_OWN_CHANNEL:
case CFG_CNF_OWN_SSID:
case CFG_CNF_OWN_ATIM_WINDOW:
case CFG_CNF_SYSTEM_SCALE:
case CFG_CNF_MAX_DATA_LEN:
case CFG_CNF_PM_ENABLED:
case CFG_CNF_MCAST_RX:
case CFG_CNF_MAX_SLEEP_DURATION:
case CFG_CNF_HOLDOVER_DURATION:
case CFG_CNF_OWN_NAME:
case CFG_CNF_LOAD_BALANCING:
case CFG_CNF_MEDIUM_DISTRIBUTION:
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
case CFG_CNF_CONNECTION_CNTL:
/*case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /*;? (HCF_TYPE) & HCF_TYPE_AP */
/*;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
#endif /* WARP */
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
case CFG_CNF_WDS_ADDR2:
case CFG_CNF_WDS_ADDR3:
case CFG_CNF_WDS_ADDR4:
case CFG_CNF_WDS_ADDR5:
case CFG_CNF_WDS_ADDR6:
#endif
case CFG_CNF_MCAST_PM_BUF:
case CFG_CNF_REJECT_ANY:
#endif
case CFG_CNF_ENCRYPTION:
case CFG_CNF_AUTHENTICATION:
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_EXCL_UNENCRYPTED:
case CFG_CNF_MCAST_RATE:
case CFG_CNF_INTRA_BSS_RELAY:
#endif
case CFG_CNF_MICRO_WAVE:
/* case CFG_CNF_LOAD_BALANCING: */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* case CFG_CNF_COUNTRY_INFO: */
/* case CFG_COUNTRY_STRING: */
case CFG_AP_MODE:
case CFG_ENCRYPT_STRING:
/* case CFG_DRIVER_ENABLE: */
case CFG_WOLAS_ENABLE:
case CFG_MB_INFO:
case CFG_IFB:
break;
/* Deal with this dynamic MSF RID, as it's required for WPA */
case CFG_DRIVER_ENABLE:
if (lp->driverEnable) {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_ENABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_CONNECT);
} else {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISCONNECT);
}
break;
default:
wl_act_int_off(lp);
urq->result = hcf_put_info(&(lp->hcfCtx), (LTVP) pLtv);
wl_act_int_on(lp);
break;
}
if (ltvAllocated)
kfree(pLtv);
} else {
urq->result = UIL_FAILURE;
}
} else {
DBG_ERROR(DbgInfo, "EPERM\n");
urq->result = UIL_FAILURE;
result = -EPERM;
}
} else {
DBG_ERROR(DbgInfo, "UIL_ERR_WRONG_IFB\n");
urq->result = UIL_ERR_WRONG_IFB;
}
DBG_LEAVE(DbgInfo);
return result;
} /* wvlan_uil_put_info */
Commit Message: staging: wlags49_h2: buffer overflow setting station name
We need to check the length parameter before doing the memcpy(). I've
actually changed it to strlcpy() as well so that it's NUL terminated.
You need CAP_NET_ADMIN to trigger these so it's not the end of the
world.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | int wvlan_uil_put_info(struct uilreq *urq, struct wl_private *lp)
{
int result = 0;
ltv_t *pLtv;
bool_t ltvAllocated = FALSE;
ENCSTRCT sEncryption;
size_t len;
#ifdef USE_WDS
hcf_16 hcfPort = HCF_PORT_0;
#endif /* USE_WDS */
/*------------------------------------------------------------------------*/
DBG_FUNC("wvlan_uil_put_info");
DBG_ENTER(DbgInfo);
if (urq->hcfCtx == &(lp->hcfCtx)) {
if (capable(CAP_NET_ADMIN)) {
if ((urq->data != NULL) && (urq->len != 0)) {
/* Make sure that we have at least a command and length to send. */
if (urq->len < (sizeof(hcf_16) * 2)) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "No Length/Type in LTV!!!\n");
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Verify the user buffer */
result = verify_area(VERIFY_READ, urq->data, urq->len);
if (result != 0) {
urq->result = UIL_FAILURE;
DBG_ERROR(DbgInfo, "verify_area(), VERIFY_READ FAILED\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* Get only the command and length information. */
copy_from_user(&(lp->ltvRecord), urq->data, sizeof(hcf_16) * 2);
/* Make sure the incoming LTV record length is within the bounds of the
IOCTL length */
if (((lp->ltvRecord.len + 1) * sizeof(hcf_16)) > urq->len) {
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
DBG_ERROR(DbgInfo, "UIL_ERR_LEN\n");
DBG_LEAVE(DbgInfo);
return result;
}
/* If the requested length is greater than the size of our local
LTV record, try to allocate it from the kernel stack.
Otherwise, we just use our local LTV record. */
if (urq->len > sizeof(lp->ltvRecord)) {
pLtv = kmalloc(urq->len, GFP_KERNEL);
if (pLtv != NULL) {
ltvAllocated = TRUE;
} else {
DBG_ERROR(DbgInfo, "Alloc FAILED\n");
urq->len = sizeof(lp->ltvRecord);
urq->result = UIL_ERR_LEN;
result = -ENOMEM;
DBG_LEAVE(DbgInfo);
return result;
}
} else {
pLtv = &(lp->ltvRecord);
}
/* Copy the data from the user's buffer into the local LTV
record data area. */
copy_from_user(pLtv, urq->data, urq->len);
/* We need to snoop the commands to see if there is anything we
need to store for the purposes of a reset or start/stop
sequence. Perform endian translation as needed */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
lp->PortType = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_MAC_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_OWN_CHANNEL:
lp->Channel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* CFG_CNF_OWN_SSID currently same as CNF_DESIRED_SSID. Do we
need separate storage for this? */
/* case CFG_CNF_OWN_SSID: */
case CFG_CNF_OWN_ATIM_WINDOW:
lp->atimWindow = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_SYSTEM_SCALE:
lp->DistanceBetweenAPs = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
case CFG_CNF_MAX_DATA_LEN:
/* TODO: determine if we are going to store anything based
on this */
break;
case CFG_CNF_PM_ENABLED:
lp->PMEnabled = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MCAST_RX:
lp->MulticastReceive = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MAX_SLEEP_DURATION:
lp->MaxSleepDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_HOLDOVER_DURATION:
lp->holdoverDuration = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_OWN_NAME:
memset(lp->StationName, 0, sizeof(lp->StationName));
len = min_t(size_t, pLtv->u.u16[0], sizeof(lp->StationName));
strlcpy(lp->StationName, &pLtv->u.u8[2], len);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_LOAD_BALANCING:
lp->loadBalancing = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_MEDIUM_DISTRIBUTION:
lp->mediumDistribution = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
lp->txPowLevel = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_CNF_SHORT_RETRY_LIMIT: */ /* Short Retry Limit */
/* case 0xFC33: */ /* Long Retry Limit */
case CFG_SUPPORTED_RATE_SET_CNTL: /* Supported Rate Set Control */
lp->srsc[0] = pLtv->u.u16[0];
lp->srsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_BASIC_RATE_SET_CNTL: /* Basic Rate Set Control */
lp->brsc[0] = pLtv->u.u16[0];
lp->brsc[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_CNF_CONNECTION_CNTL:
lp->connectionControl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
/* case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
lp->DTIMPeriod = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
lp->ownBeaconInterval = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif /* WARP */
case CFG_COEXISTENSE_BEHAVIOUR: /* Coexistence behavior */
lp->coexistence = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
memcpy(&lp->wds_port[0].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_1;
break;
case CFG_CNF_WDS_ADDR2:
memcpy(&lp->wds_port[1].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_2;
break;
case CFG_CNF_WDS_ADDR3:
memcpy(&lp->wds_port[2].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_3;
break;
case CFG_CNF_WDS_ADDR4:
memcpy(&lp->wds_port[3].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_4;
break;
case CFG_CNF_WDS_ADDR5:
memcpy(&lp->wds_port[4].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_5;
break;
case CFG_CNF_WDS_ADDR6:
memcpy(&lp->wds_port[5].wdsAddress, &pLtv->u.u8[0], ETH_ALEN);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
case CFG_CNF_MCAST_PM_BUF:
lp->multicastPMBuffering = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_REJECT_ANY:
lp->RejectAny = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_ENCRYPTION:
lp->EnableEncryption = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_CNF_AUTHENTICATION:
lp->authentication = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
/* case CFG_CNF_EXCL_UNENCRYPTED:
lp->ExcludeUnencrypted = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break; */
case CFG_CNF_MCAST_RATE:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CNF_INTRA_BSS_RELAY:
lp->intraBSSRelay = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#endif
case CFG_CNF_MICRO_WAVE:
/* TODO: determine if we are going to store anything based on this */
break;
/*case CFG_CNF_LOAD_BALANCING:*/
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
/* case CFG_CNF_COUNTRY_INFO: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
case CFG_CNF_OWN_SSID:
/* case CNF_DESIRED_SSID: */
case CFG_DESIRED_SSID:
memset(lp->NetworkName, 0, sizeof(lp->NetworkName));
memcpy((void *)lp->NetworkName, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
/* take care of the special network name "ANY" case */
if ((strlen(&pLtv->u.u8[2]) == 0) ||
(strcmp(&pLtv->u.u8[2], "ANY") == 0) ||
(strcmp(&pLtv->u.u8[2], "any") == 0)) {
/* set the SSID_STRCT llen field (u16[0]) to zero, and the
effectually null the string u8[2] */
pLtv->u.u16[0] = 0;
pLtv->u.u8[2] = 0;
}
break;
case CFG_GROUP_ADDR:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_CREATE_IBSS:
lp->CreateIBSS = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_RTS_THRH:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL:
lp->TxRateControl[0] = pLtv->u.u16[0];
lp->TxRateControl[1] = pLtv->u.u16[1];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
pLtv->u.u16[1] = CNV_INT_TO_LITTLE(pLtv->u.u16[1]);
break;
case CFG_PROMISCUOUS_MODE:
/* TODO: determine if we are going to store anything based on this */
break;
/* case CFG_WAKE_ON_LAN: */
/* TODO: determine if we are going to store anything based on this */
/* break; */
#if 1 /* ;? #if (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_RTS_THRH0:
lp->RTSThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_TX_RATE_CNTL0:
/*;?no idea what this should be, get going so comment it out lp->TxRateControl = pLtv->u.u16[0];*/
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
#ifdef USE_WDS
case CFG_RTS_THRH1:
lp->wds_port[0].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_RTS_THRH2:
lp->wds_port[1].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_RTS_THRH3:
lp->wds_port[2].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_RTS_THRH4:
lp->wds_port[3].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_RTS_THRH5:
lp->wds_port[4].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_RTS_THRH6:
lp->wds_port[5].rtsThreshold = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
case CFG_TX_RATE_CNTL1:
lp->wds_port[0].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_1;
break;
case CFG_TX_RATE_CNTL2:
lp->wds_port[1].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_2;
break;
case CFG_TX_RATE_CNTL3:
lp->wds_port[2].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_3;
break;
case CFG_TX_RATE_CNTL4:
lp->wds_port[3].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_4;
break;
case CFG_TX_RATE_CNTL5:
lp->wds_port[4].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_5;
break;
case CFG_TX_RATE_CNTL6:
lp->wds_port[5].txRateCntl = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
hcfPort = HCF_PORT_6;
break;
#endif /* USE_WDS */
#endif /* (HCF_TYPE) & HCF_TYPE_AP */
case CFG_DEFAULT_KEYS:
{
CFG_DEFAULT_KEYS_STRCT *pKeys = (CFG_DEFAULT_KEYS_STRCT *)pLtv;
pKeys->key[0].len = CNV_INT_TO_LITTLE(pKeys->key[0].len);
pKeys->key[1].len = CNV_INT_TO_LITTLE(pKeys->key[1].len);
pKeys->key[2].len = CNV_INT_TO_LITTLE(pKeys->key[2].len);
pKeys->key[3].len = CNV_INT_TO_LITTLE(pKeys->key[3].len);
memcpy((void *)&(lp->DefaultKeys), (void *)pKeys,
sizeof(CFG_DEFAULT_KEYS_STRCT));
}
break;
case CFG_TX_KEY_ID:
lp->TransmitKeyID = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SCAN_SSID:
/* TODO: determine if we are going to store anything based on this */
break;
case CFG_TICK_TIME:
/* TODO: determine if we are going to store anything based on this */
break;
/* these RIDS are Info RIDs, and should they be allowed for puts??? */
case CFG_MAX_LOAD_TIME:
case CFG_DL_BUF:
/* case CFG_HSI_SUP_RANGE: */
case CFG_NIC_SERIAL_NUMBER:
case CFG_NIC_IDENTITY:
case CFG_NIC_MFI_SUP_RANGE:
case CFG_NIC_CFI_SUP_RANGE:
case CFG_NIC_TEMP_TYPE:
case CFG_NIC_PROFILE:
case CFG_FW_IDENTITY:
case CFG_FW_SUP_RANGE:
case CFG_MFI_ACT_RANGES_STA:
case CFG_CFI_ACT_RANGES_STA:
case CFG_PORT_STAT:
case CFG_CUR_SSID:
case CFG_CUR_BSSID:
case CFG_COMMS_QUALITY:
case CFG_CUR_TX_RATE:
case CFG_CUR_BEACON_INTERVAL:
case CFG_CUR_SCALE_THRH:
case CFG_PROTOCOL_RSP_TIME:
case CFG_CUR_SHORT_RETRY_LIMIT:
case CFG_CUR_LONG_RETRY_LIMIT:
case CFG_MAX_TX_LIFETIME:
case CFG_MAX_RX_LIFETIME:
case CFG_CF_POLLABLE:
case CFG_AUTHENTICATION_ALGORITHMS:
case CFG_PRIVACY_OPT_IMPLEMENTED:
/* case CFG_CURRENT_REMOTE_RATES: */
/* case CFG_CURRENT_USED_RATES: */
/* case CFG_CURRENT_SYSTEM_SCALE: */
/* case CFG_CURRENT_TX_RATE1: */
/* case CFG_CURRENT_TX_RATE2: */
/* case CFG_CURRENT_TX_RATE3: */
/* case CFG_CURRENT_TX_RATE4: */
/* case CFG_CURRENT_TX_RATE5: */
/* case CFG_CURRENT_TX_RATE6: */
case CFG_NIC_MAC_ADDR:
case CFG_PCF_INFO:
/* case CFG_CURRENT_COUNTRY_INFO: */
case CFG_PHY_TYPE:
case CFG_CUR_CHANNEL:
/* case CFG_CURRENT_POWER_STATE: */
/* case CFG_CCAMODE: */
case CFG_SUPPORTED_DATA_RATES:
break;
case CFG_AP_MODE:
/*;? lp->DownloadFirmware = (pLtv->u.u16[0]) + 1; */
DBG_ERROR(DbgInfo, "set CFG_AP_MODE no longer supported\n");
break;
case CFG_ENCRYPT_STRING:
/* TODO: ENDIAN TRANSLATION HERE??? */
memset(lp->szEncryption, 0, sizeof(lp->szEncryption));
memcpy((void *)lp->szEncryption, (void *)&pLtv->u.u8[0],
(pLtv->len * sizeof(hcf_16)));
wl_wep_decode(CRYPT_CODE, &sEncryption,
lp->szEncryption);
/* the Linux driver likes to use 1-4 for the key IDs, and then
convert to 0-3 when sending to the card. The Windows code
base used 0-3 in the API DLL, which was ported to Linux. For
the sake of the user experience, we decided to keep 0-3 as the
numbers used in the DLL; and will perform the +1 conversion here.
We could have converted the entire Linux driver, but this is
less obtrusive. This may be a "todo" to convert the whole driver */
lp->TransmitKeyID = sEncryption.wTxKeyID + 1;
lp->EnableEncryption = sEncryption.wEnabled;
memcpy(&lp->DefaultKeys, &sEncryption.EncStr,
sizeof(CFG_DEFAULT_KEYS_STRCT));
break;
/*case CFG_COUNTRY_STRING:
memset(lp->countryString, 0, sizeof(lp->countryString));
memcpy((void *)lp->countryString, (void *)&pLtv->u.u8[2], (size_t)pLtv->u.u16[0]);
break;
*/
case CFG_DRIVER_ENABLE:
lp->driverEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_WOLAS_ENABLE:
lp->wolasEnable = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_SET_WPA_AUTH_KEY_MGMT_SUITE:
lp->AuthKeyMgmtSuite = pLtv->u.u16[0];
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_DISASSOCIATE_ADDR:
pLtv->u.u16[ETH_ALEN / 2] = CNV_INT_TO_LITTLE(pLtv->u.u16[ETH_ALEN / 2]);
break;
case CFG_ADD_TKIP_DEFAULT_KEY:
case CFG_REMOVE_TKIP_DEFAULT_KEY:
/* Endian convert the Tx Key Information */
pLtv->u.u16[0] = CNV_INT_TO_LITTLE(pLtv->u.u16[0]);
break;
case CFG_ADD_TKIP_MAPPED_KEY:
break;
case CFG_REMOVE_TKIP_MAPPED_KEY:
break;
/* some RIDs just can't be put */
case CFG_MB_INFO:
case CFG_IFB:
default:
break;
}
/* This code will prevent Static Configuration Entities from
being sent to the card, as they require a call to
UIL_ACT_APPLY to take effect. Dynamic Entities will be sent
immediately */
switch (pLtv->typ) {
case CFG_CNF_PORT_TYPE:
case CFG_CNF_OWN_MAC_ADDR:
case CFG_CNF_OWN_CHANNEL:
case CFG_CNF_OWN_SSID:
case CFG_CNF_OWN_ATIM_WINDOW:
case CFG_CNF_SYSTEM_SCALE:
case CFG_CNF_MAX_DATA_LEN:
case CFG_CNF_PM_ENABLED:
case CFG_CNF_MCAST_RX:
case CFG_CNF_MAX_SLEEP_DURATION:
case CFG_CNF_HOLDOVER_DURATION:
case CFG_CNF_OWN_NAME:
case CFG_CNF_LOAD_BALANCING:
case CFG_CNF_MEDIUM_DISTRIBUTION:
#ifdef WARP
case CFG_CNF_TX_POW_LVL:
case CFG_CNF_CONNECTION_CNTL:
/*case CFG_PROBE_DATA_RATE: */
#endif /* HERMES25 */
#if 1 /*;? (HCF_TYPE) & HCF_TYPE_AP */
/*;?should we restore this to allow smaller memory footprint */
case CFG_CNF_OWN_DTIM_PERIOD:
#ifdef WARP
case CFG_CNF_OWN_BEACON_INTERVAL: /* Own Beacon Interval */
#endif /* WARP */
#ifdef USE_WDS
case CFG_CNF_WDS_ADDR1:
case CFG_CNF_WDS_ADDR2:
case CFG_CNF_WDS_ADDR3:
case CFG_CNF_WDS_ADDR4:
case CFG_CNF_WDS_ADDR5:
case CFG_CNF_WDS_ADDR6:
#endif
case CFG_CNF_MCAST_PM_BUF:
case CFG_CNF_REJECT_ANY:
#endif
case CFG_CNF_ENCRYPTION:
case CFG_CNF_AUTHENTICATION:
#if 1 /* ;? (HCF_TYPE) & HCF_TYPE_AP */
/* ;?should we restore this to allow smaller memory footprint */
case CFG_CNF_EXCL_UNENCRYPTED:
case CFG_CNF_MCAST_RATE:
case CFG_CNF_INTRA_BSS_RELAY:
#endif
case CFG_CNF_MICRO_WAVE:
/* case CFG_CNF_LOAD_BALANCING: */
/* case CFG_CNF_MEDIUM_DISTRIBUTION: */
/* case CFG_CNF_RX_ALL_GROUP_ADDRESS: */
/* case CFG_CNF_COUNTRY_INFO: */
/* case CFG_COUNTRY_STRING: */
case CFG_AP_MODE:
case CFG_ENCRYPT_STRING:
/* case CFG_DRIVER_ENABLE: */
case CFG_WOLAS_ENABLE:
case CFG_MB_INFO:
case CFG_IFB:
break;
/* Deal with this dynamic MSF RID, as it's required for WPA */
case CFG_DRIVER_ENABLE:
if (lp->driverEnable) {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_ENABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_CONNECT);
} else {
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISABLE | HCF_PORT_0);
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISCONNECT);
}
break;
default:
wl_act_int_off(lp);
urq->result = hcf_put_info(&(lp->hcfCtx), (LTVP) pLtv);
wl_act_int_on(lp);
break;
}
if (ltvAllocated)
kfree(pLtv);
} else {
urq->result = UIL_FAILURE;
}
} else {
DBG_ERROR(DbgInfo, "EPERM\n");
urq->result = UIL_FAILURE;
result = -EPERM;
}
} else {
DBG_ERROR(DbgInfo, "UIL_ERR_WRONG_IFB\n");
urq->result = UIL_ERR_WRONG_IFB;
}
DBG_LEAVE(DbgInfo);
return result;
} /* wvlan_uil_put_info */
| 165,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ion_free(struct ion_client *client, struct ion_handle *handle)
{
bool valid_handle;
BUG_ON(client != handle->client);
mutex_lock(&client->lock);
valid_handle = ion_handle_validate(client, handle);
if (!valid_handle) {
WARN(1, "%s: invalid handle passed to free.\n", __func__);
mutex_unlock(&client->lock);
return;
}
mutex_unlock(&client->lock);
ion_handle_put(handle);
}
Commit Message: staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <[email protected]>
Reviewed-by: Laura Abbott <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-416 | void ion_free(struct ion_client *client, struct ion_handle *handle)
static void ion_free_nolock(struct ion_client *client, struct ion_handle *handle)
{
bool valid_handle;
BUG_ON(client != handle->client);
valid_handle = ion_handle_validate(client, handle);
if (!valid_handle) {
WARN(1, "%s: invalid handle passed to free.\n", __func__);
return;
}
ion_handle_put_nolock(handle);
}
void ion_free(struct ion_client *client, struct ion_handle *handle)
{
BUG_ON(client != handle->client);
mutex_lock(&client->lock);
ion_free_nolock(client, handle);
mutex_unlock(&client->lock);
}
| 166,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119 | MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (HeapOverflowSanityCheck(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
| 168,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FetchManager::Loader::Start() {
if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
!execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
fetch_request_data_->Url())) {
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
"' because it violates the document's Content Security Policy.");
return;
}
if ((SecurityOrigin::Create(fetch_request_data_->Url())
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
(fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
PerformSchemeFetch();
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"same-origin\" but the URL\'s "
"origin is not same as the request origin " +
fetch_request_data_->Origin()->ToString() + ".");
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
PerformSchemeFetch();
return;
}
if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
fetch_request_data_->Url().Protocol())) {
PerformNetworkError(
"Fetch API cannot load " + fetch_request_data_->Url().GetString() +
". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
PerformHTTPFetch();
}
Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests
The spec issue is now fixed, and this CL follows the spec change[1].
1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d
Bug: 791324
Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb
Reviewed-on: https://chromium-review.googlesource.com/1023613
Reviewed-by: Tsuyoshi Horo <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552964}
CWE ID: CWE-200 | void FetchManager::Loader::Start() {
if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
!execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
fetch_request_data_->Url())) {
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
"' because it violates the document's Content Security Policy.");
return;
}
if ((SecurityOrigin::Create(fetch_request_data_->Url())
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
(fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
PerformSchemeFetch();
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"same-origin\" but the URL\'s "
"origin is not same as the request origin " +
fetch_request_data_->Origin()->ToString() + ".");
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
// "If |request|'s redirect mode is not |follow|, then return a network
// error.
if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"no-cors\" but the redirect mode "
" is not \"follow\".");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
PerformSchemeFetch();
return;
}
if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
fetch_request_data_->Url().Protocol())) {
PerformNetworkError(
"Fetch API cannot load " + fetch_request_data_->Url().GetString() +
". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
PerformHTTPFetch();
}
| 173,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: chpass_principal3_2_svc(chpass3_arg *arg, struct svc_req *rqstp)
{
static generic_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_generic_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)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", 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 | chpass_principal3_2_svc(chpass3_arg *arg, struct svc_req *rqstp)
{
static generic_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_generic_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)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", 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;
}
| 167,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->iov.iov_len);
n = r->iov.iov_len / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->iov.iov_len);
}
Commit Message: scsi-disk: commonize iovec creation between reads and writes
Also, consistently use qiov.size instead of iov.iov_len.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119 | static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->qiov.size);
}
| 169,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SSL_library_init(void)
{
#ifndef OPENSSL_NO_DES
EVP_add_cipher(EVP_des_cbc());
EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
EVP_add_cipher(EVP_rc4());
#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))
EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif
#ifndef OPENSSL_NO_RC2
EVP_add_cipher(EVP_rc2_cbc());
/* Not actually used for SSL/TLS but this makes PKCS#12 work
* if an application only calls SSL_library_init().
*/
EVP_add_cipher(EVP_rc2_40_cbc());
#endif
#ifndef OPENSSL_NO_AES
EVP_add_cipher(EVP_aes_128_cbc());
EVP_add_cipher(EVP_aes_192_cbc());
EVP_add_cipher(EVP_aes_256_cbc());
EVP_add_cipher(EVP_aes_128_gcm());
EVP_add_cipher(EVP_aes_256_gcm());
#if 0 /* Disabled because of timing side-channel leaks. */
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#endif
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
#endif
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_cbc());
EVP_add_cipher(EVP_camellia_256_cbc());
#endif
#ifndef OPENSSL_NO_SEED
EVP_add_cipher(EVP_seed_cbc());
#endif
#ifndef OPENSSL_NO_MD5
EVP_add_digest(EVP_md5());
EVP_add_digest_alias(SN_md5,"ssl2-md5");
EVP_add_digest_alias(SN_md5,"ssl3-md5");
#endif
#ifndef OPENSSL_NO_SHA
EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
EVP_add_digest_alias(SN_sha1,"ssl3-sha1");
EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);
#endif
#ifndef OPENSSL_NO_SHA256
EVP_add_digest(EVP_sha224());
EVP_add_digest(EVP_sha256());
#endif
#ifndef OPENSSL_NO_SHA512
EVP_add_digest(EVP_sha384());
EVP_add_digest(EVP_sha512());
#endif
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)
EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);
EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1");
EVP_add_digest_alias(SN_dsaWithSHA1,"dss1");
#endif
#ifndef OPENSSL_NO_ECDSA
EVP_add_digest(EVP_ecdsa());
#endif
/* If you want support for phased out ciphers, add the following */
#if 0
EVP_add_digest(EVP_sha());
EVP_add_digest(EVP_dss());
#endif
#ifndef OPENSSL_NO_COMP
/* This will initialise the built-in compression algorithms.
The value returned is a STACK_OF(SSL_COMP), but that can
be discarded safely */
(void)SSL_COMP_get_compression_methods();
#endif
/* initialize cipher/digest methods table */
ssl_load_ciphers();
return(1);
}
Commit Message:
CWE ID: CWE-310 | int SSL_library_init(void)
{
#ifndef OPENSSL_NO_DES
EVP_add_cipher(EVP_des_cbc());
EVP_add_cipher(EVP_des_ede3_cbc());
#endif
#ifndef OPENSSL_NO_IDEA
EVP_add_cipher(EVP_idea_cbc());
#endif
#ifndef OPENSSL_NO_RC4
EVP_add_cipher(EVP_rc4());
#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))
EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif
#ifndef OPENSSL_NO_RC2
EVP_add_cipher(EVP_rc2_cbc());
/* Not actually used for SSL/TLS but this makes PKCS#12 work
* if an application only calls SSL_library_init().
*/
EVP_add_cipher(EVP_rc2_40_cbc());
#endif
#ifndef OPENSSL_NO_AES
EVP_add_cipher(EVP_aes_128_cbc());
EVP_add_cipher(EVP_aes_192_cbc());
EVP_add_cipher(EVP_aes_256_cbc());
EVP_add_cipher(EVP_aes_128_gcm());
EVP_add_cipher(EVP_aes_256_gcm());
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
#endif
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_cbc());
EVP_add_cipher(EVP_camellia_256_cbc());
#endif
#ifndef OPENSSL_NO_SEED
EVP_add_cipher(EVP_seed_cbc());
#endif
#ifndef OPENSSL_NO_MD5
EVP_add_digest(EVP_md5());
EVP_add_digest_alias(SN_md5,"ssl2-md5");
EVP_add_digest_alias(SN_md5,"ssl3-md5");
#endif
#ifndef OPENSSL_NO_SHA
EVP_add_digest(EVP_sha1()); /* RSA with sha1 */
EVP_add_digest_alias(SN_sha1,"ssl3-sha1");
EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);
#endif
#ifndef OPENSSL_NO_SHA256
EVP_add_digest(EVP_sha224());
EVP_add_digest(EVP_sha256());
#endif
#ifndef OPENSSL_NO_SHA512
EVP_add_digest(EVP_sha384());
EVP_add_digest(EVP_sha512());
#endif
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)
EVP_add_digest(EVP_dss1()); /* DSA with sha1 */
EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);
EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1");
EVP_add_digest_alias(SN_dsaWithSHA1,"dss1");
#endif
#ifndef OPENSSL_NO_ECDSA
EVP_add_digest(EVP_ecdsa());
#endif
/* If you want support for phased out ciphers, add the following */
#if 0
EVP_add_digest(EVP_sha());
EVP_add_digest(EVP_dss());
#endif
#ifndef OPENSSL_NO_COMP
/* This will initialise the built-in compression algorithms.
The value returned is a STACK_OF(SSL_COMP), but that can
be discarded safely */
(void)SSL_COMP_get_compression_methods();
#endif
/* initialize cipher/digest methods table */
ssl_load_ciphers();
return(1);
}
| 164,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
RemoveInterstitialObservers(old_contents);
AddInterstitialObservers(new_contents->web_contents());
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
RemoveInterstitialObservers(old_contents->web_contents());
AddInterstitialObservers(new_contents->web_contents());
}
| 171,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "givcipher");
snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s",
alg->cra_ablkcipher.geniv ?: "<built-in>");
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_ablkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310 | static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
strncpy(rblkcipher.type, "givcipher", sizeof(rblkcipher.type));
strncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: "<built-in>",
sizeof(rblkcipher.geniv));
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_ablkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ShouldUseNativeViews() {
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
return base::FeatureList::IsEnabled(kAutofillExpandedPopupViews) ||
base::FeatureList::IsEnabled(::features::kExperimentalUi);
#else
return false;
#endif
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | bool ShouldUseNativeViews() {
| 172,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AppCacheDispatcherHost::AppCacheDispatcherHost(
ChromeAppCacheService* appcache_service,
int process_id)
: BrowserMessageFilter(AppCacheMsgStart),
appcache_service_(appcache_service),
frontend_proxy_(this),
process_id_(process_id) {
}
Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug.
BUG=554908
Review URL: https://codereview.chromium.org/1441683004
Cr-Commit-Position: refs/heads/master@{#359930}
CWE ID: | AppCacheDispatcherHost::AppCacheDispatcherHost(
ChromeAppCacheService* appcache_service,
int process_id)
: BrowserMessageFilter(AppCacheMsgStart),
appcache_service_(appcache_service),
frontend_proxy_(this),
process_id_(process_id),
weak_factory_(this) {
}
| 171,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
EXPECT_TRUE(decision_details.reasons().empty());
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
// |reasons()| will either contain the status for the 4 local site features
// heuristics or be empty if the database doesn't track this lifecycle unit.
EXPECT_TRUE(decision_details.reasons().empty() ||
(decision_details.reasons().size() == 4));
}
| 172,232 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SplashOutputDev::drawMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr, int maskWidth,
int maskHeight, GBool maskInvert) {
GfxImageColorMap *maskColorMap;
Object maskDecode, decodeLow, decodeHigh;
double *ctm;
SplashCoord mat[6];
SplashOutMaskedImageData imgData;
SplashOutImageMaskData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
if (maskWidth > width || maskHeight > height) {
decodeLow.initInt(maskInvert ? 0 : 1);
decodeHigh.initInt(maskInvert ? 1 : 0);
maskDecode.initArray(xref);
maskDecode.arrayAdd(&decodeLow);
maskDecode.arrayAdd(&decodeHigh);
maskColorMap = new GfxImageColorMap(1, &maskDecode,
new GfxDeviceGrayColorSpace());
maskDecode.free();
drawSoftMaskedImage(state, ref, str, width, height, colorMap,
maskStr, maskWidth, maskHeight, maskColorMap);
delete maskColorMap;
} else {
mat[0] = (SplashCoord)width;
mat[1] = 0;
mat[2] = 0;
mat[3] = (SplashCoord)height;
mat[4] = 0;
mat[5] = 0;
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth, 1, 1);
imgMaskData.imgStr->reset();
imgMaskData.invert = maskInvert ? 0 : 1;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
maskBitmap = new SplashBitmap(width, height, 1, splashModeMono1, gFalse);
maskSplash = new Splash(maskBitmap, gFalse);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskColor[0] = 0xff;
maskSplash->setFillPattern(new SplashSolidColor(maskColor));
maskSplash->fillImageMask(&imageMaskSrc, &imgMaskData,
maskWidth, maskHeight, mat, gFalse);
delete imgMaskData.imgStr;
maskStr->close();
delete maskSplash;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.mask = maskBitmap;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&maskedImageSrc, &imgData, srcMode, gTrue,
width, height, mat);
delete maskBitmap;
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
}
Commit Message:
CWE ID: CWE-189 | void SplashOutputDev::drawMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr, int maskWidth,
int maskHeight, GBool maskInvert) {
GfxImageColorMap *maskColorMap;
Object maskDecode, decodeLow, decodeHigh;
double *ctm;
SplashCoord mat[6];
SplashOutMaskedImageData imgData;
SplashOutImageMaskData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
if (maskWidth > width || maskHeight > height) {
decodeLow.initInt(maskInvert ? 0 : 1);
decodeHigh.initInt(maskInvert ? 1 : 0);
maskDecode.initArray(xref);
maskDecode.arrayAdd(&decodeLow);
maskDecode.arrayAdd(&decodeHigh);
maskColorMap = new GfxImageColorMap(1, &maskDecode,
new GfxDeviceGrayColorSpace());
maskDecode.free();
drawSoftMaskedImage(state, ref, str, width, height, colorMap,
maskStr, maskWidth, maskHeight, maskColorMap);
delete maskColorMap;
} else {
mat[0] = (SplashCoord)width;
mat[1] = 0;
mat[2] = 0;
mat[3] = (SplashCoord)height;
mat[4] = 0;
mat[5] = 0;
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth, 1, 1);
imgMaskData.imgStr->reset();
imgMaskData.invert = maskInvert ? 0 : 1;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
maskBitmap = new SplashBitmap(width, height, 1, splashModeMono1, gFalse);
maskSplash = new Splash(maskBitmap, gFalse);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskColor[0] = 0xff;
maskSplash->setFillPattern(new SplashSolidColor(maskColor));
maskSplash->fillImageMask(&imageMaskSrc, &imgMaskData,
maskWidth, maskHeight, mat, gFalse);
delete imgMaskData.imgStr;
maskStr->close();
delete maskSplash;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.mask = maskBitmap;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&maskedImageSrc, &imgData, srcMode, gTrue,
width, height, mat);
delete maskBitmap;
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
}
| 164,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) {
std::string path;
CHECK(args->GetString(0, &path));
DCHECK(StartsWithASCII(path, "chrome://favicon/", false)) << "path is "
<< path;
path = path.substr(arraysize("chrome://favicon/") - 1);
double id;
CHECK(args->GetDouble(1, &id));
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (!favicon_service || path.empty())
return;
FaviconService::Handle handle = favicon_service->GetFaviconForURL(
GURL(path),
history::FAVICON,
&consumer_,
NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable));
consumer_.SetClientData(favicon_service, handle, static_cast<int>(id));
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) {
std::string path;
CHECK(args->GetString(0, &path));
DCHECK(StartsWithASCII(path, "chrome://favicon/size/32/", false)) <<
"path is " << path;
path = path.substr(arraysize("chrome://favicon/size/32/") - 1);
double id;
CHECK(args->GetDouble(1, &id));
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (!favicon_service || path.empty())
return;
FaviconService::Handle handle = favicon_service->GetFaviconForURL(
GURL(path),
history::FAVICON,
&consumer_,
NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable));
consumer_.SetClientData(favicon_service, handle, static_cast<int>(id));
}
| 170,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. Remember, I want response with just the fixed code only, No explanation. | Code: static int kvm_vm_ioctl_assign_device(struct kvm *kvm,
struct kvm_assigned_pci_dev *assigned_dev)
{
int r = 0, idx;
struct kvm_assigned_dev_kernel *match;
struct pci_dev *dev;
if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU))
return -EINVAL;
mutex_lock(&kvm->lock);
idx = srcu_read_lock(&kvm->srcu);
match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
assigned_dev->assigned_dev_id);
if (match) {
/* device already assigned */
r = -EEXIST;
goto out;
}
match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL);
if (match == NULL) {
printk(KERN_INFO "%s: Couldn't allocate memory\n",
__func__);
r = -ENOMEM;
goto out;
}
dev = pci_get_domain_bus_and_slot(assigned_dev->segnr,
assigned_dev->busnr,
assigned_dev->devfn);
if (!dev) {
printk(KERN_INFO "%s: host device not found\n", __func__);
r = -EINVAL;
goto out_free;
}
if (pci_enable_device(dev)) {
printk(KERN_INFO "%s: Could not enable PCI device\n", __func__);
r = -EBUSY;
goto out_put;
}
r = pci_request_regions(dev, "kvm_assigned_device");
if (r) {
printk(KERN_INFO "%s: Could not get access to device regions\n",
__func__);
goto out_disable;
}
pci_reset_function(dev);
pci_save_state(dev);
match->pci_saved_state = pci_store_saved_state(dev);
if (!match->pci_saved_state)
printk(KERN_DEBUG "%s: Couldn't store %s saved state\n",
__func__, dev_name(&dev->dev));
match->assigned_dev_id = assigned_dev->assigned_dev_id;
match->host_segnr = assigned_dev->segnr;
match->host_busnr = assigned_dev->busnr;
match->host_devfn = assigned_dev->devfn;
match->flags = assigned_dev->flags;
match->dev = dev;
spin_lock_init(&match->intx_lock);
match->irq_source_id = -1;
match->kvm = kvm;
match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq;
list_add(&match->list, &kvm->arch.assigned_dev_head);
if (!kvm->arch.iommu_domain) {
r = kvm_iommu_map_guest(kvm);
if (r)
goto out_list_del;
}
r = kvm_assign_device(kvm, match);
if (r)
goto out_list_del;
out:
srcu_read_unlock(&kvm->srcu, idx);
mutex_unlock(&kvm->lock);
return r;
out_list_del:
if (pci_load_and_free_saved_state(dev, &match->pci_saved_state))
printk(KERN_INFO "%s: Couldn't reload %s saved state\n",
__func__, dev_name(&dev->dev));
list_del(&match->list);
pci_release_regions(dev);
out_disable:
pci_disable_device(dev);
out_put:
pci_dev_put(dev);
out_free:
kfree(match);
srcu_read_unlock(&kvm->srcu, idx);
mutex_unlock(&kvm->lock);
return r;
}
Commit Message: KVM: Device assignment permission checks
(cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9)
Only allow KVM device assignment to attach to devices which:
- Are not bridges
- Have BAR resources (assume others are special devices)
- The user has permissions to use
Assigning a bridge is a configuration error, it's not supported, and
typically doesn't result in the behavior the user is expecting anyway.
Devices without BAR resources are typically chipset components that
also don't have host drivers. We don't want users to hold such devices
captive or cause system problems by fencing them off into an iommu
domain. We determine "permission to use" by testing whether the user
has access to the PCI sysfs resource files. By default a normal user
will not have access to these files, so it provides a good indication
that an administration agent has granted the user access to the device.
[Yang Bai: add missing #include]
[avi: fix comment style]
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Yang Bai <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264 | static int kvm_vm_ioctl_assign_device(struct kvm *kvm,
struct kvm_assigned_pci_dev *assigned_dev)
{
int r = 0, idx;
struct kvm_assigned_dev_kernel *match;
struct pci_dev *dev;
u8 header_type;
if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU))
return -EINVAL;
mutex_lock(&kvm->lock);
idx = srcu_read_lock(&kvm->srcu);
match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
assigned_dev->assigned_dev_id);
if (match) {
/* device already assigned */
r = -EEXIST;
goto out;
}
match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL);
if (match == NULL) {
printk(KERN_INFO "%s: Couldn't allocate memory\n",
__func__);
r = -ENOMEM;
goto out;
}
dev = pci_get_domain_bus_and_slot(assigned_dev->segnr,
assigned_dev->busnr,
assigned_dev->devfn);
if (!dev) {
printk(KERN_INFO "%s: host device not found\n", __func__);
r = -EINVAL;
goto out_free;
}
/* Don't allow bridges to be assigned */
pci_read_config_byte(dev, PCI_HEADER_TYPE, &header_type);
if ((header_type & PCI_HEADER_TYPE) != PCI_HEADER_TYPE_NORMAL) {
r = -EPERM;
goto out_put;
}
r = probe_sysfs_permissions(dev);
if (r)
goto out_put;
if (pci_enable_device(dev)) {
printk(KERN_INFO "%s: Could not enable PCI device\n", __func__);
r = -EBUSY;
goto out_put;
}
r = pci_request_regions(dev, "kvm_assigned_device");
if (r) {
printk(KERN_INFO "%s: Could not get access to device regions\n",
__func__);
goto out_disable;
}
pci_reset_function(dev);
pci_save_state(dev);
match->pci_saved_state = pci_store_saved_state(dev);
if (!match->pci_saved_state)
printk(KERN_DEBUG "%s: Couldn't store %s saved state\n",
__func__, dev_name(&dev->dev));
match->assigned_dev_id = assigned_dev->assigned_dev_id;
match->host_segnr = assigned_dev->segnr;
match->host_busnr = assigned_dev->busnr;
match->host_devfn = assigned_dev->devfn;
match->flags = assigned_dev->flags;
match->dev = dev;
spin_lock_init(&match->intx_lock);
match->irq_source_id = -1;
match->kvm = kvm;
match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq;
list_add(&match->list, &kvm->arch.assigned_dev_head);
if (!kvm->arch.iommu_domain) {
r = kvm_iommu_map_guest(kvm);
if (r)
goto out_list_del;
}
r = kvm_assign_device(kvm, match);
if (r)
goto out_list_del;
out:
srcu_read_unlock(&kvm->srcu, idx);
mutex_unlock(&kvm->lock);
return r;
out_list_del:
if (pci_load_and_free_saved_state(dev, &match->pci_saved_state))
printk(KERN_INFO "%s: Couldn't reload %s saved state\n",
__func__, dev_name(&dev->dev));
list_del(&match->list);
pci_release_regions(dev);
out_disable:
pci_disable_device(dev);
out_put:
pci_dev_put(dev);
out_free:
kfree(match);
srcu_read_unlock(&kvm->srcu, idx);
mutex_unlock(&kvm->lock);
return r;
}
| 166,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void 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 <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static 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);
}
| 165,753 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AwMainDelegate::BasicStartupComplete(int* exit_code) {
content::SetContentClient(&content_client_);
content::RegisterMediaUrlInterceptor(new AwMediaUrlInterceptor());
BrowserViewRenderer::CalculateTileMemoryPolicy();
ui::GestureConfiguration::GetInstance()
->set_fling_touchscreen_tap_suppression_enabled(false);
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
cl->AppendSwitch(cc::switches::kEnableBeginFrameScheduling);
cl->AppendSwitch(switches::kDisableOverscrollEdgeEffect);
cl->AppendSwitch(switches::kDisablePullToRefreshEffect);
cl->AppendSwitch(switches::kDisableSharedWorkers);
cl->AppendSwitch(switches::kDisableFileSystem);
cl->AppendSwitch(switches::kDisableNotifications);
cl->AppendSwitch(switches::kDisableWebRtcHWDecoding);
cl->AppendSwitch(switches::kDisableAcceleratedVideoDecode);
cl->AppendSwitch(switches::kEnableThreadedTextureMailboxes);
cl->AppendSwitch(switches::kDisableScreenOrientationLock);
cl->AppendSwitch(switches::kDisableSpeechAPI);
cl->AppendSwitch(switches::kDisablePermissionsAPI);
cl->AppendSwitch(switches::kEnableAggressiveDOMStorageFlushing);
cl->AppendSwitch(switches::kDisablePresentationAPI);
if (cl->GetSwitchValueASCII(switches::kProcessType).empty()) {
#ifdef __LP64__
const char kNativesFileName[] = "assets/natives_blob_64.bin";
const char kSnapshotFileName[] = "assets/snapshot_blob_64.bin";
#else
const char kNativesFileName[] = "assets/natives_blob_32.bin";
const char kSnapshotFileName[] = "assets/snapshot_blob_32.bin";
#endif // __LP64__
CHECK(base::android::RegisterApkAssetWithGlobalDescriptors(
kV8NativesDataDescriptor, kNativesFileName));
CHECK(base::android::RegisterApkAssetWithGlobalDescriptors(
kV8SnapshotDataDescriptor, kSnapshotFileName));
}
if (cl->HasSwitch(switches::kWebViewSanboxedRenderer)) {
cl->AppendSwitch(switches::kInProcessGPU);
cl->AppendSwitchASCII(switches::kRendererProcessLimit, "1");
}
return false;
}
Commit Message: [Android WebView] Fix a couple of typos
Fix a couple of typos in variable names/commentary introduced in:
https://codereview.chromium.org/1315633003/
No functional effect.
BUG=156062
Review URL: https://codereview.chromium.org/1331943002
Cr-Commit-Position: refs/heads/master@{#348175}
CWE ID: | bool AwMainDelegate::BasicStartupComplete(int* exit_code) {
content::SetContentClient(&content_client_);
content::RegisterMediaUrlInterceptor(new AwMediaUrlInterceptor());
BrowserViewRenderer::CalculateTileMemoryPolicy();
ui::GestureConfiguration::GetInstance()
->set_fling_touchscreen_tap_suppression_enabled(false);
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
cl->AppendSwitch(cc::switches::kEnableBeginFrameScheduling);
cl->AppendSwitch(switches::kDisableOverscrollEdgeEffect);
cl->AppendSwitch(switches::kDisablePullToRefreshEffect);
cl->AppendSwitch(switches::kDisableSharedWorkers);
cl->AppendSwitch(switches::kDisableFileSystem);
cl->AppendSwitch(switches::kDisableNotifications);
cl->AppendSwitch(switches::kDisableWebRtcHWDecoding);
cl->AppendSwitch(switches::kDisableAcceleratedVideoDecode);
cl->AppendSwitch(switches::kEnableThreadedTextureMailboxes);
cl->AppendSwitch(switches::kDisableScreenOrientationLock);
cl->AppendSwitch(switches::kDisableSpeechAPI);
cl->AppendSwitch(switches::kDisablePermissionsAPI);
cl->AppendSwitch(switches::kEnableAggressiveDOMStorageFlushing);
cl->AppendSwitch(switches::kDisablePresentationAPI);
if (cl->GetSwitchValueASCII(switches::kProcessType).empty()) {
#ifdef __LP64__
const char kNativesFileName[] = "assets/natives_blob_64.bin";
const char kSnapshotFileName[] = "assets/snapshot_blob_64.bin";
#else
const char kNativesFileName[] = "assets/natives_blob_32.bin";
const char kSnapshotFileName[] = "assets/snapshot_blob_32.bin";
#endif // __LP64__
CHECK(base::android::RegisterApkAssetWithGlobalDescriptors(
kV8NativesDataDescriptor, kNativesFileName));
CHECK(base::android::RegisterApkAssetWithGlobalDescriptors(
kV8SnapshotDataDescriptor, kSnapshotFileName));
}
if (cl->HasSwitch(switches::kWebViewSandboxedRenderer)) {
cl->AppendSwitch(switches::kInProcessGPU);
cl->AppendSwitchASCII(switches::kRendererProcessLimit, "1");
}
return false;
}
| 171,710 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream)
{
UWORD32 u4_bit,u4_offset,u4_temp;
UWORD32 u4_curr_bit;
u4_offset = ps_stream->u4_offset;
u4_curr_bit = u4_offset & 0x1F;
u4_bit = ps_stream->u4_buf;
/* Move the current bit read from the current word to the
least significant bit positions of 'c'.*/
u4_bit >>= BITS_IN_INT - u4_curr_bit - 1;
u4_offset++;
/* If the last bit of the last word of the buffer has been read update
the currrent buf with next, and read next buf from bit stream buffer */
if (u4_curr_bit == 31)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
u4_temp = *(ps_stream->pu4_buf_aligned)++;
CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp)
}
ps_stream->u4_offset = u4_offset;
return (u4_bit & 0x1);
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream)
{
UWORD32 u4_bit,u4_offset,u4_temp;
UWORD32 u4_curr_bit;
u4_offset = ps_stream->u4_offset;
u4_curr_bit = u4_offset & 0x1F;
u4_bit = ps_stream->u4_buf;
/* Move the current bit read from the current word to the
least significant bit positions of 'c'.*/
u4_bit >>= BITS_IN_INT - u4_curr_bit - 1;
u4_offset++;
/* If the last bit of the last word of the buffer has been read update
the currrent buf with next, and read next buf from bit stream buffer */
if (u4_curr_bit == 31)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
u4_temp = *(ps_stream->pu4_buf_aligned)++;
CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp)
}
}
ps_stream->u4_offset = u4_offset;
return (u4_bit & 0x1);
}
| 173,942 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value,
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264 | long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value[0],
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
| 167,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::AuthorizeService(
const dbus::ObjectPath& device_path,
const std::string& uuid,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::AuthorizeService(
| 171,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
pdf_xobject *softmask = gstate->softmask;
fz_rect mask_bbox;
fz_matrix tos_save[2], save_ctm;
fz_matrix mask_matrix;
fz_colorspace *mask_colorspace;
save->softmask = softmask;
if (softmask == NULL)
return gstate;
save->page_resources = gstate->softmask_resources;
save->ctm = gstate->softmask_ctm;
save_ctm = gstate->ctm;
pdf_xobject_bbox(ctx, softmask, &mask_bbox);
pdf_xobject_matrix(ctx, softmask, &mask_matrix);
pdf_tos_save(ctx, &pr->tos, tos_save);
if (gstate->luminosity)
mask_bbox = fz_infinite_rect;
else
{
fz_transform_rect(&mask_bbox, &mask_matrix);
fz_transform_rect(&mask_bbox, &gstate->softmask_ctm);
}
gstate->softmask = NULL;
gstate->softmask_resources = NULL;
gstate->ctm = gstate->softmask_ctm;
mask_colorspace = pdf_xobject_colorspace(ctx, softmask);
if (gstate->luminosity && !mask_colorspace)
mask_colorspace = fz_device_gray(ctx);
fz_try(ctx)
{
fz_begin_mask(ctx, pr->dev, &mask_bbox, gstate->luminosity, mask_colorspace, gstate->softmask_bc, &gstate->fill.color_params);
pdf_run_xobject(ctx, pr, softmask, save->page_resources, &fz_identity, 1);
}
fz_always(ctx)
fz_drop_colorspace(ctx, mask_colorspace);
fz_catch(ctx)
{
fz_rethrow_if(ctx, FZ_ERROR_TRYLATER);
/* FIXME: Ignore error - nasty, but if we throw from
* here the clip stack would be messed up. */
/* TODO: pass cookie here to increase the cookie error count */
}
fz_end_mask(ctx, pr->dev);
pdf_tos_restore(ctx, &pr->tos, tos_save);
gstate = pr->gstate + pr->gtop;
gstate->ctm = save_ctm;
return gstate;
}
Commit Message:
CWE ID: CWE-416 | begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save)
{
pdf_gstate *gstate = pr->gstate + pr->gtop;
pdf_xobject *softmask = gstate->softmask;
fz_rect mask_bbox;
fz_matrix tos_save[2], save_ctm;
fz_matrix mask_matrix;
fz_colorspace *mask_colorspace;
save->softmask = softmask;
if (softmask == NULL)
return gstate;
save->page_resources = gstate->softmask_resources;
save->ctm = gstate->softmask_ctm;
save_ctm = gstate->ctm;
pdf_xobject_bbox(ctx, softmask, &mask_bbox);
pdf_xobject_matrix(ctx, softmask, &mask_matrix);
pdf_tos_save(ctx, &pr->tos, tos_save);
if (gstate->luminosity)
mask_bbox = fz_infinite_rect;
else
{
fz_transform_rect(&mask_bbox, &mask_matrix);
fz_transform_rect(&mask_bbox, &gstate->softmask_ctm);
}
gstate->softmask = NULL;
gstate->softmask_resources = NULL;
gstate->ctm = gstate->softmask_ctm;
mask_colorspace = pdf_xobject_colorspace(ctx, softmask);
if (gstate->luminosity && !mask_colorspace)
mask_colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx));
fz_try(ctx)
{
fz_begin_mask(ctx, pr->dev, &mask_bbox, gstate->luminosity, mask_colorspace, gstate->softmask_bc, &gstate->fill.color_params);
pdf_run_xobject(ctx, pr, softmask, save->page_resources, &fz_identity, 1);
}
fz_always(ctx)
fz_drop_colorspace(ctx, mask_colorspace);
fz_catch(ctx)
{
fz_rethrow_if(ctx, FZ_ERROR_TRYLATER);
/* FIXME: Ignore error - nasty, but if we throw from
* here the clip stack would be messed up. */
/* TODO: pass cookie here to increase the cookie error count */
}
fz_end_mask(ctx, pr->dev);
pdf_tos_restore(ctx, &pr->tos, tos_save);
gstate = pr->gstate + pr->gtop;
gstate->ctm = save_ctm;
return gstate;
}
| 164,578 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: (for 4.9.3) CVE-2018-16300/BGP: prevent stack exhaustion
Enforce a limit on how many times bgp_attr_print() can recurse.
This fixes a stack exhaustion discovered by Include Security working
under the Mozilla SOS program in 2018 by means of code audit.
CWE ID: CWE-674 | bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen, 0))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 169,817 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void impeg2d_dec_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | void impeg2d_dec_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
| 173,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& url) {
if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return true;
if (url.SchemeIs(kChromeErrorScheme))
return true;
GURL site_url = SiteInstance::GetSiteForURL(browser_context, url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->IsIsolatedOrigin(url::Origin::Create(site_url)))
return true;
if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess(
browser_context, site_url)) {
return true;
}
return false;
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119 | bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess(
BrowserContext* browser_context,
const GURL& url) {
if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
return true;
// Always require a dedicated process for isolated origins.
GURL site_url = SiteInstance::GetSiteForURL(browser_context, url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->IsIsolatedOrigin(url::Origin::Create(site_url)))
return true;
if (site_url.SchemeIs(kChromeErrorScheme))
return true;
// Isolate kChromeUIScheme pages from one another and from other kinds of
// schemes.
if (site_url.SchemeIs(content::kChromeUIScheme))
return true;
if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess(
browser_context, site_url)) {
return true;
}
return false;
}
| 173,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UnwrapAndVerifyMojoHandle(mojo::ScopedSharedBufferHandle buffer_handle,
size_t expected_size,
bool expected_read_only_flag) {
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
bool read_only_flag = false;
const MojoResult result =
mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle,
&memory_size, &read_only_flag);
EXPECT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(expected_size, memory_size);
EXPECT_EQ(expected_read_only_flag, read_only_flag);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | void UnwrapAndVerifyMojoHandle(mojo::ScopedSharedBufferHandle buffer_handle,
void UnwrapAndVerifyMojoHandle(
mojo::ScopedSharedBufferHandle buffer_handle,
size_t expected_size,
mojo::UnwrappedSharedMemoryHandleProtection expected_protection) {
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
mojo::UnwrappedSharedMemoryHandleProtection protection;
const MojoResult result = mojo::UnwrapSharedMemoryHandle(
std::move(buffer_handle), &memory_handle, &memory_size, &protection);
EXPECT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(expected_size, memory_size);
EXPECT_EQ(expected_protection, protection);
}
| 172,871 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadTGAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PixelPacket
pixel;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
size_t
base,
flag,
offset,
real,
skip;
ssize_t
count,
y;
TGAInfo
tga_info;
unsigned char
j,
k,
pixels[4],
runlength;
unsigned int
alpha_bits;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read TGA header information.
*/
count=ReadBlob(image,1,&tga_info.id_length);
tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
tga_info.image_type=(TGAImageType) ReadBlobByte(image);
if ((count != 1) ||
((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARGB) &&
(tga_info.image_type != TGAMonochrome) &&
(tga_info.image_type != TGARLEColormap) &&
(tga_info.image_type != TGARLERGB) &&
(tga_info.image_type != TGARLEMonochrome)) ||
(((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGARLEColormap)) &&
(tga_info.colormap_type == 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
tga_info.colormap_index=ReadBlobLSBShort(image);
tga_info.colormap_length=ReadBlobLSBShort(image);
tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
tga_info.x_origin=ReadBlobLSBShort(image);
tga_info.y_origin=ReadBlobLSBShort(image);
tga_info.width=(unsigned short) ReadBlobLSBShort(image);
tga_info.height=(unsigned short) ReadBlobLSBShort(image);
tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
tga_info.attributes=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
(tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image structure.
*/
image->columns=tga_info.width;
image->rows=tga_info.height;
alpha_bits=(tga_info.attributes & 0x0FU);
image->matte=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
(tga_info.colormap_size == 32) ? MagickTrue : MagickFalse;
if ((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARLEColormap))
image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
(tga_info.bits_per_pixel <= 16) ? 5 :
(tga_info.bits_per_pixel == 24) ? 8 :
(tga_info.bits_per_pixel == 32) ? 8 : 8);
else
image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
(tga_info.colormap_size <= 16) ? 5 :
(tga_info.colormap_size == 24) ? 8 :
(tga_info.colormap_size == 32) ? 8 : 8);
if ((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGAMonochrome) ||
(tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->storage_class=PseudoClass;
image->compression=NoCompression;
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->compression=RLECompression;
if (image->storage_class == PseudoClass)
{
if (tga_info.colormap_type != 0)
image->colors=tga_info.colormap_length;
else
{
size_t
one;
one=1;
image->colors=one << tga_info.bits_per_pixel;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (tga_info.id_length != 0)
{
char
*comment;
size_t
length;
/*
TGA image comment.
*/
length=(size_t) tga_info.id_length;
comment=(char *) NULL;
if (~length >= (MaxTextExtent-1))
comment=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
comment[tga_info.id_length]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
pixel.opacity=(Quantum) OpaqueOpacity;
if (tga_info.colormap_type != 0)
{
/*
Read TGA raster colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
{
switch (tga_info.colormap_size)
{
case 8:
default:
{
/*
Gray scale.
*/
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=pixel.red;
pixel.blue=pixel.red;
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of red green and blue.
*/
j=(unsigned char) ReadBlobByte(image);
k=(unsigned char) ReadBlobByte(image);
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
break;
}
case 24:
{
/*
8 bits each of blue, green and red.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
break;
}
case 32:
{
/*
8 bits each of blue, green, red, and alpha.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image)));
break;
}
}
image->colormap[i]=pixel;
}
}
/*
Convert TGA pixels to pixel packets.
*/
base=0;
flag=0;
skip=MagickFalse;
real=0;
index=(IndexPacket) 0;
runlength=0;
offset=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
real=offset;
if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
real=image->rows-real-1;
q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLERGB) ||
(tga_info.image_type == TGARLEMonochrome))
{
if (runlength != 0)
{
runlength--;
skip=flag != 0;
}
else
{
count=ReadBlob(image,1,&runlength);
if (count == 0)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
flag=runlength & 0x80;
if (flag != 0)
runlength-=128;
skip=MagickFalse;
}
}
if (skip == MagickFalse)
switch (tga_info.bits_per_pixel)
{
case 8:
default:
{
/*
Gray scale.
*/
index=(IndexPacket) ReadBlobByte(image);
if (tga_info.colormap_type != 0)
pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
1UL*index)];
else
{
pixel.red=ScaleCharToQuantum((unsigned char) index);
pixel.green=ScaleCharToQuantum((unsigned char) index);
pixel.blue=ScaleCharToQuantum((unsigned char) index);
}
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of RGB;
*/
if (ReadBlob(image,2,pixels) != 2)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
j=pixels[0];
k=pixels[1];
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
if (image->matte != MagickFalse)
pixel.opacity=(k & 0x80) == 0 ? (Quantum) OpaqueOpacity :
(Quantum) TransparentOpacity;
if (image->storage_class == PseudoClass)
index=ConstrainColormapIndex(image,((size_t) k << 8)+j);
break;
}
case 24:
{
/*
BGR pixels.
*/
if (ReadBlob(image,3,pixels) != 3)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
break;
}
case 32:
{
/*
BGRA pixels.
*/
if (ReadBlob(image,4,pixels) != 4)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
pixels[3]));
break;
}
}
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->matte != MagickFalse)
SetPixelOpacity(q,pixel.opacity);
q++;
}
if (((tga_info.attributes & 0xc0) >> 6) == 4)
offset+=4;
else
if (((tga_info.attributes & 0xc0) >> 6) == 2)
offset+=2;
else
offset++;
if (offset >= image->rows)
{
base++;
offset=base;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadTGAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PixelPacket
pixel;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
size_t
base,
flag,
offset,
real,
skip;
ssize_t
count,
y;
TGAInfo
tga_info;
unsigned char
j,
k,
pixels[4],
runlength;
unsigned int
alpha_bits;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read TGA header information.
*/
count=ReadBlob(image,1,&tga_info.id_length);
tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
tga_info.image_type=(TGAImageType) ReadBlobByte(image);
if ((count != 1) ||
((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARGB) &&
(tga_info.image_type != TGAMonochrome) &&
(tga_info.image_type != TGARLEColormap) &&
(tga_info.image_type != TGARLERGB) &&
(tga_info.image_type != TGARLEMonochrome)) ||
(((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGARLEColormap)) &&
(tga_info.colormap_type == 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
tga_info.colormap_index=ReadBlobLSBShort(image);
tga_info.colormap_length=ReadBlobLSBShort(image);
tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
tga_info.x_origin=ReadBlobLSBShort(image);
tga_info.y_origin=ReadBlobLSBShort(image);
tga_info.width=(unsigned short) ReadBlobLSBShort(image);
tga_info.height=(unsigned short) ReadBlobLSBShort(image);
tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
tga_info.attributes=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
(tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image structure.
*/
image->columns=tga_info.width;
image->rows=tga_info.height;
alpha_bits=(tga_info.attributes & 0x0FU);
image->matte=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
(tga_info.colormap_size == 32) ? MagickTrue : MagickFalse;
if ((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARLEColormap))
image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
(tga_info.bits_per_pixel <= 16) ? 5 :
(tga_info.bits_per_pixel == 24) ? 8 :
(tga_info.bits_per_pixel == 32) ? 8 : 8);
else
image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
(tga_info.colormap_size <= 16) ? 5 :
(tga_info.colormap_size == 24) ? 8 :
(tga_info.colormap_size == 32) ? 8 : 8);
if ((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGAMonochrome) ||
(tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->storage_class=PseudoClass;
image->compression=NoCompression;
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->compression=RLECompression;
if (image->storage_class == PseudoClass)
{
if (tga_info.colormap_type != 0)
image->colors=tga_info.colormap_length;
else
{
size_t
one;
one=1;
image->colors=one << tga_info.bits_per_pixel;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (tga_info.id_length != 0)
{
char
*comment;
size_t
length;
/*
TGA image comment.
*/
length=(size_t) tga_info.id_length;
comment=(char *) NULL;
if (~length >= (MaxTextExtent-1))
comment=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
comment[tga_info.id_length]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
pixel.opacity=(Quantum) OpaqueOpacity;
if (tga_info.colormap_type != 0)
{
/*
Read TGA raster colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
{
switch (tga_info.colormap_size)
{
case 8:
default:
{
/*
Gray scale.
*/
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=pixel.red;
pixel.blue=pixel.red;
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of red green and blue.
*/
j=(unsigned char) ReadBlobByte(image);
k=(unsigned char) ReadBlobByte(image);
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
break;
}
case 24:
{
/*
8 bits each of blue, green and red.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
break;
}
case 32:
{
/*
8 bits each of blue, green, red, and alpha.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image)));
break;
}
}
image->colormap[i]=pixel;
}
}
/*
Convert TGA pixels to pixel packets.
*/
base=0;
flag=0;
skip=MagickFalse;
real=0;
index=(IndexPacket) 0;
runlength=0;
offset=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
real=offset;
if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
real=image->rows-real-1;
q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLERGB) ||
(tga_info.image_type == TGARLEMonochrome))
{
if (runlength != 0)
{
runlength--;
skip=flag != 0;
}
else
{
count=ReadBlob(image,1,&runlength);
if (count == 0)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
flag=runlength & 0x80;
if (flag != 0)
runlength-=128;
skip=MagickFalse;
}
}
if (skip == MagickFalse)
switch (tga_info.bits_per_pixel)
{
case 8:
default:
{
/*
Gray scale.
*/
index=(IndexPacket) ReadBlobByte(image);
if (tga_info.colormap_type != 0)
pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
1UL*index)];
else
{
pixel.red=ScaleCharToQuantum((unsigned char) index);
pixel.green=ScaleCharToQuantum((unsigned char) index);
pixel.blue=ScaleCharToQuantum((unsigned char) index);
}
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of RGB;
*/
if (ReadBlob(image,2,pixels) != 2)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
j=pixels[0];
k=pixels[1];
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
if (image->matte != MagickFalse)
pixel.opacity=(k & 0x80) == 0 ? (Quantum) OpaqueOpacity :
(Quantum) TransparentOpacity;
if (image->storage_class == PseudoClass)
index=ConstrainColormapIndex(image,((size_t) k << 8)+j);
break;
}
case 24:
{
/*
BGR pixels.
*/
if (ReadBlob(image,3,pixels) != 3)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
break;
}
case 32:
{
/*
BGRA pixels.
*/
if (ReadBlob(image,4,pixels) != 4)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
pixels[3]));
break;
}
}
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->matte != MagickFalse)
SetPixelOpacity(q,pixel.opacity);
q++;
}
if (((tga_info.attributes & 0xc0) >> 6) == 4)
offset+=4;
else
if (((tga_info.attributes & 0xc0) >> 6) == 2)
offset+=2;
else
offset++;
if (offset >= image->rows)
{
base++;
offset=base;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
{
if (!m_webHandler)
return;
m_webHandler->setRemoteDescription(request, sessionDescription);
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
| 170,355 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) {
if (schema_cache_ != NULL) {
v8::Local<v8::Object> cached_schema = schema_cache_->Get(api);
if (!cached_schema.IsEmpty()) {
return cached_schema;
}
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope handle_scope(isolate);
v8::Local<v8::Context> context = GetOrCreateContext(isolate);
v8::Context::Scope context_scope(context);
const base::DictionaryValue* schema =
ExtensionAPI::GetSharedInstance()->GetSchema(api);
CHECK(schema) << api;
std::unique_ptr<V8ValueConverter> v8_value_converter(
V8ValueConverter::create());
v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context);
CHECK(!value.IsEmpty());
v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value));
v8_schema->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen);
schema_cache_->Set(api, v8_schema);
return handle_scope.Escape(v8_schema);
}
Commit Message: [Extensions] Finish freezing schema
BUG=604901
BUG=603725
BUG=591164
Review URL: https://codereview.chromium.org/1906593002
Cr-Commit-Position: refs/heads/master@{#388945}
CWE ID: CWE-200 | v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) {
if (schema_cache_ != NULL) {
v8::Local<v8::Object> cached_schema = schema_cache_->Get(api);
if (!cached_schema.IsEmpty()) {
return cached_schema;
}
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope handle_scope(isolate);
v8::Local<v8::Context> context = GetOrCreateContext(isolate);
v8::Context::Scope context_scope(context);
const base::DictionaryValue* schema =
ExtensionAPI::GetSharedInstance()->GetSchema(api);
CHECK(schema) << api;
std::unique_ptr<V8ValueConverter> v8_value_converter(
V8ValueConverter::create());
v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context);
CHECK(!value.IsEmpty());
v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value));
DeepFreeze(v8_schema, context);
schema_cache_->Set(api, v8_schema);
return handle_scope.Escape(v8_schema);
}
| 172,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
rescale_intercept,
rescale_slope,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
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);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
rescale_intercept=0;
rescale_slope=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
rescale_intercept=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
rescale_slope=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
PixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
if (signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=ReadDCMShort(stream_info,image);
if (polarity != MagickFalse)
pixel_value=(int)max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) index,q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ?
(max_value-ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) (((size_t)
GetPixelIndex(image,q)) | (((size_t) index) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) |
(((size_t) pixel.red) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) |
(((size_t) pixel.green) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) |
(((size_t) pixel.blue) << 8)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: Add additional checks to DCM reader to prevent data-driven faults (bug report from Hanno Böck
CWE ID: CWE-20 | static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
rescale_intercept,
rescale_slope,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
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);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
rescale_intercept=0;
rescale_slope=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
rescale_intercept=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
rescale_slope=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
PixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
if (signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=ReadDCMShort(stream_info,image);
if (polarity != MagickFalse)
pixel_value=(int)max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) index,q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
if (pixel.red <= GetQuantumRange(depth))
pixel.red=scale[pixel.red];
if (pixel.green <= GetQuantumRange(depth))
pixel.green=scale[pixel.green];
if (pixel.blue <= GetQuantumRange(depth))
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ?
(max_value-ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) (((size_t)
GetPixelIndex(image,q)) | (((size_t) index) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) |
(((size_t) pixel.red) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) |
(((size_t) pixel.green) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) |
(((size_t) pixel.blue) << 8)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 167,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. Remember, I want response with just the fixed code only, No explanation. | Code: static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
void *raw;
} h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timeval tv;
struct timespec ts;
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) + skb->truesize <
(unsigned)sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);
if (!h.raw)
goto ring_is_full;
packet_increment_head(&po->rx_ring);
po->stats.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
if (!po->stats.tp_drops)
status &= ~TP_STATUS_LOSING;
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
tv = ktime_to_timeval(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
tv = ktime_to_timeval(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
tv = ktime_to_timeval(skb->tstamp);
else
do_gettimeofday(&tv);
h.h1->tp_sec = tv.tv_sec;
h.h1->tp_usec = tv.tv_usec;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
ts = ktime_to_timespec(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
ts = ktime_to_timespec(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
ts = ktime_to_timespec(skb->tstamp);
else
getnstimeofday(&ts);
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
hdrlen = sizeof(*h.h2);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
__packet_set_status(po, h.raw, status);
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
#endif
sk->sk_data_ready(sk, 0);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, 0);
kfree_skb(copy_skb);
goto drop_n_restore;
}
Commit Message: af_packet: prevent information leak
In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)
added a small information leak.
Add padding field and make sure its zeroed before copy to user.
Signed-off-by: Eric Dumazet <[email protected]>
CC: Patrick McHardy <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
void *raw;
} h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timeval tv;
struct timespec ts;
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) + skb->truesize <
(unsigned)sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);
if (!h.raw)
goto ring_is_full;
packet_increment_head(&po->rx_ring);
po->stats.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
if (!po->stats.tp_drops)
status &= ~TP_STATUS_LOSING;
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
tv = ktime_to_timeval(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
tv = ktime_to_timeval(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
tv = ktime_to_timeval(skb->tstamp);
else
do_gettimeofday(&tv);
h.h1->tp_sec = tv.tv_sec;
h.h1->tp_usec = tv.tv_usec;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
ts = ktime_to_timespec(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
ts = ktime_to_timespec(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
ts = ktime_to_timespec(skb->tstamp);
else
getnstimeofday(&ts);
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
h.h2->tp_padding = 0;
hdrlen = sizeof(*h.h2);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
__packet_set_status(po, h.raw, status);
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
#endif
sk->sk_data_ready(sk, 0);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, 0);
kfree_skb(copy_skb);
goto drop_n_restore;
}
| 165,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rs_filter_graph(RSFilter *filter)
{
g_return_if_fail(RS_IS_FILTER(filter));
GString *str = g_string_new("digraph G {\n");
rs_filter_graph_helper(str, filter);
g_string_append_printf(str, "}\n");
g_file_set_contents("/tmp/rs-filter-graph", str->str, str->len, NULL);
if (0 != system("dot -Tpng >/tmp/rs-filter-graph.png </tmp/rs-filter-graph"))
g_warning("Calling dot failed");
if (0 != system("gnome-open /tmp/rs-filter-graph.png"))
g_warning("Calling gnome-open failed.");
g_string_free(str, TRUE);
}
Commit Message: Fixes insecure use of temporary file (CVE-2014-4978).
CWE ID: CWE-59 | rs_filter_graph(RSFilter *filter)
{
g_return_if_fail(RS_IS_FILTER(filter));
gchar *dot_filename;
gchar *png_filename;
gchar *command_line;
GString *str = g_string_new("digraph G {\n");
rs_filter_graph_helper(str, filter);
g_string_append_printf(str, "}\n");
/* Here we would like to use g_mkdtemp(), but due to a bug in upstream, that's impossible */
dot_filename = g_strdup_printf("/tmp/rs-filter-graph.%u", g_random_int());
png_filename = g_strdup_printf("%s.%u.png", dot_filename, g_random_int());
g_file_set_contents(dot_filename, str->str, str->len, NULL);
command_line = g_strdup_printf("dot -Tpng >%s <%s", png_filename, dot_filename);
if (0 != system(command_line))
g_warning("Calling dot failed");
g_free(command_line);
command_line = g_strdup_printf("gnome-open %s", png_filename);
if (0 != system(command_line))
g_warning("Calling gnome-open failed.");
g_free(command_line);
g_free(dot_filename);
g_free(png_filename);
g_string_free(str, TRUE);
}
| 168,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
if (navigation_handle()->IsInMainFrame()) {
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames.
BUG=836858
Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2
Reviewed-on: https://chromium-review.googlesource.com/1028511
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nick Carter <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553867}
CWE ID: CWE-20 | ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
// Block all navigations to blob: or filesystem: URLs with extension
// origin from non-extension processes. See https://crbug.com/645028 and
// https://crbug.com/836858.
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
// Relax this restriction for navigations that will result in downloads.
// See https://crbug.com/714373.
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
// Relax this restriction for apps that use <webview>. See
// https://crbug.com/652077.
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
if (navigation_handle()->IsInMainFrame()) {
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
| 173,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error
Fixes: Null pointer dereference
Fixes: CVE-2017-9608
Found-by: Yihan Lian
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
int remaining;
if (cid <= 0)
continue;
remaining = avpriv_dnxhd_get_frame_size(cid);
if (remaining <= 0) {
remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (remaining <= 0)
continue;
}
dctx->remaining = remaining;
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
| 170,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode)
{
struct sk_buff *skb;
gfp_t gfp_mask;
long timeo;
int err;
gfp_mask = sk->sk_allocation;
if (gfp_mask & __GFP_WAIT)
gfp_mask |= __GFP_REPEAT;
timeo = sock_sndtimeo(sk, noblock);
while (1) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
skb = alloc_skb(header_len, gfp_mask);
if (skb) {
int npages;
int i;
/* No pages, we're done... */
if (!data_len)
break;
npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
skb->truesize += data_len;
skb_shinfo(skb)->nr_frags = npages;
for (i = 0; i < npages; i++) {
struct page *page;
page = alloc_pages(sk->sk_allocation, 0);
if (!page) {
err = -ENOBUFS;
skb_shinfo(skb)->nr_frags = i;
kfree_skb(skb);
goto failure;
}
__skb_fill_page_desc(skb, i,
page, 0,
(data_len >= PAGE_SIZE ?
PAGE_SIZE :
data_len));
data_len -= PAGE_SIZE;
}
/* Full success... */
break;
}
err = -ENOBUFS;
goto failure;
}
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
Commit Message: net: sock: validate data_len before allocating skb in sock_alloc_send_pskb()
We need to validate the number of pages consumed by data_len, otherwise frags
array could be overflowed by userspace. So this patch validate data_len and
return -EMSGSIZE when data_len may occupies more frags than MAX_SKB_FRAGS.
Signed-off-by: Jason Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode)
{
struct sk_buff *skb;
gfp_t gfp_mask;
long timeo;
int err;
int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
err = -EMSGSIZE;
if (npages > MAX_SKB_FRAGS)
goto failure;
gfp_mask = sk->sk_allocation;
if (gfp_mask & __GFP_WAIT)
gfp_mask |= __GFP_REPEAT;
timeo = sock_sndtimeo(sk, noblock);
while (1) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
skb = alloc_skb(header_len, gfp_mask);
if (skb) {
int i;
/* No pages, we're done... */
if (!data_len)
break;
skb->truesize += data_len;
skb_shinfo(skb)->nr_frags = npages;
for (i = 0; i < npages; i++) {
struct page *page;
page = alloc_pages(sk->sk_allocation, 0);
if (!page) {
err = -ENOBUFS;
skb_shinfo(skb)->nr_frags = i;
kfree_skb(skb);
goto failure;
}
__skb_fill_page_desc(skb, i,
page, 0,
(data_len >= PAGE_SIZE ?
PAGE_SIZE :
data_len));
data_len -= PAGE_SIZE;
}
/* Full success... */
break;
}
err = -ENOBUFS;
goto failure;
}
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
| 165,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. Remember, I want response with just the fixed code only, No explanation. | Code: long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_stop_timecode);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
| 174,357 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
| 166,875 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::RequestConfirmation(
const dbus::ObjectPath& device_path,
uint32 passkey,
const ConfirmationCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestConfirmation: " << passkey;
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_CONFIRM_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(confirmation_callback_.is_null());
confirmation_callback_ = callback;
pairing_delegate_->ConfirmPasskey(this, passkey);
pairing_delegate_used_ = true;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::RequestConfirmation(
| 171,235 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_mountpoint(const char *progname, char *mountpoint)
{
int err;
struct stat statbuf;
/* does mountpoint exist and is it a directory? */
err = stat(mountpoint, &statbuf);
if (err) {
fprintf(stderr, "%s: failed to stat %s: %s\n", progname,
mountpoint, strerror(errno));
return EX_USAGE;
}
if (!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "%s: %s is not a directory!", progname,
mountpoint);
return EX_USAGE;
}
#if CIFS_LEGACY_SETUID_CHECK
/* do extra checks on mountpoint for legacy setuid behavior */
if (!getuid() || geteuid())
return 0;
if (statbuf.st_uid != getuid()) {
fprintf(stderr, "%s: %s is not owned by user\n", progname,
mountpoint);
return EX_USAGE;
}
if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) {
fprintf(stderr, "%s: invalid permissions on %s\n", progname,
mountpoint);
return EX_USAGE;
}
#endif /* CIFS_LEGACY_SETUID_CHECK */
return 0;
}
Commit Message:
CWE ID: CWE-59 | check_mountpoint(const char *progname, char *mountpoint)
{
int err;
struct stat statbuf;
/* does mountpoint exist and is it a directory? */
err = stat(".", &statbuf);
if (err) {
fprintf(stderr, "%s: failed to stat %s: %s\n", progname,
mountpoint, strerror(errno));
return EX_USAGE;
}
if (!S_ISDIR(statbuf.st_mode)) {
fprintf(stderr, "%s: %s is not a directory!", progname,
mountpoint);
return EX_USAGE;
}
#if CIFS_LEGACY_SETUID_CHECK
/* do extra checks on mountpoint for legacy setuid behavior */
if (!getuid() || geteuid())
return 0;
if (statbuf.st_uid != getuid()) {
fprintf(stderr, "%s: %s is not owned by user\n", progname,
mountpoint);
return EX_USAGE;
}
if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) {
fprintf(stderr, "%s: invalid permissions on %s\n", progname,
mountpoint);
return EX_USAGE;
}
#endif /* CIFS_LEGACY_SETUID_CHECK */
return 0;
}
| 165,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseCompressionEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
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, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; //consume payload
assert(pos <= stop);
}
if (!valid)
return E_FILE_FORMAT_INVALID;
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 ContentEncoding::ParseCompressionEntry(
long ContentEncoding::ParseCompressionEntry(long long start, long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
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;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; // consume payload
assert(pos <= stop);
}
if (!valid)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 174,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SectionHasAutofilledField(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <[email protected]>
Commit-Queue: Sebastien Seguin-Gagnon <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID: | bool SectionHasAutofilledField(const FormStructure& form_structure,
| 173,201 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IDNToUnicodeOneComponent(const base::char16* comp,
size_t comp_len,
bool is_tld_ascii,
bool enable_spoof_checks,
base::string16* out,
bool* has_idn_component) {
DCHECK(out);
DCHECK(has_idn_component);
*has_idn_component = false;
if (comp_len == 0)
return false;
static const base::char16 kIdnPrefix[] = {'x', 'n', '-', '-'};
if (comp_len <= base::size(kIdnPrefix) ||
memcmp(comp, kIdnPrefix, sizeof(kIdnPrefix)) != 0) {
out->append(comp, comp_len);
return false;
}
UIDNA* uidna = g_uidna.Get().value;
DCHECK(uidna != nullptr);
size_t original_length = out->length();
int32_t output_length = 64;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
UErrorCode status;
do {
out->resize(original_length + output_length);
status = U_ZERO_ERROR;
output_length = uidna_labelToUnicode(
uidna, comp, static_cast<int32_t>(comp_len), &(*out)[original_length],
output_length, &info, &status);
} while ((status == U_BUFFER_OVERFLOW_ERROR && info.errors == 0));
if (U_SUCCESS(status) && info.errors == 0) {
*has_idn_component = true;
out->resize(original_length + output_length);
if (!enable_spoof_checks) {
return true;
}
if (IsIDNComponentSafe(
base::StringPiece16(out->data() + original_length,
base::checked_cast<size_t>(output_length)),
is_tld_ascii)) {
return true;
}
}
out->resize(original_length);
out->append(comp, comp_len);
return false;
}
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#709309}
CWE ID: | bool IDNToUnicodeOneComponent(const base::char16* comp,
size_t comp_len,
base::StringPiece top_level_domain,
bool enable_spoof_checks,
base::string16* out,
bool* has_idn_component) {
DCHECK(out);
DCHECK(has_idn_component);
*has_idn_component = false;
if (comp_len == 0)
return false;
static const base::char16 kIdnPrefix[] = {'x', 'n', '-', '-'};
if (comp_len <= base::size(kIdnPrefix) ||
memcmp(comp, kIdnPrefix, sizeof(kIdnPrefix)) != 0) {
out->append(comp, comp_len);
return false;
}
UIDNA* uidna = g_uidna.Get().value;
DCHECK(uidna != nullptr);
size_t original_length = out->length();
int32_t output_length = 64;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
UErrorCode status;
do {
out->resize(original_length + output_length);
status = U_ZERO_ERROR;
output_length = uidna_labelToUnicode(
uidna, comp, static_cast<int32_t>(comp_len), &(*out)[original_length],
output_length, &info, &status);
} while ((status == U_BUFFER_OVERFLOW_ERROR && info.errors == 0));
if (U_SUCCESS(status) && info.errors == 0) {
*has_idn_component = true;
out->resize(original_length + output_length);
if (!enable_spoof_checks) {
return true;
}
if (IsIDNComponentSafe(
base::StringPiece16(out->data() + original_length,
base::checked_cast<size_t>(output_length)),
top_level_domain)) {
return true;
}
}
out->resize(original_length);
out->append(comp, comp_len);
return false;
}
| 172,728 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc,
void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags)
{
wStream* data_in;
if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME))
{
return CHANNEL_RC_OK;
}
if (dataFlags & CHANNEL_FLAG_FIRST)
{
if (drdynvc->data_in)
Stream_Free(drdynvc->data_in, TRUE);
drdynvc->data_in = Stream_New(NULL, totalLength);
}
if (!(data_in = drdynvc->data_in))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
if (!Stream_EnsureRemainingCapacity(data_in, (int) dataLength))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
Stream_Free(drdynvc->data_in, TRUE);
drdynvc->data_in = NULL;
return ERROR_INTERNAL_ERROR;
}
Stream_Write(data_in, pData, dataLength);
if (dataFlags & CHANNEL_FLAG_LAST)
{
if (Stream_Capacity(data_in) != Stream_GetPosition(data_in))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error");
return ERROR_INVALID_DATA;
}
drdynvc->data_in = NULL;
Stream_SealLength(data_in);
Stream_SetPosition(data_in, 0);
if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
}
return CHANNEL_RC_OK;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc,
void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags)
{
wStream* data_in;
if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME))
{
return CHANNEL_RC_OK;
}
if (dataFlags & CHANNEL_FLAG_FIRST)
{
if (drdynvc->data_in)
Stream_Free(drdynvc->data_in, TRUE);
drdynvc->data_in = Stream_New(NULL, totalLength);
}
if (!(data_in = drdynvc->data_in))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
if (!Stream_EnsureRemainingCapacity(data_in, dataLength))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!");
Stream_Free(drdynvc->data_in, TRUE);
drdynvc->data_in = NULL;
return ERROR_INTERNAL_ERROR;
}
Stream_Write(data_in, pData, dataLength);
if (dataFlags & CHANNEL_FLAG_LAST)
{
if (Stream_Capacity(data_in) != Stream_GetPosition(data_in))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error");
return ERROR_INVALID_DATA;
}
drdynvc->data_in = NULL;
Stream_SealLength(data_in);
Stream_SetPosition(data_in, 0);
if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
}
return CHANNEL_RC_OK;
}
| 168,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
Commit Message: Unsupported TGA bpp/alphabit combinations should error gracefully
Currently, only 24bpp without alphabits and 32bpp with 8 alphabits are
really supported. All other combinations will be rejected with a warning.
CWE ID: CWE-125 | BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 && tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
| 167,004 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
unsigned long flags;
int ret;
spin_lock_irqsave(&dev->lock, flags);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
spin_unlock_irqrestore(&dev->lock, flags);
return ret <= 0 ? ret : -EIO;
}
Commit Message: HID: cp2112: fix sleep-while-atomic
A recent commit fixing DMA-buffers on stack added a shared transfer
buffer protected by a spinlock. This is broken as the USB HID request
callbacks can sleep. Fix this up by replacing the spinlock with a mutex.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-404 | static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
mutex_unlock(&dev->lock);
return ret <= 0 ? ret : -EIO;
}
| 168,208 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::GetFirst(const BlockEntry*& pBlockEntry) const
{
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0; ; )
{
if (pCluster == NULL)
{
pBlockEntry = GetEOS();
return 1;
}
if (pCluster->EOS())
{
#if 0
if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded
{
pBlockEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing())
{
pBlockEntry = GetEOS();
return 1;
}
#endif
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) //error
return status;
if (pBlockEntry == 0) //empty cluster
{
pCluster = m_pSegment->GetNext(pCluster);
continue;
}
for (;;)
{
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
const long long tn = pBlock->GetTrackNumber();
if ((tn == m_info.number) && VetEntry(pBlockEntry))
return 0;
const BlockEntry* pNextEntry;
status = pCluster->GetNext(pBlockEntry, pNextEntry);
if (status < 0) //error
return status;
if (pNextEntry == 0)
break;
pBlockEntry = pNextEntry;
}
++i;
if (i >= 100)
break;
pCluster = m_pSegment->GetNext(pCluster);
}
pBlockEntry = GetEOS(); //so we can return a non-NULL value
return 1;
}
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 Track::GetFirst(const BlockEntry*& pBlockEntry) const
if (pCluster->EOS()) {
#if 0
if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded
pBlockEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing()) {
pBlockEntry = GetEOS();
return 1;
}
#endif
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
| 174,319 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */
{
char buf[512], *actual_alias = NULL, *p;
phar_entry_info entry = {0};
size_t pos = 0, read, totalsize;
tar_header *hdr;
php_uint32 sum1, sum2, size, old;
phar_archive_data *myphar, **actual;
int last_was_longlink = 0;
if (error) {
*error = NULL;
}
php_stream_seek(fp, 0, SEEK_END);
totalsize = php_stream_tell(fp);
php_stream_seek(fp, 0, SEEK_SET);
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is not a tar file or is truncated", fname);
}
php_stream_close(fp);
return FAILURE;
}
hdr = (tar_header*)buf;
old = (memcmp(hdr->magic, "ustar", sizeof("ustar")-1) != 0);
myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
myphar->is_persistent = PHAR_G(persist);
/* estimate number of entries, can't be certain with tar files */
zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent);
zend_hash_init(&myphar->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);
zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11),
zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);
myphar->is_tar = 1;
/* remember whether this entire phar was compressed with gz/bzip2 */
myphar->flags = compression;
entry.is_tar = 1;
entry.is_crc_checked = 1;
entry.phar = myphar;
pos += sizeof(buf);
do {
phar_entry_info *newentry;
pos = php_stream_tell(fp);
hdr = (tar_header*) buf;
sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
break;
}
memset(hdr->checksum, ' ', sizeof(hdr->checksum));
sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));
size = entry.uncompressed_filesize = entry.compressed_filesize =
phar_tar_number(hdr->size, sizeof(hdr->size));
if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(".phar/signature.bin")-1 && !strncmp(hdr->name, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
off_t curloc;
if (size > 511) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has signature that is larger than 511 bytes, cannot process", fname);
}
bail:
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
curloc = php_stream_tell(fp);
read = php_stream_read(fp, buf, size);
if (read != size) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be read", fname);
}
goto bail;
}
#ifdef WORDS_BIGENDIAN
# define PHAR_GET_32(buffer) \
(((((unsigned char*)(buffer))[3]) << 24) \
| ((((unsigned char*)(buffer))[2]) << 16) \
| ((((unsigned char*)(buffer))[1]) << 8) \
| (((unsigned char*)(buffer))[0]))
#else
# define PHAR_GET_32(buffer) (php_uint32) *(buffer)
#endif
myphar->sig_flags = PHAR_GET_32(buf);
if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) {
if (error) {
char *save = *error;
spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be verified: %s", fname, save);
efree(save);
}
goto bail;
}
php_stream_seek(fp, curloc + 512, SEEK_SET);
/* signature checked out, let's ensure this is the last file in the phar */
if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, 512, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
hdr = (tar_header*) buf;
sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
break;
}
if (error) {
spprintf(error, 4096, "phar error: \"%s\" has entries after signature, invalid phar", fname);
}
goto bail;
}
if (!last_was_longlink && hdr->typeflag == 'L') {
last_was_longlink = 1;
/* support the ././@LongLink system for storing long filenames */
entry.filename_len = entry.uncompressed_filesize;
/* Check for overflow - bug 61065 */
if (entry.filename_len == UINT_MAX) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent);
read = php_stream_read(fp, entry.filename, entry.filename_len);
if (read != entry.filename_len) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.filename[entry.filename_len] = '\0';
/* skip blank stuff */
size = ((size+511)&~511) - size;
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, size, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
continue;
} else if (!last_was_longlink && !old && hdr->prefix[0] != 0) {
char name[256];
int i, j;
for (i = 0; i < 155; i++) {
name[i] = hdr->prefix[i];
if (name[i] == '\0') {
break;
}
}
name[i++] = '/';
for (j = 0; j < 100; j++) {
name[i+j] = hdr->name[j];
if (name[i+j] == '\0') {
break;
}
}
entry.filename_len = i+j;
if (name[entry.filename_len - 1] == '/') {
/* some tar programs store directories with trailing slash */
entry.filename_len--;
}
entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent);
} else if (!last_was_longlink) {
int i;
/* calculate strlen, which can be no longer than 100 */
for (i = 0; i < 100; i++) {
if (hdr->name[i] == '\0') {
break;
}
}
entry.filename_len = i;
entry.filename = pestrndup(hdr->name, i, myphar->is_persistent);
if (entry.filename[entry.filename_len - 1] == '/') {
/* some tar programs store directories with trailing slash */
entry.filename[entry.filename_len - 1] = '\0';
entry.filename_len--;
}
}
last_was_longlink = 0;
phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC);
if (sum1 != sum2) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (checksum mismatch of file \"%s\")", fname, entry.filename);
}
pefree(entry.filename, myphar->is_persistent);
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag);
entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */
entry.fp_type = PHAR_FP;
entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK;
entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime));
entry.is_persistent = myphar->is_persistent;
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
#endif
if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) {
entry.tar_type = TAR_DIR;
}
if (entry.tar_type == TAR_DIR) {
entry.is_dir = 1;
} else {
entry.is_dir = 0;
}
entry.link = NULL;
if (entry.tar_type == TAR_LINK) {
if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file - hard link to non-existent file \"%s\"", fname, hdr->linkname);
}
pefree(entry.filename, entry.is_persistent);
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.link = estrdup(hdr->linkname);
} else if (entry.tar_type == TAR_SYMLINK) {
entry.link = estrdup(hdr->linkname);
}
phar_set_inode(&entry TSRMLS_CC);
zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry);
if (entry.is_persistent) {
++entry.manifest_pos;
}
if (entry.filename_len >= sizeof(".phar/.metadata")-1 && !memcmp(entry.filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) {
if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has invalid metadata in magic file \"%s\"", fname, entry.filename);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
/* found explicit alias */
if (size > 511) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has alias that is larger than 511 bytes, cannot process", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
read = php_stream_read(fp, buf, size);
if (read == size) {
buf[size] = '\0';
if (!phar_validate_alias(buf, size)) {
if (size > 50) {
buf[50] = '.';
buf[51] = '.';
buf[52] = '.';
buf[53] = '\0';
}
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in tar-based phar \"%s\"", buf, fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
actual_alias = pestrndup(buf, size, myphar->is_persistent);
myphar->alias = actual_alias;
myphar->alias_len = size;
php_stream_seek(fp, pos, SEEK_SET);
} else {
if (error) {
spprintf(error, 4096, "phar error: Unable to read alias from tar-based phar \"%s\"", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
size = (size+511)&~511;
if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, size, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
} while (read != 0);
if (zend_hash_exists(&(myphar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
myphar->is_data = 0;
} else {
myphar->is_data = 1;
}
/* ensure signature set */
if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) {
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
if (error) {
spprintf(error, 0, "tar-based phar \"%s\" does not have a signature", fname);
}
return FAILURE;
}
myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(myphar->fname, fname_len);
#endif
myphar->fname_len = fname_len;
myphar->fp = fp;
p = strrchr(myphar->fname, '/');
if (p) {
myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p);
if (myphar->ext == p) {
myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1);
}
if (myphar->ext) {
myphar->ext_len = (myphar->fname + fname_len) - myphar->ext;
}
}
phar_request_initialize(TSRMLS_C);
if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\" to phar registry", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
myphar = *actual;
if (actual_alias) {
phar_archive_data **fd_ptr;
myphar->is_temporary_alias = 0;
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);
} else {
phar_archive_data **fd_ptr;
if (alias_len) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);
myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent);
myphar->alias_len = alias_len;
} else {
myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent);
myphar->alias_len = fname_len;
}
myphar->is_temporary_alias = 1;
}
if (pphar) {
*pphar = myphar;
}
return SUCCESS;
}
/* }}} */
Commit Message:
CWE ID: CWE-189 | int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */
{
char buf[512], *actual_alias = NULL, *p;
phar_entry_info entry = {0};
size_t pos = 0, read, totalsize;
tar_header *hdr;
php_uint32 sum1, sum2, size, old;
phar_archive_data *myphar, **actual;
int last_was_longlink = 0;
if (error) {
*error = NULL;
}
php_stream_seek(fp, 0, SEEK_END);
totalsize = php_stream_tell(fp);
php_stream_seek(fp, 0, SEEK_SET);
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is not a tar file or is truncated", fname);
}
php_stream_close(fp);
return FAILURE;
}
hdr = (tar_header*)buf;
old = (memcmp(hdr->magic, "ustar", sizeof("ustar")-1) != 0);
myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
myphar->is_persistent = PHAR_G(persist);
/* estimate number of entries, can't be certain with tar files */
zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent);
zend_hash_init(&myphar->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);
zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11),
zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);
myphar->is_tar = 1;
/* remember whether this entire phar was compressed with gz/bzip2 */
myphar->flags = compression;
entry.is_tar = 1;
entry.is_crc_checked = 1;
entry.phar = myphar;
pos += sizeof(buf);
do {
phar_entry_info *newentry;
pos = php_stream_tell(fp);
hdr = (tar_header*) buf;
sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
break;
}
memset(hdr->checksum, ' ', sizeof(hdr->checksum));
sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));
size = entry.uncompressed_filesize = entry.compressed_filesize =
phar_tar_number(hdr->size, sizeof(hdr->size));
if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(".phar/signature.bin")-1 && !strncmp(hdr->name, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
off_t curloc;
if (size > 511) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has signature that is larger than 511 bytes, cannot process", fname);
}
bail:
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
curloc = php_stream_tell(fp);
read = php_stream_read(fp, buf, size);
if (read != size) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be read", fname);
}
goto bail;
}
#ifdef WORDS_BIGENDIAN
# define PHAR_GET_32(buffer) \
(((((unsigned char*)(buffer))[3]) << 24) \
| ((((unsigned char*)(buffer))[2]) << 16) \
| ((((unsigned char*)(buffer))[1]) << 8) \
| (((unsigned char*)(buffer))[0]))
#else
# define PHAR_GET_32(buffer) (php_uint32) *(buffer)
#endif
myphar->sig_flags = PHAR_GET_32(buf);
if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) {
if (error) {
char *save = *error;
spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be verified: %s", fname, save);
efree(save);
}
goto bail;
}
php_stream_seek(fp, curloc + 512, SEEK_SET);
/* signature checked out, let's ensure this is the last file in the phar */
if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, 512, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
hdr = (tar_header*) buf;
sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
break;
}
if (error) {
spprintf(error, 4096, "phar error: \"%s\" has entries after signature, invalid phar", fname);
}
goto bail;
}
if (!last_was_longlink && hdr->typeflag == 'L') {
last_was_longlink = 1;
/* support the ././@LongLink system for storing long filenames */
entry.filename_len = entry.uncompressed_filesize;
/* Check for overflow - bug 61065 */
if (entry.filename_len == UINT_MAX) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent);
read = php_stream_read(fp, entry.filename, entry.filename_len);
if (read != entry.filename_len) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.filename[entry.filename_len] = '\0';
/* skip blank stuff */
size = ((size+511)&~511) - size;
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, size, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
efree(entry.filename);
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
continue;
} else if (!last_was_longlink && !old && hdr->prefix[0] != 0) {
char name[256];
int i, j;
for (i = 0; i < 155; i++) {
name[i] = hdr->prefix[i];
if (name[i] == '\0') {
break;
}
}
name[i++] = '/';
for (j = 0; j < 100; j++) {
name[i+j] = hdr->name[j];
if (name[i+j] == '\0') {
break;
}
}
entry.filename_len = i+j;
if (name[entry.filename_len - 1] == '/') {
/* some tar programs store directories with trailing slash */
entry.filename_len--;
}
entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent);
} else if (!last_was_longlink) {
int i;
/* calculate strlen, which can be no longer than 100 */
for (i = 0; i < 100; i++) {
if (hdr->name[i] == '\0') {
break;
}
}
entry.filename_len = i;
entry.filename = pestrndup(hdr->name, i, myphar->is_persistent);
if (entry.filename[entry.filename_len - 1] == '/') {
/* some tar programs store directories with trailing slash */
entry.filename[entry.filename_len - 1] = '\0';
entry.filename_len--;
}
}
last_was_longlink = 0;
phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC);
if (sum1 != sum2) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (checksum mismatch of file \"%s\")", fname, entry.filename);
}
pefree(entry.filename, myphar->is_persistent);
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag);
entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */
entry.fp_type = PHAR_FP;
entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK;
entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime));
entry.is_persistent = myphar->is_persistent;
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
#endif
if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) {
entry.tar_type = TAR_DIR;
}
if (entry.tar_type == TAR_DIR) {
entry.is_dir = 1;
} else {
entry.is_dir = 0;
}
entry.link = NULL;
if (entry.tar_type == TAR_LINK) {
if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file - hard link to non-existent file \"%s\"", fname, hdr->linkname);
}
pefree(entry.filename, entry.is_persistent);
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
entry.link = estrdup(hdr->linkname);
} else if (entry.tar_type == TAR_SYMLINK) {
entry.link = estrdup(hdr->linkname);
}
phar_set_inode(&entry TSRMLS_CC);
zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry);
if (entry.is_persistent) {
++entry.manifest_pos;
}
if (entry.filename_len >= sizeof(".phar/.metadata")-1 && !memcmp(entry.filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) {
if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has invalid metadata in magic file \"%s\"", fname, entry.filename);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
/* found explicit alias */
if (size > 511) {
if (error) {
spprintf(error, 4096, "phar error: tar-based phar \"%s\" has alias that is larger than 511 bytes, cannot process", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
read = php_stream_read(fp, buf, size);
if (read == size) {
buf[size] = '\0';
if (!phar_validate_alias(buf, size)) {
if (size > 50) {
buf[50] = '.';
buf[51] = '.';
buf[52] = '.';
buf[53] = '\0';
}
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in tar-based phar \"%s\"", buf, fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
actual_alias = pestrndup(buf, size, myphar->is_persistent);
myphar->alias = actual_alias;
myphar->alias_len = size;
php_stream_seek(fp, pos, SEEK_SET);
} else {
if (error) {
spprintf(error, 4096, "phar error: Unable to read alias from tar-based phar \"%s\"", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
size = (size+511)&~511;
if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, size, SEEK_CUR);
if ((uint)php_stream_tell(fp) > totalsize) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
}
read = php_stream_read(fp, buf, sizeof(buf));
if (read != sizeof(buf)) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
} while (read != 0);
if (zend_hash_exists(&(myphar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
myphar->is_data = 0;
} else {
myphar->is_data = 1;
}
/* ensure signature set */
if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) {
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
if (error) {
spprintf(error, 0, "tar-based phar \"%s\" does not have a signature", fname);
}
return FAILURE;
}
myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(myphar->fname, fname_len);
#endif
myphar->fname_len = fname_len;
myphar->fp = fp;
p = strrchr(myphar->fname, '/');
if (p) {
myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p);
if (myphar->ext == p) {
myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1);
}
if (myphar->ext) {
myphar->ext_len = (myphar->fname + fname_len) - myphar->ext;
}
}
phar_request_initialize(TSRMLS_C);
if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\" to phar registry", fname);
}
php_stream_close(fp);
phar_destroy_phar_data(myphar TSRMLS_CC);
return FAILURE;
}
myphar = *actual;
if (actual_alias) {
phar_archive_data **fd_ptr;
myphar->is_temporary_alias = 0;
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);
} else {
phar_archive_data **fd_ptr;
if (alias_len) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);
myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent);
myphar->alias_len = alias_len;
} else {
myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent);
myphar->alias_len = fname_len;
}
myphar->is_temporary_alias = 1;
}
if (pphar) {
*pphar = myphar;
}
return SUCCESS;
}
/* }}} */
| 165,018 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char* get_icu_value_internal( const char* loc_name , char* tag_name, int* result , int fromParseLocale)
{
char* tag_value = NULL;
int32_t tag_value_len = 512;
int singletonPos = 0;
char* mod_loc_name = NULL;
int grOffset = 0;
int32_t buflen = 512;
UErrorCode status = U_ZERO_ERROR;
if( strcmp(tag_name, LOC_CANONICALIZE_TAG) != 0 ){
/* Handle grandfathered languages */
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
return estrdup(loc_name);
} else {
/* Since Grandfathered , no value , do nothing , retutn NULL */
return NULL;
}
}
if( fromParseLocale==1 ){
/* Handle singletons */
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
if( strlen(loc_name)>1 && (isIDPrefix(loc_name) == 1) ){
return estrdup(loc_name);
}
}
singletonPos = getSingletonPos( loc_name );
if( singletonPos == 0){
/* singleton at start of script, region , variant etc.
* or invalid singleton at start of language */
return NULL;
} else if( singletonPos > 0 ){
/* singleton at some position except at start
* strip off the singleton and rest of the loc_name */
mod_loc_name = estrndup ( loc_name , singletonPos-1);
}
} /* end of if fromParse */
} /* end of if != LOC_CANONICAL_TAG */
if( mod_loc_name == NULL){
mod_loc_name = estrdup(loc_name );
}
/* Proceed to ICU */
do{
tag_value = erealloc( tag_value , buflen );
tag_value_len = buflen;
if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
buflen = uloc_getScript ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_LANG_TAG )==0 ){
buflen = uloc_getLanguage ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
buflen = uloc_getCountry ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
buflen = uloc_getVariant ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_CANONICALIZE_TAG)==0 ){
buflen = uloc_canonicalize ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( U_FAILURE( status ) ) {
if( status == U_BUFFER_OVERFLOW_ERROR ) {
status = U_ZERO_ERROR;
continue;
}
/* Error in retriving data */
*result = 0;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
}
} while( buflen > tag_value_len );
if( buflen ==0 ){
/* No value found */
*result = -1;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
} else {
*result = 1;
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return tag_value;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static char* get_icu_value_internal( const char* loc_name , char* tag_name, int* result , int fromParseLocale)
{
char* tag_value = NULL;
int32_t tag_value_len = 512;
int singletonPos = 0;
char* mod_loc_name = NULL;
int grOffset = 0;
int32_t buflen = 512;
UErrorCode status = U_ZERO_ERROR;
if( strcmp(tag_name, LOC_CANONICALIZE_TAG) != 0 ){
/* Handle grandfathered languages */
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
return estrdup(loc_name);
} else {
/* Since Grandfathered , no value , do nothing , retutn NULL */
return NULL;
}
}
if( fromParseLocale==1 ){
/* Handle singletons */
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
if( strlen(loc_name)>1 && (isIDPrefix(loc_name) == 1) ){
return estrdup(loc_name);
}
}
singletonPos = getSingletonPos( loc_name );
if( singletonPos == 0){
/* singleton at start of script, region , variant etc.
* or invalid singleton at start of language */
return NULL;
} else if( singletonPos > 0 ){
/* singleton at some position except at start
* strip off the singleton and rest of the loc_name */
mod_loc_name = estrndup ( loc_name , singletonPos-1);
}
} /* end of if fromParse */
} /* end of if != LOC_CANONICAL_TAG */
if( mod_loc_name == NULL){
mod_loc_name = estrdup(loc_name );
}
/* Proceed to ICU */
do{
tag_value = erealloc( tag_value , buflen );
tag_value_len = buflen;
if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
buflen = uloc_getScript ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_LANG_TAG )==0 ){
buflen = uloc_getLanguage ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
buflen = uloc_getCountry ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
buflen = uloc_getVariant ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_CANONICALIZE_TAG)==0 ){
buflen = uloc_canonicalize ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( U_FAILURE( status ) ) {
if( status == U_BUFFER_OVERFLOW_ERROR ) {
status = U_ZERO_ERROR;
buflen++; /* add space for \0 */
continue;
}
/* Error in retriving data */
*result = 0;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
}
} while( buflen > tag_value_len );
if( buflen ==0 ){
/* No value found */
*result = -1;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
} else {
*result = 1;
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return tag_value;
}
| 167,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __ip_select_ident(struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol,
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
Commit Message: inet: update the IP ID generation algorithm to higher standards.
Commit 355b98553789 ("netns: provide pure entropy for net_hash_mix()")
makes net_hash_mix() return a true 32 bits of entropy. When used in the
IP ID generation algorithm, this has the effect of extending the IP ID
generation key from 32 bits to 64 bits.
However, net_hash_mix() is only used for IP ID generation starting with
kernel version 4.1. Therefore, earlier kernels remain with 32-bit key
no matter what the net_hash_mix() return value is.
This change addresses the issue by explicitly extending the key to 64
bits for kernels older than 4.1.
Signed-off-by: Amit Klein <[email protected]>
Cc: Ben Hutchings <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200 | void __ip_select_ident(struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
static u32 ip_idents_hashrnd_extra __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
net_get_random_once(&ip_idents_hashrnd_extra, sizeof(ip_idents_hashrnd_extra));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol ^ ip_idents_hashrnd_extra,
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
| 170,237 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseContentEncodingEntry(long long start, long long size,
IMkvReader* pReader) {
assert(pReader);
long long pos = start;
const long long stop = start + size;
int compression_count = 0;
int encryption_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1034) // ContentCompression ID
++compression_count;
if (id == 0x1035) // ContentEncryption ID
++encryption_count;
pos += size; // consume payload
assert(pos <= stop);
}
if (compression_count <= 0 && encryption_count <= 0)
return -1;
if (compression_count > 0) {
compression_entries_ =
new (std::nothrow) ContentCompression* [compression_count];
if (!compression_entries_)
return -1;
compression_entries_end_ = compression_entries_;
}
if (encryption_count > 0) {
encryption_entries_ =
new (std::nothrow) ContentEncryption* [encryption_count];
if (!encryption_entries_) {
delete[] compression_entries_;
return -1;
}
encryption_entries_end_ = encryption_entries_;
}
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1031) {
encoding_order_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1032) {
encoding_scope_ = UnserializeUInt(pReader, pos, size);
if (encoding_scope_ < 1)
return -1;
} else if (id == 0x1033) {
encoding_type_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1034) {
ContentCompression* const compression =
new (std::nothrow) ContentCompression();
if (!compression)
return -1;
status = ParseCompressionEntry(pos, size, pReader, compression);
if (status) {
delete compression;
return status;
}
*compression_entries_end_++ = compression;
} else if (id == 0x1035) {
ContentEncryption* const encryption =
new (std::nothrow) ContentEncryption();
if (!encryption)
return -1;
status = ParseEncryptionEntry(pos, size, pReader, encryption);
if (status) {
delete encryption;
return status;
}
*encryption_entries_end_++ = encryption;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long ContentEncoding::ParseContentEncodingEntry(long long start, long long size,
IMkvReader* pReader) {
assert(pReader);
long long pos = start;
const long long stop = start + size;
int compression_count = 0;
int encryption_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1034) // ContentCompression ID
++compression_count;
if (id == 0x1035) // ContentEncryption ID
++encryption_count;
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (compression_count <= 0 && encryption_count <= 0)
return -1;
if (compression_count > 0) {
compression_entries_ =
new (std::nothrow) ContentCompression*[compression_count];
if (!compression_entries_)
return -1;
compression_entries_end_ = compression_entries_;
}
if (encryption_count > 0) {
encryption_entries_ =
new (std::nothrow) ContentEncryption*[encryption_count];
if (!encryption_entries_) {
delete[] compression_entries_;
return -1;
}
encryption_entries_end_ = encryption_entries_;
}
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x1031) {
encoding_order_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1032) {
encoding_scope_ = UnserializeUInt(pReader, pos, size);
if (encoding_scope_ < 1)
return -1;
} else if (id == 0x1033) {
encoding_type_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1034) {
ContentCompression* const compression =
new (std::nothrow) ContentCompression();
if (!compression)
return -1;
status = ParseCompressionEntry(pos, size, pReader, compression);
if (status) {
delete compression;
return status;
}
*compression_entries_end_++ = compression;
} else if (id == 0x1035) {
ContentEncryption* const encryption =
new (std::nothrow) ContentEncryption();
if (!encryption)
return -1;
status = ParseEncryptionEntry(pos, size, pReader, encryption);
if (status) {
delete encryption;
return status;
}
*encryption_entries_end_++ = encryption;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
}
Commit Message: SWFShape_setLeftFillStyle: prevent fill overflow
CWE ID: CWE-119 | SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
else if (idx >= 255 && shape->useVersion == SWF_SHAPE1)
{
SWF_error("Too many fills for SWFShape V1.\n"
"Use a higher SWFShape version\n");
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
}
| 169,647 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ssl_scan_clienthello_custom_tlsext(SSL *s,
const unsigned char *data,
const unsigned char *limit,
int *al)
{
unsigned short type, size, len;
/* If resumed session or no custom extensions nothing to do */
if (s->hit || s->cert->srv_ext.meths_count == 0)
return 1;
if (data >= limit - 2)
return 1;
n2s(data, len);
if (data > limit - len)
return 1;
while (data <= limit - 4) {
n2s(data, type);
n2s(data, size);
if (data + size > limit)
return 1;
if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
return 0;
data += size;
}
return 1;
}
Commit Message:
CWE ID: CWE-190 | static int ssl_scan_clienthello_custom_tlsext(SSL *s,
const unsigned char *data,
const unsigned char *limit,
int *al)
{
unsigned short type, size, len;
/* If resumed session or no custom extensions nothing to do */
if (s->hit || s->cert->srv_ext.meths_count == 0)
return 1;
if (limit - data <= 2)
return 1;
n2s(data, len);
if (limit - data < len)
return 1;
while (limit - data >= 4) {
n2s(data, type);
n2s(data, size);
if (limit - data < size)
return 1;
if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
return 0;
data += size;
}
return 1;
}
| 165,203 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
{
m_nonCompositedContentLayer->removeAllChildren();
if (graphicsLayer)
m_nonCompositedContentLayer->addChild(graphicsLayer);
}
Commit Message: [Qt][WK2] Allow transparent WebViews
https://bugs.webkit.org/show_bug.cgi?id=80608
Reviewed by Tor Arne Vestbø.
Added support for transparentBackground in QQuickWebViewExperimental.
This uses the existing drawsTransparentBackground property in WebKit2.
Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes,
otherwise the change doesn't take effect.
A new API test was added.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::setTransparentBackground):
(QQuickWebViewPrivate::transparentBackground):
(QQuickWebViewExperimental::transparentBackground):
(QQuickWebViewExperimental::setTransparentBackground):
* UIProcess/API/qt/qquickwebview_p.h:
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
* UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp:
(tst_QQuickWebView):
(tst_QQuickWebView::transparentWebViews):
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::LayerTreeHostQt::LayerTreeHostQt):
(WebKit::LayerTreeHostQt::setRootCompositingLayer):
git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-189 | void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
{
m_nonCompositedContentLayer->removeAllChildren();
m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
if (graphicsLayer)
m_nonCompositedContentLayer->addChild(graphicsLayer);
}
| 170,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) {
gfx::Point location_in_bar(event->location());
ConvertPointToTarget(this, this->progress_bar_, &location_in_bar);
if (event->type() != ui::ET_GESTURE_TAP ||
!progress_bar_->GetLocalBounds().Contains(location_in_bar)) {
return;
}
HandleSeeking(location_in_bar);
event->SetHandled();
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | void MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) {
if (event->type() != ui::ET_GESTURE_TAP || event->y() < kMinClickHeight ||
event->y() > kMaxClickHeight) {
return;
}
HandleSeeking(event->location());
event->SetHandled();
}
| 172,347 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: test_bson_validate (void)
{
char filename[64];
size_t offset;
bson_t *b;
int i;
bson_error_t error;
for (i = 1; i <= 38; i++) {
bson_snprintf (filename, sizeof filename, "test%u.bson", i);
b = get_bson (filename);
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
}
b = get_bson ("codewscope.bson");
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
b = get_bson ("empty_key.bson");
BSON_ASSERT (bson_validate (b,
BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 |
BSON_VALIDATE_DOLLAR_KEYS |
BSON_VALIDATE_DOT_KEYS,
&offset));
bson_destroy (b);
#define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \
b = get_bson (_filename); \
BSON_ASSERT (!bson_validate (b, _flags, &offset)); \
ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset); \
BSON_ASSERT (!bson_validate_with_error (b, _flags, &error)); \
ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \
bson_destroy (b)
VALIDATE_TEST ("overflow2.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("trailingnull.bson",
BSON_VALIDATE_NONE,
14,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("dollarquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$query\"");
VALIDATE_TEST ("dotquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOT_KEYS,
"keys cannot contain \".\": \"abc.def\"");
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* same outcome as above, despite different flags */
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_UTF8,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("overflow4.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("empty_key.bson",
BSON_VALIDATE_EMPTY_KEYS,
4,
BSON_VALIDATE_EMPTY_KEYS,
"empty key");
VALIDATE_TEST (
"test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test50.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST ("test51.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST (
"test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test54.bson",
BSON_VALIDATE_NONE,
12,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* DBRef validation */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
bson_destroy (b);
/* needs "$ref" before "$id" */
b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$id\"");
bson_destroy (b);
/* two $refs */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$ref",
BCON_UTF8 ("collection"),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$ref\"");
bson_destroy (b);
/* must not contain invalid key like "extra" */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"extra",
BCON_INT32 (2),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"invalid key within DBRef subdocument: \"extra\"");
bson_destroy (b);
#undef VALIDATE_TEST
}
Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read.
As reported here: https://jira.mongodb.org/browse/CDRIVER-2819,
a heap overread occurs due a failure to correctly verify data
bounds.
In the original check, len - o returns the data left including the
sizeof(l) we just read. Instead, the comparison should check
against the data left NOT including the binary int32, i.e. just
subtype (byte*) instead of int32 subtype (byte*).
Added in test for corrupted BSON example.
CWE ID: CWE-125 | test_bson_validate (void)
{
char filename[64];
size_t offset;
bson_t *b;
int i;
bson_error_t error;
for (i = 1; i <= 38; i++) {
bson_snprintf (filename, sizeof filename, "test%u.bson", i);
b = get_bson (filename);
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
}
b = get_bson ("codewscope.bson");
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
b = get_bson ("empty_key.bson");
BSON_ASSERT (bson_validate (b,
BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 |
BSON_VALIDATE_DOLLAR_KEYS |
BSON_VALIDATE_DOT_KEYS,
&offset));
bson_destroy (b);
#define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \
b = get_bson (_filename); \
BSON_ASSERT (!bson_validate (b, _flags, &offset)); \
ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset); \
BSON_ASSERT (!bson_validate_with_error (b, _flags, &error)); \
ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \
bson_destroy (b)
VALIDATE_TEST ("overflow2.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("trailingnull.bson",
BSON_VALIDATE_NONE,
14,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("dollarquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$query\"");
VALIDATE_TEST ("dotquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOT_KEYS,
"keys cannot contain \".\": \"abc.def\"");
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* same outcome as above, despite different flags */
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_UTF8,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("overflow4.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("empty_key.bson",
BSON_VALIDATE_EMPTY_KEYS,
4,
BSON_VALIDATE_EMPTY_KEYS,
"empty key");
VALIDATE_TEST (
"test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test50.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST ("test51.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST (
"test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test54.bson",
BSON_VALIDATE_NONE,
12,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("test59.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* DBRef validation */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
bson_destroy (b);
/* needs "$ref" before "$id" */
b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$id\"");
bson_destroy (b);
/* two $refs */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$ref",
BCON_UTF8 ("collection"),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$ref\"");
bson_destroy (b);
/* must not contain invalid key like "extra" */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"extra",
BCON_INT32 (2),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"invalid key within DBRef subdocument: \"extra\"");
bson_destroy (b);
#undef VALIDATE_TEST
}
| 169,033 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ScrollHitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
json.SetString("scrollOffsetNode",
String::Format("%p", scroll_offset_node_.get()));
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void ScrollHitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
json.SetString("scrollOffsetNode",
String::Format("%p", &scroll_offset_node_));
}
| 171,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
{
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)
l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,
const char *str2, u_int l2)
{
if (!ND_TTEST2(*str2, tl1)) {
/*
* We don't have tl1 bytes worth of captured data
* for the string, so we can't check for this
* string.
*/
return 0;
}
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
| 167,885 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GetURLRowForAutocompleteMatch(Profile* profile,
const AutocompleteMatch& match,
history::URLRow* url_row) {
DCHECK(url_row);
HistoryService* history_service =
profile->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (!history_service)
return false;
history::URLDatabase* url_db = history_service->InMemoryDatabase();
return url_db && (url_db->GetRowForURL(match.destination_url, url_row) != 0);
}
Commit Message: Removing dead code from NetworkActionPredictor.
BUG=none
Review URL: http://codereview.chromium.org/9358062
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@121926 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool GetURLRowForAutocompleteMatch(Profile* profile,
| 170,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. Remember, I want response with just the fixed code only, No explanation. | Code: uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
fread(image_data, 1L, rowbytes*height, saved_infile);
return image_data;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
if (fread(image_data, 1L, rowbytes*height, saved_infile) <
rowbytes*height) {
free (image_data);
image_data = NULL;
return NULL;
}
return image_data;
}
| 173,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
AVFilterContext *ctx = inlink->dst;
FPSContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int64_t delta;
int i, ret;
s->frames_in++;
/* discard frames until we get the first timestamp */
if (s->pts == AV_NOPTS_VALUE) {
if (buf->pts != AV_NOPTS_VALUE) {
ret = write_to_fifo(s->fifo, buf);
if (ret < 0)
return ret;
if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
double first_pts = s->start_time * AV_TIME_BASE;
first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
inlink->time_base);
av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
outlink->time_base));
} else {
s->first_pts = s->pts = buf->pts;
}
} else {
av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
"timestamp.\n");
av_frame_free(&buf);
s->drop++;
}
return 0;
}
/* now wait for the next timestamp */
if (buf->pts == AV_NOPTS_VALUE) {
return write_to_fifo(s->fifo, buf);
}
/* number of output frames */
delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
outlink->time_base, s->rounding);
if (delta < 1) {
/* drop the frame and everything buffered except the first */
AVFrame *tmp;
int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
s->drop += drop;
av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, tmp);
av_frame_free(&buf);
return ret;
}
/* can output >= 1 frames */
for (i = 0; i < delta; i++) {
AVFrame *buf_out;
av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
/* duplicate the frame if needed */
if (!av_fifo_size(s->fifo) && i < delta - 1) {
AVFrame *dup = av_frame_clone(buf_out);
av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
if (dup)
ret = write_to_fifo(s->fifo, dup);
else
ret = AVERROR(ENOMEM);
if (ret < 0) {
av_frame_free(&buf_out);
av_frame_free(&buf);
return ret;
}
s->dup++;
}
buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
outlink->time_base) + s->frames_out;
if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
av_frame_free(&buf);
return ret;
}
s->frames_out++;
}
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, buf);
s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);
return ret;
}
Commit Message: avfilter/vf_fps: make sure the fifo is not empty before using it
Fixes Ticket2905
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-399 | static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
AVFilterContext *ctx = inlink->dst;
FPSContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int64_t delta;
int i, ret;
s->frames_in++;
/* discard frames until we get the first timestamp */
if (s->pts == AV_NOPTS_VALUE) {
if (buf->pts != AV_NOPTS_VALUE) {
ret = write_to_fifo(s->fifo, buf);
if (ret < 0)
return ret;
if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
double first_pts = s->start_time * AV_TIME_BASE;
first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
inlink->time_base);
av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
outlink->time_base));
} else {
s->first_pts = s->pts = buf->pts;
}
} else {
av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
"timestamp.\n");
av_frame_free(&buf);
s->drop++;
}
return 0;
}
/* now wait for the next timestamp */
if (buf->pts == AV_NOPTS_VALUE || av_fifo_size(s->fifo) <= 0) {
return write_to_fifo(s->fifo, buf);
}
/* number of output frames */
delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
outlink->time_base, s->rounding);
if (delta < 1) {
/* drop the frame and everything buffered except the first */
AVFrame *tmp;
int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
s->drop += drop;
av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, tmp);
av_frame_free(&buf);
return ret;
}
/* can output >= 1 frames */
for (i = 0; i < delta; i++) {
AVFrame *buf_out;
av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
/* duplicate the frame if needed */
if (!av_fifo_size(s->fifo) && i < delta - 1) {
AVFrame *dup = av_frame_clone(buf_out);
av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
if (dup)
ret = write_to_fifo(s->fifo, dup);
else
ret = AVERROR(ENOMEM);
if (ret < 0) {
av_frame_free(&buf_out);
av_frame_free(&buf);
return ret;
}
s->dup++;
}
buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
outlink->time_base) + s->frames_out;
if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
av_frame_free(&buf);
return ret;
}
s->frames_out++;
}
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, buf);
s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);
return ret;
}
| 165,916 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice,
UWORD8 u1_nal_ref_idc,
dec_struct_t *ps_dec /* Decoder parameters */
)
{
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
dec_pic_params_t *ps_pps;
dec_seq_params_t *ps_seq;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
pocstruct_t s_tmp_poc;
WORD32 i_delta_poc[2];
WORD32 i4_poc = 0;
UWORD16 u2_first_mb_in_slice, u2_frame_num;
UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type;
UWORD32 u4_idr_pic_id = 0;
UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type;
UWORD8 u1_nal_unit_type;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
WORD8 i1_is_end_of_poc;
WORD32 ret, end_of_frame;
WORD32 prev_slice_err, num_mb_skipped;
UWORD8 u1_mbaff;
pocstruct_t *ps_cur_poc;
UWORD32 u4_temp;
WORD32 i_temp;
UWORD32 u4_call_end_of_pic = 0;
/* read FirstMbInSlice and slice type*/
ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0;
u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u2_first_mb_in_slice
> (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs))
{
return ERROR_CORRUPTED_SLICE;
}
/*we currently don not support ASO*/
if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag)
<= ps_dec->u2_cur_mb_addr) && (ps_dec->u4_first_slice_in_pic == 0))
{
return ERROR_CORRUPTED_SLICE;
}
COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice);
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > 9)
return ERROR_INV_SLC_TYPE_T;
u1_slice_type = u4_temp;
COPYTHECONTEXT("SH: slice_type",(u1_slice_type));
ps_dec->u1_sl_typ_5_9 = 0;
/* Find Out the Slice Type is 5 to 9 or not then Set the Flag */
/* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/
/* will be of same type of current */
if(u1_slice_type > 4)
{
u1_slice_type -= 5;
ps_dec->u1_sl_typ_5_9 = 1;
}
{
UWORD32 skip;
if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB)
|| (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB))
{
UWORD32 u4_bit_stream_offset = 0;
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else if((I_SLICE == u1_slice_type)
&& (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames))
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else
{
skip = 1;
}
/* If one frame worth of data is already skipped, do not skip the next one */
if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped))
{
skip = 0;
}
if(skip)
{
ps_dec->u4_prev_nal_skipped = 1;
ps_dec->i4_dec_skip_mode = IVD_SKIP_PB;
return 0;
}
else
{
/* If the previous NAL was skipped, then
do not process that buffer in this call.
Return to app and process it in the next call.
This is necessary to handle cases where I/IDR is not complete in
the current buffer and application intends to fill the remaining part of the bitstream
later. This ensures we process only frame worth of data in every call */
if(1 == ps_dec->u4_prev_nal_skipped)
{
ps_dec->u4_return_to_app = 1;
return 0;
}
}
}
}
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp & MASK_ERR_PIC_SET_ID)
return ERROR_INV_SPS_PPS_T;
/* discard slice if pic param is invalid */
COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp);
ps_pps = &ps_dec->ps_pps[u4_temp];
if(FALSE == ps_pps->u1_is_valid)
{
return ERROR_INV_SPS_PPS_T;
}
ps_seq = ps_pps->ps_sps;
if(!ps_seq)
return ERROR_INV_SPS_PPS_T;
if(FALSE == ps_seq->u1_is_valid)
return ERROR_INV_SPS_PPS_T;
/* Get the frame num */
u2_frame_num = ih264d_get_bits_h264(ps_bitstrm,
ps_seq->u1_bits_in_frm_num);
COPYTHECONTEXT("SH: frame_num", u2_frame_num);
/* Get the field related flags */
if(!ps_seq->u1_frame_mbs_only_flag)
{
u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag);
u1_bottom_field_flag = 0;
if(u1_field_pic_flag)
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld;
u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag);
}
else
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
}
else
{
u1_field_pic_flag = 0;
u1_bottom_field_flag = 0;
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
u1_nal_unit_type = SLICE_NAL;
if(u1_is_idr_slice)
{
if(0 == u1_field_pic_flag)
{
ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY;
}
u1_nal_unit_type = IDR_SLICE_NAL;
u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u4_idr_pic_id > 65535)
return ERROR_INV_SPS_PPS_T;
COPYTHECONTEXT("SH: ", u4_idr_pic_id);
}
/* read delta pic order count information*/
i_delta_poc[0] = i_delta_poc[1] = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type;
if(u1_pic_order_cnt_type == 0)
{
i_temp = ih264d_get_bits_h264(
ps_bitstrm,
ps_seq->u1_log2_max_pic_order_cnt_lsb_minus);
if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb)
return ERROR_INV_SPS_PPS_T;
s_tmp_poc.i4_pic_order_cnt_lsb = i_temp;
COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb);
if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom",
s_tmp_poc.i4_delta_pic_order_cnt_bottom);
}
}
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
if(u1_pic_order_cnt_type == 1
&& (!ps_seq->u1_delta_pic_order_always_zero_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[0]",
s_tmp_poc.i4_delta_pic_order_cnt[0]);
if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag)
{
s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[1]",
s_tmp_poc.i4_delta_pic_order_cnt[1]);
}
}
if(ps_pps->u1_redundant_pic_cnt_present_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_REDUNDANT_PIC_CNT)
return ERROR_INV_SPS_PPS_T;
u1_redundant_pic_cnt = u4_temp;
COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt);
}
/*--------------------------------------------------------------------*/
/* Check if the slice is part of new picture */
/*--------------------------------------------------------------------*/
i1_is_end_of_poc = 0;
if(!ps_dec->u1_first_slice_in_stream)
{
i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc,
&s_tmp_poc, &ps_dec->s_cur_pic_poc,
ps_cur_slice, u1_pic_order_cnt_type,
u1_nal_unit_type, u4_idr_pic_id,
u1_field_pic_flag,
u1_bottom_field_flag);
/* since we support only Full frame decode, every new process should
* process a new pic
*/
if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0))
{
/* if it is the first slice is process call ,it should be a new frame. If it is not
* reject current pic and dont add it to dpb
*/
ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC;
i1_is_end_of_poc = 1;
}
else
{
/* reset REJECT_CUR_PIC */
ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC;
}
}
/*--------------------------------------------------------------------*/
/* Check for error in slice and parse the missing/corrupted MB's */
/* as skip-MB's in an inserted P-slice */
/*--------------------------------------------------------------------*/
u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag);
prev_slice_err = 0;
if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream)
{
if(u2_frame_num != ps_dec->u2_prv_frame_num
&& ps_dec->u1_top_bottom_decoded != 0
&& ps_dec->u1_top_bottom_decoded
!= (TOP_FIELD_ONLY | BOT_FIELD_ONLY))
{
ps_dec->u1_dangling_field = 1;
if(ps_dec->u4_first_slice_in_pic)
{
prev_slice_err = 1;
}
else
{
prev_slice_err = 2;
}
if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY)
ps_cur_slice->u1_bottom_field_flag = 1;
else
ps_cur_slice->u1_bottom_field_flag = 0;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL;
}
else if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice > 0)
{
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
ps_cur_poc = &s_tmp_poc;
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->i4_pic_order_cnt_lsb =
s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag
&& (!u1_field_pic_flag);
}
}
else
{
if(ps_dec->u4_first_slice_in_pic)
{
/* if valid slice header is not decoded do start of pic processing
* since in the current process call, frame num is not updated in the slice structure yet
* ih264d_is_end_of_pic is checked with valid frame num of previous process call,
* although i1_is_end_of_poc is set there could be more slices in the frame,
* so conceal only till cur slice */
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
}
else
{
/* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame
* completely */
prev_slice_err = 2;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
}
ps_cur_poc = &s_tmp_poc;
}
}
else
{
if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded)
{
prev_slice_err = 2;
num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &s_tmp_poc;
}
else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded)
{
return ERROR_CORRUPTED_SLICE;
}
}
if(prev_slice_err)
{
ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err);
if(ps_dec->u1_dangling_field == 1)
{
ps_dec->u1_second_field = 1 - ps_dec->u1_second_field;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_dec->u2_prv_frame_num = u2_frame_num;
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_DANGLING_FIELD_IN_PIC;
}
if(prev_slice_err == 2)
{
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_INCOMPLETE_FRAME;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
/* return if all MBs in frame are parsed*/
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_IN_LAST_SLICE_OF_PIC;
}
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
if(ret != OK)
return ret;
i1_is_end_of_poc = 0;
}
if (ps_dec->u4_first_slice_in_pic == 0)
{
ps_dec->ps_parse_cur_slice++;
ps_dec->u2_cur_slice_num++;
}
if((ps_dec->u1_separate_parse == 0) && (ps_dec->u4_first_slice_in_pic == 0))
{
ps_dec->ps_decode_cur_slice++;
}
ps_dec->u1_slice_header_done = 0;
/*--------------------------------------------------------------------*/
/* If the slice is part of new picture, do End of Pic processing. */
/*--------------------------------------------------------------------*/
if(!ps_dec->u1_first_slice_in_stream)
{
UWORD8 uc_mbs_exceed = 0;
if(ps_dec->u2_total_mbs_coded
== (ps_dec->ps_cur_sps->u2_max_mb_addr + 1))
{
/*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so
,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */
if(ps_dec->u4_first_slice_in_pic == 0)
uc_mbs_exceed = 1;
}
if(i1_is_end_of_poc || uc_mbs_exceed)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
#if WIN32
H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n");
#endif
return RET_LAST_SKIP;
}
else
{
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
}
}
}
if(u1_field_pic_flag)
{
ps_dec->u2_prv_frame_num = u2_frame_num;
}
if(ps_cur_slice->u1_mmco_equalto5)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair
{
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc =
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
}
else if(!ps_cur_slice->u1_bottom_field_flag)
i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
else
i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_poc = i4_temp_poc;
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice, ps_pps,
u1_nal_ref_idc,
u1_bottom_field_flag,
u1_field_pic_flag, &i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering + 1;
ps_dec->i4_max_poc = 0;
}
}
/*--------------------------------------------------------------------*/
/* Copy the values read from the bitstream to the slice header and then*/
/* If the slice is first slice in picture, then do Start of Picture */
/* processing. */
/*--------------------------------------------------------------------*/
ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0];
ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1];
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->u1_slice_type = u1_slice_type;
ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
if(ps_seq->u1_frame_mbs_only_flag)
ps_cur_slice->u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
else
ps_cur_slice->u1_direct_8x8_inference_flag = 1;
if(u1_slice_type == B_SLICE)
{
ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag",
ps_cur_slice->u1_direct_spatial_mv_pred_flag);
if(ps_cur_slice->u1_direct_spatial_mv_pred_flag)
ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct;
else
ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct;
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB;
}
else
{
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice == 0)
{
ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps);
if(ret != OK)
return ret;
}
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
/* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */
{
UWORD8 uc_nofield_nombaff;
uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0)
&& (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0)
&& (u1_slice_type != B_SLICE)
&& (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0));
/* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */
if(uc_nofield_nombaff)
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
}
else
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_mp;
}
}
/*
* Decide whether to decode the current picture or not
*/
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u4_frm_sei_sync == u2_frame_num)
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
}
ps_err->u4_cur_frm = u2_frame_num;
}
/* Decision for decoding if the picture is to be skipped */
{
WORD32 i4_skip_b_pic, i4_skip_p_pic;
i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT)
&& (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT)
&& (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
/**************************************************************/
/* Skip the B picture if skip mask is set for B picture and */
/* Current B picture is a non reference B picture or there is */
/* no user for reference B picture */
/**************************************************************/
if(i4_skip_b_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
/* Don't decode the picture in SKIP-B mode if that picture is B */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
/**************************************************************/
/* Skip the P picture if skip mask is set for P picture and */
/* Current P picture is a non reference P picture or there is */
/* no user for reference P picture */
/**************************************************************/
if(i4_skip_p_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
/* Don't decode the picture in SKIP-P mode if that picture is P */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
}
{
UWORD16 u2_mb_x, u2_mb_y;
ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice
<< ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE)
- SUB_BLK_SIZE;
if(u2_first_mb_in_slice)
{
UWORD8 u1_mb_aff;
UWORD8 u1_field_pic;
UWORD16 u2_frm_wd_in_mbs;
u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag;
u1_field_pic = ps_cur_slice->u1_field_pic_flag;
{
UWORD32 x_offset;
UWORD32 y_offset;
UWORD32 u4_frame_stride;
tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y <<= u1_mb_aff;
if((u2_mb_x > u2_frm_wd_in_mbs - 1)
|| (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1))
{
return ERROR_CORRUPTED_SLICE;
}
u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic;
x_offset = u2_mb_x << 4;
y_offset = (u2_mb_y * u4_frame_stride) << 4;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset
+ y_offset;
u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic;
x_offset >>= 1;
y_offset = (u2_mb_y * u4_frame_stride) << 3;
x_offset *= YUV420SP_FACTOR;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset
+ y_offset;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset
+ y_offset;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
if(ps_dec->u1_separate_parse == 1)
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
else
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff);
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv
+ ((u2_first_mb_in_slice << u1_mb_aff) << 4);
}
}
else
{
tfr_ctxt_t *ps_trns_addr;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = 0xffff;
u2_mb_y = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
}
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
}
/* RBSP stop bit is used for CABAC decoding*/
ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode;
ps_dec->u1_B = (u1_slice_type == B_SLICE);
ps_dec->u4_next_mb_skip = 0;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice =
ps_dec->ps_cur_slice->u2_first_mb_in_slice;
ps_dec->ps_parse_cur_slice->slice_type =
ps_dec->ps_cur_slice->u1_slice_type;
ps_dec->u4_start_recon_deblk = 1;
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf;
}
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
if(u1_slice_type == I_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT;
ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice);
if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE)
ps_dec->i4_pic_type = I_SLICE;
}
else if(u1_slice_type == P_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
if(ps_dec->i4_pic_type != B_SLICE)
ps_dec->i4_pic_type = P_SLICE;
}
else if(u1_slice_type == B_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
ps_dec->i4_pic_type = B_SLICE;
}
else
return ERROR_INV_SLC_TYPE_T;
if(ps_dec->u1_slice_header_done)
{
/* set to zero to indicate a valid slice has been decoded */
/* first slice header successfully decoded */
ps_dec->u4_first_slice_in_pic = 0;
ps_dec->u1_first_slice_in_stream = 0;
}
if(ret != OK)
return ret;
/* storing last Mb X and MbY of the slice */
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
/* End of Picture detection */
if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1))
{
ps_dec->u1_pic_decode_done = 1;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if((ps_err->u1_err_flag & REJECT_PB_PICS)
&& (ps_err->u1_cur_pic_type == PIC_TYPE_I))
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
PRINT_BIN_BIT_RATIO(ps_dec)
return ret;
}
Commit Message: Decoder: Return correct error code for slice header errors
Return ERROR_INV_SLICE_HDR_T instead of ERROR_INV_SPS_PPS_T for slice
header errors.
Bug: 34097915
Change-Id: I45d14a71f2322ff349058baaf65fb0f3c1140fba
CWE ID: | WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice,
UWORD8 u1_nal_ref_idc,
dec_struct_t *ps_dec /* Decoder parameters */
)
{
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
dec_pic_params_t *ps_pps;
dec_seq_params_t *ps_seq;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
pocstruct_t s_tmp_poc;
WORD32 i_delta_poc[2];
WORD32 i4_poc = 0;
UWORD16 u2_first_mb_in_slice, u2_frame_num;
UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type;
UWORD32 u4_idr_pic_id = 0;
UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type;
UWORD8 u1_nal_unit_type;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
WORD8 i1_is_end_of_poc;
WORD32 ret, end_of_frame;
WORD32 prev_slice_err, num_mb_skipped;
UWORD8 u1_mbaff;
pocstruct_t *ps_cur_poc;
UWORD32 u4_temp;
WORD32 i_temp;
UWORD32 u4_call_end_of_pic = 0;
/* read FirstMbInSlice and slice type*/
ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0;
u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u2_first_mb_in_slice
> (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs))
{
return ERROR_CORRUPTED_SLICE;
}
/*we currently don not support ASO*/
if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag)
<= ps_dec->u2_cur_mb_addr) && (ps_dec->u4_first_slice_in_pic == 0))
{
return ERROR_CORRUPTED_SLICE;
}
COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice);
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > 9)
return ERROR_INV_SLC_TYPE_T;
u1_slice_type = u4_temp;
COPYTHECONTEXT("SH: slice_type",(u1_slice_type));
ps_dec->u1_sl_typ_5_9 = 0;
/* Find Out the Slice Type is 5 to 9 or not then Set the Flag */
/* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/
/* will be of same type of current */
if(u1_slice_type > 4)
{
u1_slice_type -= 5;
ps_dec->u1_sl_typ_5_9 = 1;
}
{
UWORD32 skip;
if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB)
|| (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB))
{
UWORD32 u4_bit_stream_offset = 0;
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else if((I_SLICE == u1_slice_type)
&& (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames))
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else
{
skip = 1;
}
/* If one frame worth of data is already skipped, do not skip the next one */
if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped))
{
skip = 0;
}
if(skip)
{
ps_dec->u4_prev_nal_skipped = 1;
ps_dec->i4_dec_skip_mode = IVD_SKIP_PB;
return 0;
}
else
{
/* If the previous NAL was skipped, then
do not process that buffer in this call.
Return to app and process it in the next call.
This is necessary to handle cases where I/IDR is not complete in
the current buffer and application intends to fill the remaining part of the bitstream
later. This ensures we process only frame worth of data in every call */
if(1 == ps_dec->u4_prev_nal_skipped)
{
ps_dec->u4_return_to_app = 1;
return 0;
}
}
}
}
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp & MASK_ERR_PIC_SET_ID)
return ERROR_INV_SLICE_HDR_T;
/* discard slice if pic param is invalid */
COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp);
ps_pps = &ps_dec->ps_pps[u4_temp];
if(FALSE == ps_pps->u1_is_valid)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_seq = ps_pps->ps_sps;
if(!ps_seq)
return ERROR_INV_SLICE_HDR_T;
if(FALSE == ps_seq->u1_is_valid)
return ERROR_INV_SLICE_HDR_T;
/* Get the frame num */
u2_frame_num = ih264d_get_bits_h264(ps_bitstrm,
ps_seq->u1_bits_in_frm_num);
COPYTHECONTEXT("SH: frame_num", u2_frame_num);
/* Get the field related flags */
if(!ps_seq->u1_frame_mbs_only_flag)
{
u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag);
u1_bottom_field_flag = 0;
if(u1_field_pic_flag)
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld;
u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag);
}
else
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
}
else
{
u1_field_pic_flag = 0;
u1_bottom_field_flag = 0;
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
u1_nal_unit_type = SLICE_NAL;
if(u1_is_idr_slice)
{
if(0 == u1_field_pic_flag)
{
ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY;
}
u1_nal_unit_type = IDR_SLICE_NAL;
u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u4_idr_pic_id > 65535)
return ERROR_INV_SLICE_HDR_T;
COPYTHECONTEXT("SH: ", u4_idr_pic_id);
}
/* read delta pic order count information*/
i_delta_poc[0] = i_delta_poc[1] = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type;
if(u1_pic_order_cnt_type == 0)
{
i_temp = ih264d_get_bits_h264(
ps_bitstrm,
ps_seq->u1_log2_max_pic_order_cnt_lsb_minus);
if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb)
return ERROR_INV_SLICE_HDR_T;
s_tmp_poc.i4_pic_order_cnt_lsb = i_temp;
COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb);
if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom",
s_tmp_poc.i4_delta_pic_order_cnt_bottom);
}
}
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
if(u1_pic_order_cnt_type == 1
&& (!ps_seq->u1_delta_pic_order_always_zero_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[0]",
s_tmp_poc.i4_delta_pic_order_cnt[0]);
if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag)
{
s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[1]",
s_tmp_poc.i4_delta_pic_order_cnt[1]);
}
}
if(ps_pps->u1_redundant_pic_cnt_present_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_REDUNDANT_PIC_CNT)
return ERROR_INV_SLICE_HDR_T;
u1_redundant_pic_cnt = u4_temp;
COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt);
}
/*--------------------------------------------------------------------*/
/* Check if the slice is part of new picture */
/*--------------------------------------------------------------------*/
i1_is_end_of_poc = 0;
if(!ps_dec->u1_first_slice_in_stream)
{
i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc,
&s_tmp_poc, &ps_dec->s_cur_pic_poc,
ps_cur_slice, u1_pic_order_cnt_type,
u1_nal_unit_type, u4_idr_pic_id,
u1_field_pic_flag,
u1_bottom_field_flag);
/* since we support only Full frame decode, every new process should
* process a new pic
*/
if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0))
{
/* if it is the first slice is process call ,it should be a new frame. If it is not
* reject current pic and dont add it to dpb
*/
ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC;
i1_is_end_of_poc = 1;
}
else
{
/* reset REJECT_CUR_PIC */
ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC;
}
}
/*--------------------------------------------------------------------*/
/* Check for error in slice and parse the missing/corrupted MB's */
/* as skip-MB's in an inserted P-slice */
/*--------------------------------------------------------------------*/
u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag);
prev_slice_err = 0;
if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream)
{
if(u2_frame_num != ps_dec->u2_prv_frame_num
&& ps_dec->u1_top_bottom_decoded != 0
&& ps_dec->u1_top_bottom_decoded
!= (TOP_FIELD_ONLY | BOT_FIELD_ONLY))
{
ps_dec->u1_dangling_field = 1;
if(ps_dec->u4_first_slice_in_pic)
{
prev_slice_err = 1;
}
else
{
prev_slice_err = 2;
}
if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY)
ps_cur_slice->u1_bottom_field_flag = 1;
else
ps_cur_slice->u1_bottom_field_flag = 0;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL;
}
else if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice > 0)
{
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
ps_cur_poc = &s_tmp_poc;
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->i4_pic_order_cnt_lsb =
s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag
&& (!u1_field_pic_flag);
}
}
else
{
if(ps_dec->u4_first_slice_in_pic)
{
/* if valid slice header is not decoded do start of pic processing
* since in the current process call, frame num is not updated in the slice structure yet
* ih264d_is_end_of_pic is checked with valid frame num of previous process call,
* although i1_is_end_of_poc is set there could be more slices in the frame,
* so conceal only till cur slice */
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
}
else
{
/* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame
* completely */
prev_slice_err = 2;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
}
ps_cur_poc = &s_tmp_poc;
}
}
else
{
if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded)
{
prev_slice_err = 2;
num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &s_tmp_poc;
}
else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded)
{
return ERROR_CORRUPTED_SLICE;
}
}
if(prev_slice_err)
{
ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err);
if(ps_dec->u1_dangling_field == 1)
{
ps_dec->u1_second_field = 1 - ps_dec->u1_second_field;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_dec->u2_prv_frame_num = u2_frame_num;
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_DANGLING_FIELD_IN_PIC;
}
if(prev_slice_err == 2)
{
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_INCOMPLETE_FRAME;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
/* return if all MBs in frame are parsed*/
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_IN_LAST_SLICE_OF_PIC;
}
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
if(ret != OK)
return ret;
i1_is_end_of_poc = 0;
}
if (ps_dec->u4_first_slice_in_pic == 0)
{
ps_dec->ps_parse_cur_slice++;
ps_dec->u2_cur_slice_num++;
}
if((ps_dec->u1_separate_parse == 0) && (ps_dec->u4_first_slice_in_pic == 0))
{
ps_dec->ps_decode_cur_slice++;
}
ps_dec->u1_slice_header_done = 0;
/*--------------------------------------------------------------------*/
/* If the slice is part of new picture, do End of Pic processing. */
/*--------------------------------------------------------------------*/
if(!ps_dec->u1_first_slice_in_stream)
{
UWORD8 uc_mbs_exceed = 0;
if(ps_dec->u2_total_mbs_coded
== (ps_dec->ps_cur_sps->u2_max_mb_addr + 1))
{
/*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so
,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */
if(ps_dec->u4_first_slice_in_pic == 0)
uc_mbs_exceed = 1;
}
if(i1_is_end_of_poc || uc_mbs_exceed)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
#if WIN32
H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n");
#endif
return RET_LAST_SKIP;
}
else
{
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
}
}
}
if(u1_field_pic_flag)
{
ps_dec->u2_prv_frame_num = u2_frame_num;
}
if(ps_cur_slice->u1_mmco_equalto5)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair
{
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc =
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
}
else if(!ps_cur_slice->u1_bottom_field_flag)
i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
else
i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_poc = i4_temp_poc;
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice, ps_pps,
u1_nal_ref_idc,
u1_bottom_field_flag,
u1_field_pic_flag, &i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering + 1;
ps_dec->i4_max_poc = 0;
}
}
/*--------------------------------------------------------------------*/
/* Copy the values read from the bitstream to the slice header and then*/
/* If the slice is first slice in picture, then do Start of Picture */
/* processing. */
/*--------------------------------------------------------------------*/
ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0];
ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1];
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->u1_slice_type = u1_slice_type;
ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
if(ps_seq->u1_frame_mbs_only_flag)
ps_cur_slice->u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
else
ps_cur_slice->u1_direct_8x8_inference_flag = 1;
if(u1_slice_type == B_SLICE)
{
ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag",
ps_cur_slice->u1_direct_spatial_mv_pred_flag);
if(ps_cur_slice->u1_direct_spatial_mv_pred_flag)
ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct;
else
ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct;
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB;
}
else
{
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice == 0)
{
ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps);
if(ret != OK)
return ret;
}
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
/* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */
{
UWORD8 uc_nofield_nombaff;
uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0)
&& (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0)
&& (u1_slice_type != B_SLICE)
&& (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0));
/* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */
if(uc_nofield_nombaff)
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
}
else
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_mp;
}
}
/*
* Decide whether to decode the current picture or not
*/
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u4_frm_sei_sync == u2_frame_num)
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
}
ps_err->u4_cur_frm = u2_frame_num;
}
/* Decision for decoding if the picture is to be skipped */
{
WORD32 i4_skip_b_pic, i4_skip_p_pic;
i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT)
&& (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT)
&& (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
/**************************************************************/
/* Skip the B picture if skip mask is set for B picture and */
/* Current B picture is a non reference B picture or there is */
/* no user for reference B picture */
/**************************************************************/
if(i4_skip_b_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
/* Don't decode the picture in SKIP-B mode if that picture is B */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
/**************************************************************/
/* Skip the P picture if skip mask is set for P picture and */
/* Current P picture is a non reference P picture or there is */
/* no user for reference P picture */
/**************************************************************/
if(i4_skip_p_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
/* Don't decode the picture in SKIP-P mode if that picture is P */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
}
{
UWORD16 u2_mb_x, u2_mb_y;
ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice
<< ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE)
- SUB_BLK_SIZE;
if(u2_first_mb_in_slice)
{
UWORD8 u1_mb_aff;
UWORD8 u1_field_pic;
UWORD16 u2_frm_wd_in_mbs;
u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag;
u1_field_pic = ps_cur_slice->u1_field_pic_flag;
{
UWORD32 x_offset;
UWORD32 y_offset;
UWORD32 u4_frame_stride;
tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y <<= u1_mb_aff;
if((u2_mb_x > u2_frm_wd_in_mbs - 1)
|| (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1))
{
return ERROR_CORRUPTED_SLICE;
}
u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic;
x_offset = u2_mb_x << 4;
y_offset = (u2_mb_y * u4_frame_stride) << 4;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset
+ y_offset;
u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic;
x_offset >>= 1;
y_offset = (u2_mb_y * u4_frame_stride) << 3;
x_offset *= YUV420SP_FACTOR;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset
+ y_offset;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset
+ y_offset;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
if(ps_dec->u1_separate_parse == 1)
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
else
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff);
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv
+ ((u2_first_mb_in_slice << u1_mb_aff) << 4);
}
}
else
{
tfr_ctxt_t *ps_trns_addr;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = 0xffff;
u2_mb_y = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
}
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
}
/* RBSP stop bit is used for CABAC decoding*/
ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode;
ps_dec->u1_B = (u1_slice_type == B_SLICE);
ps_dec->u4_next_mb_skip = 0;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice =
ps_dec->ps_cur_slice->u2_first_mb_in_slice;
ps_dec->ps_parse_cur_slice->slice_type =
ps_dec->ps_cur_slice->u1_slice_type;
ps_dec->u4_start_recon_deblk = 1;
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf;
}
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
if(u1_slice_type == I_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT;
ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice);
if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE)
ps_dec->i4_pic_type = I_SLICE;
}
else if(u1_slice_type == P_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
if(ps_dec->i4_pic_type != B_SLICE)
ps_dec->i4_pic_type = P_SLICE;
}
else if(u1_slice_type == B_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
ps_dec->i4_pic_type = B_SLICE;
}
else
return ERROR_INV_SLC_TYPE_T;
if(ps_dec->u1_slice_header_done)
{
/* set to zero to indicate a valid slice has been decoded */
/* first slice header successfully decoded */
ps_dec->u4_first_slice_in_pic = 0;
ps_dec->u1_first_slice_in_stream = 0;
}
if(ret != OK)
return ret;
/* storing last Mb X and MbY of the slice */
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
/* End of Picture detection */
if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1))
{
ps_dec->u1_pic_decode_done = 1;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if((ps_err->u1_err_flag & REJECT_PB_PICS)
&& (ps_err->u1_cur_pic_type == PIC_TYPE_I))
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
PRINT_BIN_BIT_RATIO(ps_dec)
return ret;
}
| 174,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftVPXEncoder::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftVPXEncoder::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
| 174,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_ioctl_setattr(
xfs_inode_t *ip,
struct fsxattr *fa,
int mask)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_trans *tp;
unsigned int lock_flags = 0;
struct xfs_dquot *udqp = NULL;
struct xfs_dquot *pdqp = NULL;
struct xfs_dquot *olddquot = NULL;
int code;
trace_xfs_ioctl_setattr(ip);
if (mp->m_flags & XFS_MOUNT_RDONLY)
return XFS_ERROR(EROFS);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
/*
* Disallow 32bit project ids when projid32bit feature is not enabled.
*/
if ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) &&
!xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb))
return XFS_ERROR(EINVAL);
/*
* If disk quotas is on, we make sure that the dquots do exist on disk,
* before we start any other transactions. Trying to do this later
* is messy. We don't care to take a readlock to look at the ids
* in inode here, because we can't hold it across the trans_reserve.
* If the IDs do change before we take the ilock, we're covered
* because the i_*dquot fields will get updated anyway.
*/
if (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) {
code = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid,
ip->i_d.di_gid, fa->fsx_projid,
XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp);
if (code)
return code;
}
/*
* For the other attributes, we acquire the inode lock and
* first do an error checking pass.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE);
code = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0);
if (code)
goto error_return;
lock_flags = XFS_ILOCK_EXCL;
xfs_ilock(ip, lock_flags);
/*
* CAP_FOWNER overrides the following restrictions:
*
* The user ID of the calling process must be equal
* to the file owner ID, except in cases where the
* CAP_FSETID capability is applicable.
*/
if (!inode_owner_or_capable(VFS_I(ip))) {
code = XFS_ERROR(EPERM);
goto error_return;
}
/*
* Do a quota reservation only if projid is actually going to change.
* Only allow changing of projid from init_user_ns since it is a
* non user namespace aware identifier.
*/
if (mask & FSX_PROJID) {
if (current_user_ns() != &init_user_ns) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
if (XFS_IS_QUOTA_RUNNING(mp) &&
XFS_IS_PQUOTA_ON(mp) &&
xfs_get_projid(ip) != fa->fsx_projid) {
ASSERT(tp);
code = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL,
pdqp, capable(CAP_FOWNER) ?
XFS_QMOPT_FORCE_RES : 0);
if (code) /* out of quota */
goto error_return;
}
}
if (mask & FSX_EXTSIZE) {
/*
* Can't change extent size if any extents are allocated.
*/
if (ip->i_d.di_nextents &&
((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) !=
fa->fsx_extsize)) {
code = XFS_ERROR(EINVAL); /* EFBIG? */
goto error_return;
}
/*
* Extent size must be a multiple of the appropriate block
* size, if set at all. It must also be smaller than the
* maximum extent size supported by the filesystem.
*
* Also, for non-realtime files, limit the extent size hint to
* half the size of the AGs in the filesystem so alignment
* doesn't result in extents larger than an AG.
*/
if (fa->fsx_extsize != 0) {
xfs_extlen_t size;
xfs_fsblock_t extsize_fsb;
extsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize);
if (extsize_fsb > MAXEXTLEN) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
if (XFS_IS_REALTIME_INODE(ip) ||
((mask & FSX_XFLAGS) &&
(fa->fsx_xflags & XFS_XFLAG_REALTIME))) {
size = mp->m_sb.sb_rextsize <<
mp->m_sb.sb_blocklog;
} else {
size = mp->m_sb.sb_blocksize;
if (extsize_fsb > mp->m_sb.sb_agblocks / 2) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
if (fa->fsx_extsize % size) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
}
if (mask & FSX_XFLAGS) {
/*
* Can't change realtime flag if any extents are allocated.
*/
if ((ip->i_d.di_nextents || ip->i_delayed_blks) &&
(XFS_IS_REALTIME_INODE(ip)) !=
(fa->fsx_xflags & XFS_XFLAG_REALTIME)) {
code = XFS_ERROR(EINVAL); /* EFBIG? */
goto error_return;
}
/*
* If realtime flag is set then must have realtime data.
*/
if ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) {
if ((mp->m_sb.sb_rblocks == 0) ||
(mp->m_sb.sb_rextsize == 0) ||
(ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
/*
* Can't modify an immutable/append-only file unless
* we have appropriate permission.
*/
if ((ip->i_d.di_flags &
(XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) ||
(fa->fsx_xflags &
(XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) &&
!capable(CAP_LINUX_IMMUTABLE)) {
code = XFS_ERROR(EPERM);
goto error_return;
}
}
xfs_trans_ijoin(tp, ip, 0);
/*
* Change file ownership. Must be the owner or privileged.
*/
if (mask & FSX_PROJID) {
/*
* CAP_FSETID overrides the following restrictions:
*
* The set-user-ID and set-group-ID bits of a file will be
* cleared upon successful return from chown()
*/
if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) &&
!inode_capable(VFS_I(ip), CAP_FSETID))
ip->i_d.di_mode &= ~(S_ISUID|S_ISGID);
/*
* Change the ownerships and register quota modifications
* in the transaction.
*/
if (xfs_get_projid(ip) != fa->fsx_projid) {
if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) {
olddquot = xfs_qm_vop_chown(tp, ip,
&ip->i_pdquot, pdqp);
}
xfs_set_projid(ip, fa->fsx_projid);
/*
* We may have to rev the inode as well as
* the superblock version number since projids didn't
* exist before DINODE_VERSION_2 and SB_VERSION_NLINK.
*/
if (ip->i_d.di_version == 1)
xfs_bump_ino_vers2(tp, ip);
}
}
if (mask & FSX_EXTSIZE)
ip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog;
if (mask & FSX_XFLAGS) {
xfs_set_diflags(ip, fa->fsx_xflags);
xfs_diflags_to_linux(ip);
}
xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
XFS_STATS_INC(xs_ig_attrchg);
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
* This is slightly sub-optimal in that truncates require
* two sync transactions instead of one for wsync filesystems.
* One for the truncate and one for the timestamps since we
* don't want to change the timestamps unless we're sure the
* truncate worked. Truncates are less than 1% of the laddis
* mix so this probably isn't worth the trouble to optimize.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC)
xfs_trans_set_sync(tp);
code = xfs_trans_commit(tp, 0);
xfs_iunlock(ip, lock_flags);
/*
* Release any dquot(s) the inode had kept before chown.
*/
xfs_qm_dqrele(olddquot);
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(pdqp);
return code;
error_return:
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(pdqp);
xfs_trans_cancel(tp, 0);
if (lock_flags)
xfs_iunlock(ip, lock_flags);
return code;
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | xfs_ioctl_setattr(
xfs_inode_t *ip,
struct fsxattr *fa,
int mask)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_trans *tp;
unsigned int lock_flags = 0;
struct xfs_dquot *udqp = NULL;
struct xfs_dquot *pdqp = NULL;
struct xfs_dquot *olddquot = NULL;
int code;
trace_xfs_ioctl_setattr(ip);
if (mp->m_flags & XFS_MOUNT_RDONLY)
return XFS_ERROR(EROFS);
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
/*
* Disallow 32bit project ids when projid32bit feature is not enabled.
*/
if ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) &&
!xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb))
return XFS_ERROR(EINVAL);
/*
* If disk quotas is on, we make sure that the dquots do exist on disk,
* before we start any other transactions. Trying to do this later
* is messy. We don't care to take a readlock to look at the ids
* in inode here, because we can't hold it across the trans_reserve.
* If the IDs do change before we take the ilock, we're covered
* because the i_*dquot fields will get updated anyway.
*/
if (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) {
code = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid,
ip->i_d.di_gid, fa->fsx_projid,
XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp);
if (code)
return code;
}
/*
* For the other attributes, we acquire the inode lock and
* first do an error checking pass.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE);
code = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0);
if (code)
goto error_return;
lock_flags = XFS_ILOCK_EXCL;
xfs_ilock(ip, lock_flags);
/*
* CAP_FOWNER overrides the following restrictions:
*
* The user ID of the calling process must be equal
* to the file owner ID, except in cases where the
* CAP_FSETID capability is applicable.
*/
if (!inode_owner_or_capable(VFS_I(ip))) {
code = XFS_ERROR(EPERM);
goto error_return;
}
/*
* Do a quota reservation only if projid is actually going to change.
* Only allow changing of projid from init_user_ns since it is a
* non user namespace aware identifier.
*/
if (mask & FSX_PROJID) {
if (current_user_ns() != &init_user_ns) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
if (XFS_IS_QUOTA_RUNNING(mp) &&
XFS_IS_PQUOTA_ON(mp) &&
xfs_get_projid(ip) != fa->fsx_projid) {
ASSERT(tp);
code = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL,
pdqp, capable(CAP_FOWNER) ?
XFS_QMOPT_FORCE_RES : 0);
if (code) /* out of quota */
goto error_return;
}
}
if (mask & FSX_EXTSIZE) {
/*
* Can't change extent size if any extents are allocated.
*/
if (ip->i_d.di_nextents &&
((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) !=
fa->fsx_extsize)) {
code = XFS_ERROR(EINVAL); /* EFBIG? */
goto error_return;
}
/*
* Extent size must be a multiple of the appropriate block
* size, if set at all. It must also be smaller than the
* maximum extent size supported by the filesystem.
*
* Also, for non-realtime files, limit the extent size hint to
* half the size of the AGs in the filesystem so alignment
* doesn't result in extents larger than an AG.
*/
if (fa->fsx_extsize != 0) {
xfs_extlen_t size;
xfs_fsblock_t extsize_fsb;
extsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize);
if (extsize_fsb > MAXEXTLEN) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
if (XFS_IS_REALTIME_INODE(ip) ||
((mask & FSX_XFLAGS) &&
(fa->fsx_xflags & XFS_XFLAG_REALTIME))) {
size = mp->m_sb.sb_rextsize <<
mp->m_sb.sb_blocklog;
} else {
size = mp->m_sb.sb_blocksize;
if (extsize_fsb > mp->m_sb.sb_agblocks / 2) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
if (fa->fsx_extsize % size) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
}
if (mask & FSX_XFLAGS) {
/*
* Can't change realtime flag if any extents are allocated.
*/
if ((ip->i_d.di_nextents || ip->i_delayed_blks) &&
(XFS_IS_REALTIME_INODE(ip)) !=
(fa->fsx_xflags & XFS_XFLAG_REALTIME)) {
code = XFS_ERROR(EINVAL); /* EFBIG? */
goto error_return;
}
/*
* If realtime flag is set then must have realtime data.
*/
if ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) {
if ((mp->m_sb.sb_rblocks == 0) ||
(mp->m_sb.sb_rextsize == 0) ||
(ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) {
code = XFS_ERROR(EINVAL);
goto error_return;
}
}
/*
* Can't modify an immutable/append-only file unless
* we have appropriate permission.
*/
if ((ip->i_d.di_flags &
(XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) ||
(fa->fsx_xflags &
(XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) &&
!capable(CAP_LINUX_IMMUTABLE)) {
code = XFS_ERROR(EPERM);
goto error_return;
}
}
xfs_trans_ijoin(tp, ip, 0);
/*
* Change file ownership. Must be the owner or privileged.
*/
if (mask & FSX_PROJID) {
/*
* CAP_FSETID overrides the following restrictions:
*
* The set-user-ID and set-group-ID bits of a file will be
* cleared upon successful return from chown()
*/
if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) &&
!capable_wrt_inode_uidgid(VFS_I(ip), CAP_FSETID))
ip->i_d.di_mode &= ~(S_ISUID|S_ISGID);
/*
* Change the ownerships and register quota modifications
* in the transaction.
*/
if (xfs_get_projid(ip) != fa->fsx_projid) {
if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) {
olddquot = xfs_qm_vop_chown(tp, ip,
&ip->i_pdquot, pdqp);
}
xfs_set_projid(ip, fa->fsx_projid);
/*
* We may have to rev the inode as well as
* the superblock version number since projids didn't
* exist before DINODE_VERSION_2 and SB_VERSION_NLINK.
*/
if (ip->i_d.di_version == 1)
xfs_bump_ino_vers2(tp, ip);
}
}
if (mask & FSX_EXTSIZE)
ip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog;
if (mask & FSX_XFLAGS) {
xfs_set_diflags(ip, fa->fsx_xflags);
xfs_diflags_to_linux(ip);
}
xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
XFS_STATS_INC(xs_ig_attrchg);
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
* This is slightly sub-optimal in that truncates require
* two sync transactions instead of one for wsync filesystems.
* One for the truncate and one for the timestamps since we
* don't want to change the timestamps unless we're sure the
* truncate worked. Truncates are less than 1% of the laddis
* mix so this probably isn't worth the trouble to optimize.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC)
xfs_trans_set_sync(tp);
code = xfs_trans_commit(tp, 0);
xfs_iunlock(ip, lock_flags);
/*
* Release any dquot(s) the inode had kept before chown.
*/
xfs_qm_dqrele(olddquot);
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(pdqp);
return code;
error_return:
xfs_qm_dqrele(udqp);
xfs_qm_dqrele(pdqp);
xfs_trans_cancel(tp, 0);
if (lock_flags)
xfs_iunlock(ip, lock_flags);
return code;
}
| 166,322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.