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: void xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
memcpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
Commit Message: Do not copy more bytes than were allocated
CWE ID: CWE-119 | void xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
s->append_char(s, 0);
strncpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
| 167,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int omx_venc::async_message_process (void *context, void* message)
{
omx_video* omx = NULL;
struct venc_msg *m_sVenc_msg = NULL;
OMX_BUFFERHEADERTYPE* omxhdr = NULL;
struct venc_buffer *temp_buff = NULL;
if (context == NULL || message == NULL) {
DEBUG_PRINT_ERROR("ERROR: omx_venc::async_message_process invalid i/p params");
return -1;
}
m_sVenc_msg = (struct venc_msg *)message;
omx = reinterpret_cast<omx_video*>(context);
if (m_sVenc_msg->statuscode != VEN_S_SUCCESS) {
DEBUG_PRINT_ERROR("ERROR: async_msg_process() - Error statuscode = %lu",
m_sVenc_msg->statuscode);
if(m_sVenc_msg->msgcode == VEN_MSG_HW_OVERLOAD) {
omx->omx_report_hw_overload();
} else
omx->omx_report_error();
}
DEBUG_PRINT_LOW("omx_venc::async_message_process- msgcode = %lu",
m_sVenc_msg->msgcode);
switch (m_sVenc_msg->msgcode) {
case VEN_MSG_START:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_START_DONE);
break;
case VEN_MSG_STOP:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_STOP_DONE);
break;
case VEN_MSG_RESUME:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_RESUME_DONE);
break;
case VEN_MSG_PAUSE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_PAUSE_DONE);
break;
case VEN_MSG_FLUSH_INPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_INPUT_FLUSH);
break;
case VEN_MSG_FLUSH_OUPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_OUTPUT_FLUSH);
break;
case VEN_MSG_INPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE* )\
m_sVenc_msg->buf.clientdata;
if (omxhdr == NULL ||
(((OMX_U32)(omxhdr - omx->m_inp_mem_ptr) > omx->m_sInPortDef.nBufferCountActual) &&
((OMX_U32)(omxhdr - omx->meta_buffer_hdr) > omx->m_sInPortDef.nBufferCountActual))) {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
#ifdef _ANDROID_ICS_
omx->omx_release_meta_buffer(omxhdr);
#endif
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_EBD);
break;
case VEN_MSG_OUTPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE*)m_sVenc_msg->buf.clientdata;
if ( (omxhdr != NULL) &&
((OMX_U32)(omxhdr - omx->m_out_mem_ptr) < omx->m_sOutPortDef.nBufferCountActual)) {
if (m_sVenc_msg->buf.len <= omxhdr->nAllocLen) {
omxhdr->nFilledLen = m_sVenc_msg->buf.len;
omxhdr->nOffset = m_sVenc_msg->buf.offset;
omxhdr->nTimeStamp = m_sVenc_msg->buf.timestamp;
DEBUG_PRINT_LOW("o/p TS = %u", (unsigned int)m_sVenc_msg->buf.timestamp);
omxhdr->nFlags = m_sVenc_msg->buf.flags;
/*Use buffer case*/
if (omx->output_use_buffer && !omx->m_use_output_pmem) {
DEBUG_PRINT_LOW("memcpy() for o/p Heap UseBuffer");
memcpy(omxhdr->pBuffer,
(m_sVenc_msg->buf.ptrbuffer),
m_sVenc_msg->buf.len);
}
} else {
omxhdr->nFilledLen = 0;
}
} else {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_FBD);
break;
case VEN_MSG_NEED_OUTPUT_BUFFER:
break;
#ifndef _MSM8974_
case VEN_MSG_LTRUSE_FAILED:
DEBUG_PRINT_ERROR("LTRUSE Failed!");
omx->post_event (NULL,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_LTRUSE_FAILED);
break;
#endif
default:
DEBUG_PRINT_HIGH("Unknown msg received : %lu", m_sVenc_msg->msgcode);
break;
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | int omx_venc::async_message_process (void *context, void* message)
{
omx_video* omx = NULL;
struct venc_msg *m_sVenc_msg = NULL;
OMX_BUFFERHEADERTYPE* omxhdr = NULL;
struct venc_buffer *temp_buff = NULL;
if (context == NULL || message == NULL) {
DEBUG_PRINT_ERROR("ERROR: omx_venc::async_message_process invalid i/p params");
return -1;
}
m_sVenc_msg = (struct venc_msg *)message;
omx = reinterpret_cast<omx_video*>(context);
if (m_sVenc_msg->statuscode != VEN_S_SUCCESS) {
DEBUG_PRINT_ERROR("ERROR: async_msg_process() - Error statuscode = %lu",
m_sVenc_msg->statuscode);
if(m_sVenc_msg->msgcode == VEN_MSG_HW_OVERLOAD) {
omx->omx_report_hw_overload();
} else
omx->omx_report_error();
}
DEBUG_PRINT_LOW("omx_venc::async_message_process- msgcode = %lu",
m_sVenc_msg->msgcode);
switch (m_sVenc_msg->msgcode) {
case VEN_MSG_START:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_START_DONE);
break;
case VEN_MSG_STOP:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_STOP_DONE);
break;
case VEN_MSG_RESUME:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_RESUME_DONE);
break;
case VEN_MSG_PAUSE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_PAUSE_DONE);
break;
case VEN_MSG_FLUSH_INPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_INPUT_FLUSH);
break;
case VEN_MSG_FLUSH_OUPUT_DONE:
omx->post_event (0,m_sVenc_msg->statuscode,\
OMX_COMPONENT_GENERATE_EVENT_OUTPUT_FLUSH);
break;
case VEN_MSG_INPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE* )\
m_sVenc_msg->buf.clientdata;
if (omxhdr == NULL ||
(((OMX_U32)(omxhdr - omx->m_inp_mem_ptr) > omx->m_sInPortDef.nBufferCountActual) &&
((OMX_U32)(omxhdr - omx->meta_buffer_hdr) > omx->m_sInPortDef.nBufferCountActual))) {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
#ifdef _ANDROID_ICS_
omx->omx_release_meta_buffer(omxhdr);
#endif
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_EBD);
break;
case VEN_MSG_OUTPUT_BUFFER_DONE:
omxhdr = (OMX_BUFFERHEADERTYPE*)m_sVenc_msg->buf.clientdata;
if ( (omxhdr != NULL) &&
((OMX_U32)(omxhdr - omx->m_out_mem_ptr) < omx->m_sOutPortDef.nBufferCountActual)) {
if (m_sVenc_msg->buf.len <= omxhdr->nAllocLen) {
omxhdr->nFilledLen = m_sVenc_msg->buf.len;
omxhdr->nOffset = m_sVenc_msg->buf.offset;
omxhdr->nTimeStamp = m_sVenc_msg->buf.timestamp;
DEBUG_PRINT_LOW("o/p TS = %u", (unsigned int)m_sVenc_msg->buf.timestamp);
omxhdr->nFlags = m_sVenc_msg->buf.flags;
/*Use buffer case*/
if (omx->output_use_buffer && !omx->m_use_output_pmem && !omx->is_secure_session()) {
DEBUG_PRINT_LOW("memcpy() for o/p Heap UseBuffer");
memcpy(omxhdr->pBuffer,
(m_sVenc_msg->buf.ptrbuffer),
m_sVenc_msg->buf.len);
}
} else {
omxhdr->nFilledLen = 0;
}
} else {
omxhdr = NULL;
m_sVenc_msg->statuscode = VEN_S_EFAIL;
}
omx->post_event ((unsigned long)omxhdr,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_FBD);
break;
case VEN_MSG_NEED_OUTPUT_BUFFER:
break;
#ifndef _MSM8974_
case VEN_MSG_LTRUSE_FAILED:
DEBUG_PRINT_ERROR("LTRUSE Failed!");
omx->post_event (NULL,m_sVenc_msg->statuscode,
OMX_COMPONENT_GENERATE_LTRUSE_FAILED);
break;
#endif
default:
DEBUG_PRINT_HIGH("Unknown msg received : %lu", m_sVenc_msg->msgcode);
break;
}
return 0;
}
| 173,505 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCacheUpdateJob::StartUpdate(AppCacheHost* host,
const GURL& new_master_resource) {
DCHECK(group_->update_job() == this);
DCHECK(!group_->is_obsolete());
bool is_new_pending_master_entry = false;
if (!new_master_resource.is_empty()) {
DCHECK(new_master_resource == host->pending_master_entry_url());
DCHECK(!new_master_resource.has_ref());
DCHECK(new_master_resource.GetOrigin() == manifest_url_.GetOrigin());
if (IsTerminating()) {
group_->QueueUpdate(host, new_master_resource);
return;
}
std::pair<PendingMasters::iterator, bool> ret =
pending_master_entries_.insert(
PendingMasters::value_type(new_master_resource, PendingHosts()));
is_new_pending_master_entry = ret.second;
ret.first->second.push_back(host);
host->AddObserver(this);
}
AppCacheGroup::UpdateAppCacheStatus update_status = group_->update_status();
if (update_status == AppCacheGroup::CHECKING ||
update_status == AppCacheGroup::DOWNLOADING) {
if (host) {
NotifySingleHost(host, APPCACHE_CHECKING_EVENT);
if (update_status == AppCacheGroup::DOWNLOADING)
NotifySingleHost(host, APPCACHE_DOWNLOADING_EVENT);
if (!new_master_resource.is_empty()) {
AddMasterEntryToFetchList(host, new_master_resource,
is_new_pending_master_entry);
}
}
return;
}
MadeProgress();
group_->SetUpdateAppCacheStatus(AppCacheGroup::CHECKING);
if (group_->HasCache()) {
base::TimeDelta kFullUpdateInterval = base::TimeDelta::FromHours(24);
update_type_ = UPGRADE_ATTEMPT;
base::TimeDelta time_since_last_check =
base::Time::Now() - group_->last_full_update_check_time();
doing_full_update_check_ = time_since_last_check > kFullUpdateInterval;
NotifyAllAssociatedHosts(APPCACHE_CHECKING_EVENT);
} else {
update_type_ = CACHE_ATTEMPT;
doing_full_update_check_ = true;
DCHECK(host);
NotifySingleHost(host, APPCACHE_CHECKING_EVENT);
}
if (!new_master_resource.is_empty()) {
AddMasterEntryToFetchList(host, new_master_resource,
is_new_pending_master_entry);
}
BrowserThread::PostAfterStartupTask(
FROM_HERE, base::ThreadTaskRunnerHandle::Get(),
base::Bind(&AppCacheUpdateJob::FetchManifest, weak_factory_.GetWeakPtr(),
true));
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID: | void AppCacheUpdateJob::StartUpdate(AppCacheHost* host,
const GURL& new_master_resource) {
DCHECK(group_->update_job() == this);
DCHECK(!group_->is_obsolete());
bool is_new_pending_master_entry = false;
if (!new_master_resource.is_empty()) {
DCHECK(new_master_resource == host->pending_master_entry_url());
DCHECK(!new_master_resource.has_ref());
DCHECK(new_master_resource.GetOrigin() == manifest_url_.GetOrigin());
if (ContainsKey(failed_master_entries_, new_master_resource))
return;
if (IsTerminating()) {
group_->QueueUpdate(host, new_master_resource);
return;
}
std::pair<PendingMasters::iterator, bool> ret =
pending_master_entries_.insert(
PendingMasters::value_type(new_master_resource, PendingHosts()));
is_new_pending_master_entry = ret.second;
ret.first->second.push_back(host);
host->AddObserver(this);
}
AppCacheGroup::UpdateAppCacheStatus update_status = group_->update_status();
if (update_status == AppCacheGroup::CHECKING ||
update_status == AppCacheGroup::DOWNLOADING) {
if (host) {
NotifySingleHost(host, APPCACHE_CHECKING_EVENT);
if (update_status == AppCacheGroup::DOWNLOADING)
NotifySingleHost(host, APPCACHE_DOWNLOADING_EVENT);
if (!new_master_resource.is_empty()) {
AddMasterEntryToFetchList(host, new_master_resource,
is_new_pending_master_entry);
}
}
return;
}
MadeProgress();
group_->SetUpdateAppCacheStatus(AppCacheGroup::CHECKING);
if (group_->HasCache()) {
base::TimeDelta kFullUpdateInterval = base::TimeDelta::FromHours(24);
update_type_ = UPGRADE_ATTEMPT;
base::TimeDelta time_since_last_check =
base::Time::Now() - group_->last_full_update_check_time();
doing_full_update_check_ = time_since_last_check > kFullUpdateInterval;
NotifyAllAssociatedHosts(APPCACHE_CHECKING_EVENT);
} else {
update_type_ = CACHE_ATTEMPT;
doing_full_update_check_ = true;
DCHECK(host);
NotifySingleHost(host, APPCACHE_CHECKING_EVENT);
}
if (!new_master_resource.is_empty()) {
AddMasterEntryToFetchList(host, new_master_resource,
is_new_pending_master_entry);
}
BrowserThread::PostAfterStartupTask(
FROM_HERE, base::ThreadTaskRunnerHandle::Get(),
base::Bind(&AppCacheUpdateJob::FetchManifest, weak_factory_.GetWeakPtr(),
true));
}
| 171,733 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);
switch(type) {
case EVP_CTRL_INIT:
if (actx == NULL)
actx = ctx->cipher_data
= OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());
if (actx == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);
return 0;
}
actx->len.aad = 0;
actx->len.text = 0;
actx->aad = 0;
actx->mac_inited = 0;
actx->tag_len = 0;
actx->nonce_len = 12;
actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
return 1;
case EVP_CTRL_COPY:
if (actx) {
EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;
dst->cipher_data =
OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());
if (dst->cipher_data == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);
return 0;
}
}
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0 || arg > CHACHA_CTR_SIZE)
return 0;
actx->nonce_len = arg;
return 1;
case EVP_CTRL_AEAD_SET_IV_FIXED:
if (arg != 12)
return 0;
actx->nonce[0] = actx->key.counter[1]
= CHACHA_U8TOU32((unsigned char *)ptr);
actx->nonce[1] = actx->key.counter[2]
= CHACHA_U8TOU32((unsigned char *)ptr+4);
actx->nonce[2] = actx->key.counter[3]
= CHACHA_U8TOU32((unsigned char *)ptr+8);
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)
return 0;
if (ptr != NULL) {
memcpy(actx->tag, ptr, arg);
actx->tag_len = arg;
}
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)
return 0;
memcpy(ptr, actx->tag, arg);
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
{
unsigned int len;
unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];
len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |
aad[EVP_AEAD_TLS1_AAD_LEN - 1];
if (!ctx->encrypt) {
len -= POLY1305_BLOCK_SIZE; /* discount attached tag */
memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);
aad = temp;
temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);
temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;
}
actx->tls_payload_length = len;
/*
* merge record sequence number as per
* draft-ietf-tls-chacha20-poly1305-03
*/
actx->key.counter[1] = actx->nonce[0];
actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);
actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);
actx->mac_inited = 0;
chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);
return POLY1305_BLOCK_SIZE; /* tag length */
}
case EVP_CTRL_AEAD_SET_MAC_KEY:
/* no-op */
return 1;
default:
return -1;
}
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125 | static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
void *ptr)
{
EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx);
switch(type) {
case EVP_CTRL_INIT:
if (actx == NULL)
actx = ctx->cipher_data
= OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size());
if (actx == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR);
return 0;
}
actx->len.aad = 0;
actx->len.text = 0;
actx->aad = 0;
actx->mac_inited = 0;
actx->tag_len = 0;
actx->nonce_len = 12;
actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
return 1;
case EVP_CTRL_COPY:
if (actx) {
EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr;
dst->cipher_data =
OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size());
if (dst->cipher_data == NULL) {
EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR);
return 0;
}
}
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0 || arg > CHACHA_CTR_SIZE)
return 0;
actx->nonce_len = arg;
return 1;
case EVP_CTRL_AEAD_SET_IV_FIXED:
if (arg != 12)
return 0;
actx->nonce[0] = actx->key.counter[1]
= CHACHA_U8TOU32((unsigned char *)ptr);
actx->nonce[1] = actx->key.counter[2]
= CHACHA_U8TOU32((unsigned char *)ptr+4);
actx->nonce[2] = actx->key.counter[3]
= CHACHA_U8TOU32((unsigned char *)ptr+8);
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE)
return 0;
if (ptr != NULL) {
memcpy(actx->tag, ptr, arg);
actx->tag_len = arg;
}
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt)
return 0;
memcpy(ptr, actx->tag, arg);
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
{
unsigned int len;
unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE];
len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 |
aad[EVP_AEAD_TLS1_AAD_LEN - 1];
if (!ctx->encrypt) {
if (len < POLY1305_BLOCK_SIZE)
return 0;
len -= POLY1305_BLOCK_SIZE; /* discount attached tag */
memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2);
aad = temp;
temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8);
temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len;
}
actx->tls_payload_length = len;
/*
* merge record sequence number as per RFC7905
*/
actx->key.counter[1] = actx->nonce[0];
actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad);
actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4);
actx->mac_inited = 0;
chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN);
return POLY1305_BLOCK_SIZE; /* tag length */
}
case EVP_CTRL_AEAD_SET_MAC_KEY:
/* no-op */
return 1;
default:
return -1;
}
}
| 168,432 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
char *buffer;
unsigned short use_sg;
int retvalue = 0, transfer_len = 0;
unsigned long flags;
struct CMD_MESSAGE_FIELD *pcmdmessagefld;
uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |
(uint32_t)cmd->cmnd[6] << 16 |
(uint32_t)cmd->cmnd[7] << 8 |
(uint32_t)cmd->cmnd[8];
struct scatterlist *sg;
use_sg = scsi_sg_count(cmd);
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
if (use_sg > 1) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
transfer_len += sg->length;
if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__);
goto message_out;
}
pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;
switch (controlcode) {
case ARCMSR_MESSAGE_READ_RQBUFFER: {
unsigned char *ver_addr;
uint8_t *ptmpQbuffer;
uint32_t allxfer_len = 0;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: memory not enough!\n", __func__);
goto message_out;
}
ptmpQbuffer = ver_addr;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {
unsigned int tail = acb->rqbuf_getIndex;
unsigned int head = acb->rqbuf_putIndex;
unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);
allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);
if (allxfer_len > ARCMSR_API_DATA_BUFLEN)
allxfer_len = ARCMSR_API_DATA_BUFLEN;
if (allxfer_len <= cnt_to_end)
memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);
else {
memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);
memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);
}
acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;
}
memcpy(pcmdmessagefld->messagedatabuffer, ver_addr,
allxfer_len);
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
struct QBUFFER __iomem *prbuffer;
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
prbuffer = arcmsr_get_iop_rqbuffer(acb);
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
}
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
kfree(ver_addr);
pcmdmessagefld->cmdmessage.Length = allxfer_len;
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_WRITE_WQBUFFER: {
unsigned char *ver_addr;
int32_t user_len, cnt2end;
uint8_t *pQbuffer, *ptmpuserbuffer;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
ptmpuserbuffer = ver_addr;
user_len = pcmdmessagefld->cmdmessage.Length;
memcpy(ptmpuserbuffer,
pcmdmessagefld->messagedatabuffer, user_len);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {
struct SENSE_DATA *sensebuffer =
(struct SENSE_DATA *)cmd->sense_buffer;
arcmsr_write_ioctldata2iop(acb);
/* has error report sensedata */
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->SenseKey = ILLEGAL_REQUEST;
sensebuffer->AdditionalSenseLength = 0x0A;
sensebuffer->AdditionalSenseCode = 0x20;
sensebuffer->Valid = 1;
retvalue = ARCMSR_MESSAGE_FAIL;
} else {
pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];
cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;
if (user_len > cnt2end) {
memcpy(pQbuffer, ptmpuserbuffer, cnt2end);
ptmpuserbuffer += cnt2end;
user_len -= cnt2end;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
}
memcpy(pQbuffer, ptmpuserbuffer, user_len);
acb->wqbuf_putIndex += user_len;
acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {
acb->acb_flags &=
~ACB_F_MESSAGE_WQBUFFER_CLEARED;
arcmsr_write_ioctldata2iop(acb);
}
}
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
kfree(ver_addr);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_RQBUFFER: {
uint8_t *pQbuffer = acb->rqbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_WQBUFFER: {
uint8_t *pQbuffer = acb->wqbuffer;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {
uint8_t *pQbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
pQbuffer = acb->rqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_RETURN_CODE_3F: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_3F;
break;
}
case ARCMSR_MESSAGE_SAY_HELLO: {
int8_t *hello_string = "Hello! I am ARCMSR";
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
memcpy(pcmdmessagefld->messagedatabuffer,
hello_string, (int16_t)strlen(hello_string));
break;
}
case ARCMSR_MESSAGE_SAY_GOODBYE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_iop_parking(acb);
break;
}
case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_flush_adapter_cache(acb);
break;
}
default:
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: unknown controlcode!\n", __func__);
}
message_out:
if (use_sg) {
struct scatterlist *sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
}
return retvalue;
}
Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer()
We need to put an upper bound on "user_len" so the memcpy() doesn't
overflow.
Cc: <[email protected]>
Reported-by: Marco Grassi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Tomas Henzl <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-119 | static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
char *buffer;
unsigned short use_sg;
int retvalue = 0, transfer_len = 0;
unsigned long flags;
struct CMD_MESSAGE_FIELD *pcmdmessagefld;
uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |
(uint32_t)cmd->cmnd[6] << 16 |
(uint32_t)cmd->cmnd[7] << 8 |
(uint32_t)cmd->cmnd[8];
struct scatterlist *sg;
use_sg = scsi_sg_count(cmd);
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
if (use_sg > 1) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
transfer_len += sg->length;
if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__);
goto message_out;
}
pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;
switch (controlcode) {
case ARCMSR_MESSAGE_READ_RQBUFFER: {
unsigned char *ver_addr;
uint8_t *ptmpQbuffer;
uint32_t allxfer_len = 0;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: memory not enough!\n", __func__);
goto message_out;
}
ptmpQbuffer = ver_addr;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {
unsigned int tail = acb->rqbuf_getIndex;
unsigned int head = acb->rqbuf_putIndex;
unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);
allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);
if (allxfer_len > ARCMSR_API_DATA_BUFLEN)
allxfer_len = ARCMSR_API_DATA_BUFLEN;
if (allxfer_len <= cnt_to_end)
memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);
else {
memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);
memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);
}
acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;
}
memcpy(pcmdmessagefld->messagedatabuffer, ver_addr,
allxfer_len);
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
struct QBUFFER __iomem *prbuffer;
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
prbuffer = arcmsr_get_iop_rqbuffer(acb);
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
}
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
kfree(ver_addr);
pcmdmessagefld->cmdmessage.Length = allxfer_len;
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_WRITE_WQBUFFER: {
unsigned char *ver_addr;
uint32_t user_len;
int32_t cnt2end;
uint8_t *pQbuffer, *ptmpuserbuffer;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
ptmpuserbuffer = ver_addr;
user_len = pcmdmessagefld->cmdmessage.Length;
if (user_len > ARCMSR_API_DATA_BUFLEN) {
retvalue = ARCMSR_MESSAGE_FAIL;
kfree(ver_addr);
goto message_out;
}
memcpy(ptmpuserbuffer,
pcmdmessagefld->messagedatabuffer, user_len);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {
struct SENSE_DATA *sensebuffer =
(struct SENSE_DATA *)cmd->sense_buffer;
arcmsr_write_ioctldata2iop(acb);
/* has error report sensedata */
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->SenseKey = ILLEGAL_REQUEST;
sensebuffer->AdditionalSenseLength = 0x0A;
sensebuffer->AdditionalSenseCode = 0x20;
sensebuffer->Valid = 1;
retvalue = ARCMSR_MESSAGE_FAIL;
} else {
pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];
cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;
if (user_len > cnt2end) {
memcpy(pQbuffer, ptmpuserbuffer, cnt2end);
ptmpuserbuffer += cnt2end;
user_len -= cnt2end;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
}
memcpy(pQbuffer, ptmpuserbuffer, user_len);
acb->wqbuf_putIndex += user_len;
acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {
acb->acb_flags &=
~ACB_F_MESSAGE_WQBUFFER_CLEARED;
arcmsr_write_ioctldata2iop(acb);
}
}
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
kfree(ver_addr);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_RQBUFFER: {
uint8_t *pQbuffer = acb->rqbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_WQBUFFER: {
uint8_t *pQbuffer = acb->wqbuffer;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {
uint8_t *pQbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
pQbuffer = acb->rqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_RETURN_CODE_3F: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_3F;
break;
}
case ARCMSR_MESSAGE_SAY_HELLO: {
int8_t *hello_string = "Hello! I am ARCMSR";
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
memcpy(pcmdmessagefld->messagedatabuffer,
hello_string, (int16_t)strlen(hello_string));
break;
}
case ARCMSR_MESSAGE_SAY_GOODBYE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_iop_parking(acb);
break;
}
case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_flush_adapter_cache(acb);
break;
}
default:
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: unknown controlcode!\n", __func__);
}
message_out:
if (use_sg) {
struct scatterlist *sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
}
return retvalue;
}
| 166,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GBool SplashFTFont::makeGlyph(int c, int xFrac, int yFrac,
SplashGlyphBitmap *bitmap, int x0, int y0, SplashClip *clip, SplashClipResult *clipRes) {
SplashFTFontFile *ff;
FT_Vector offset;
FT_GlyphSlot slot;
FT_UInt gid;
int rowSize;
Guchar *p, *q;
int i;
ff = (SplashFTFontFile *)fontFile;
ff->face->size = sizeObj;
offset.x = (FT_Pos)(int)((SplashCoord)xFrac * splashFontFractionMul * 64);
offset.y = 0;
FT_Set_Transform(ff->face, &matrix, &offset);
slot = ff->face->glyph;
if (ff->codeToGID && c < ff->codeToGIDLen) {
gid = (FT_UInt)ff->codeToGID[c];
} else {
gid = (FT_UInt)c;
}
if (ff->trueType && gid == 0) {
return gFalse;
}
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) {
return gFalse;
}
#else
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP
: FT_LOAD_DEFAULT)) {
return gFalse;
}
#endif
FT_Glyph_Metrics *glyphMetrics = &(ff->face->glyph->metrics);
bitmap->x = splashRound(-glyphMetrics->horiBearingX / 64.0);
bitmap->y = splashRound(glyphMetrics->horiBearingY / 64.0);
bitmap->w = splashRound(glyphMetrics->width / 64.0);
bitmap->h = splashRound(glyphMetrics->height / 64.0);
*clipRes = clip->testRect(x0 - bitmap->x,
y0 - bitmap->y,
x0 - bitmap->x + bitmap->w,
y0 - bitmap->y + bitmap->h);
if (*clipRes == splashClipAllOutside) {
bitmap->freeData = gFalse;
return gTrue;
}
if (FT_Render_Glyph(slot, aa ? ft_render_mode_normal
: ft_render_mode_mono)) {
return gFalse;
}
bitmap->x = -slot->bitmap_left;
bitmap->y = slot->bitmap_top;
bitmap->w = slot->bitmap.width;
bitmap->h = slot->bitmap.rows;
bitmap->aa = aa;
if (aa) {
rowSize = bitmap->w;
} else {
rowSize = (bitmap->w + 7) >> 3;
}
bitmap->data = (Guchar *)gmalloc(rowSize * bitmap->h);
bitmap->freeData = gTrue;
for (i = 0, p = bitmap->data, q = slot->bitmap.buffer;
i < bitmap->h;
++i, p += rowSize, q += slot->bitmap.pitch) {
memcpy(p, q, rowSize);
}
return gTrue;
}
Commit Message:
CWE ID: CWE-189 | GBool SplashFTFont::makeGlyph(int c, int xFrac, int yFrac,
SplashGlyphBitmap *bitmap, int x0, int y0, SplashClip *clip, SplashClipResult *clipRes) {
SplashFTFontFile *ff;
FT_Vector offset;
FT_GlyphSlot slot;
FT_UInt gid;
int rowSize;
Guchar *p, *q;
int i;
ff = (SplashFTFontFile *)fontFile;
ff->face->size = sizeObj;
offset.x = (FT_Pos)(int)((SplashCoord)xFrac * splashFontFractionMul * 64);
offset.y = 0;
FT_Set_Transform(ff->face, &matrix, &offset);
slot = ff->face->glyph;
if (ff->codeToGID && c < ff->codeToGIDLen) {
gid = (FT_UInt)ff->codeToGID[c];
} else {
gid = (FT_UInt)c;
}
if (ff->trueType && gid == 0) {
return gFalse;
}
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) {
return gFalse;
}
#else
if (FT_Load_Glyph(ff->face, gid,
aa ? FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP
: FT_LOAD_DEFAULT)) {
return gFalse;
}
#endif
FT_Glyph_Metrics *glyphMetrics = &(ff->face->glyph->metrics);
bitmap->x = splashRound(-glyphMetrics->horiBearingX / 64.0);
bitmap->y = splashRound(glyphMetrics->horiBearingY / 64.0);
bitmap->w = splashRound(glyphMetrics->width / 64.0);
bitmap->h = splashRound(glyphMetrics->height / 64.0);
*clipRes = clip->testRect(x0 - bitmap->x,
y0 - bitmap->y,
x0 - bitmap->x + bitmap->w,
y0 - bitmap->y + bitmap->h);
if (*clipRes == splashClipAllOutside) {
bitmap->freeData = gFalse;
return gTrue;
}
if (FT_Render_Glyph(slot, aa ? ft_render_mode_normal
: ft_render_mode_mono)) {
return gFalse;
}
bitmap->x = -slot->bitmap_left;
bitmap->y = slot->bitmap_top;
bitmap->w = slot->bitmap.width;
bitmap->h = slot->bitmap.rows;
bitmap->aa = aa;
if (aa) {
rowSize = bitmap->w;
} else {
rowSize = (bitmap->w + 7) >> 3;
}
bitmap->data = (Guchar *)gmallocn(rowSize, bitmap->h);
bitmap->freeData = gTrue;
for (i = 0, p = bitmap->data, q = slot->bitmap.buffer;
i < bitmap->h;
++i, p += rowSize, q += slot->bitmap.pitch) {
memcpy(p, q, rowSize);
}
return gTrue;
}
| 164,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
m_exceptionCode = AbortError;
abortError();
return;
}
if (error.isTimeout()) {
didTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
m_exceptionCode = NetworkError;
networkError();
}
Commit Message: Don't dispatch events when XHR is set to sync mode
Any of readystatechange, progress, abort, error, timeout and loadend
event are not specified to be dispatched in sync mode in the latest
spec. Just an exception corresponding to the failure is thrown.
Clean up for readability done in this CL
- factor out dispatchEventAndLoadEnd calling code
- make didTimeout() private
- give error handling methods more descriptive names
- set m_exceptionCode in failure type specific methods
-- Note that for didFailRedirectCheck, m_exceptionCode was not set
in networkError(), but was set at the end of createRequest()
This CL is prep for fixing crbug.com/292422
BUG=292422
Review URL: https://chromiumcodereview.appspot.com/24225002
git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void XMLHttpRequest::didFail(const ResourceError& error)
{
if (m_error)
return;
if (error.isCancellation()) {
handleDidCancel();
return;
}
if (error.isTimeout()) {
handleDidTimeout();
return;
}
if (error.domain() == errorDomainWebKitInternal)
logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
handleNetworkError();
}
| 171,165 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::ContentCompression::ContentCompression()
: algo(0),
settings(NULL),
settings_len(0) {
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | ContentEncoding::ContentCompression::ContentCompression()
| 174,250 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct user_element *ue = kcontrol->private_data;
memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size);
return 0;
}
Commit Message: ALSA: control: Protect user controls against concurrent access
The user-control put and get handlers as well as the tlv do not protect against
concurrent access from multiple threads. Since the state of the control is not
updated atomically it is possible that either two write operations or a write
and a read operation race against each other. Both can lead to arbitrary memory
disclosure. This patch introduces a new lock that protects user-controls from
concurrent access. Since applications typically access controls sequentially
than in parallel a single lock per card should be fine.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362 | static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct user_element *ue = kcontrol->private_data;
mutex_lock(&ue->card->user_ctl_lock);
memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size);
mutex_unlock(&ue->card->user_ctl_lock);
return 0;
}
| 166,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
CWE ID: CWE-125 | atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
if (char_cnt == 0)
return (0);
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
| 167,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609
CWE ID: CWE-125 | MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if ((width == 0) || (height == 0))
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
| 169,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_hunkmax (void)
{
if (!p_line)
p_line = (char **) malloc (hunkmax * sizeof *p_line);
if (!p_len)
p_len = (size_t *) malloc (hunkmax * sizeof *p_len);
if (!p_Char)
p_Char = malloc (hunkmax * sizeof *p_Char);
}
Commit Message:
CWE ID: CWE-399 | set_hunkmax (void)
{
if (!p_line)
p_line = (char **) xmalloc (hunkmax * sizeof *p_line);
if (!p_len)
p_len = (size_t *) xmalloc (hunkmax * sizeof *p_len);
if (!p_Char)
p_Char = xmalloc (hunkmax * sizeof *p_Char);
}
| 165,401 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DataReductionProxyIOData::DataReductionProxyIOData(
Client client,
PrefService* prefs,
network::NetworkConnectionTracker* network_connection_tracker,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
bool enabled,
const std::string& user_agent,
const std::string& channel)
: client_(client),
network_connection_tracker_(network_connection_tracker),
io_task_runner_(io_task_runner),
ui_task_runner_(ui_task_runner),
enabled_(enabled),
channel_(channel),
effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
DCHECK(io_task_runner_);
DCHECK(ui_task_runner_);
configurator_.reset(new DataReductionProxyConfigurator());
configurator_->SetConfigUpdatedCallback(base::BindRepeating(
&DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this)));
DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr;
std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config =
std::make_unique<DataReductionProxyMutableConfigValues>();
raw_mutable_config = mutable_config.get();
config_.reset(new DataReductionProxyConfig(
io_task_runner, ui_task_runner, network_connection_tracker_,
std::move(mutable_config), configurator_.get()));
request_options_.reset(
new DataReductionProxyRequestOptions(client_, config_.get()));
request_options_->Init();
request_options_->SetUpdateHeaderCallback(base::BindRepeating(
&DataReductionProxyIOData::UpdateProxyRequestHeaders,
base::Unretained(this)));
config_client_.reset(new DataReductionProxyConfigServiceClient(
GetBackoffPolicy(), request_options_.get(), raw_mutable_config,
config_.get(), this, network_connection_tracker_,
base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig,
base::Unretained(this))));
network_properties_manager_.reset(new NetworkPropertiesManager(
base::DefaultClock::GetInstance(), prefs, ui_task_runner_));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | DataReductionProxyIOData::DataReductionProxyIOData(
Client client,
PrefService* prefs,
network::NetworkConnectionTracker* network_connection_tracker,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
bool enabled,
const std::string& user_agent,
const std::string& channel)
: client_(client),
network_connection_tracker_(network_connection_tracker),
io_task_runner_(io_task_runner),
ui_task_runner_(ui_task_runner),
enabled_(enabled),
channel_(channel),
effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
DCHECK(io_task_runner_);
DCHECK(ui_task_runner_);
configurator_.reset(new DataReductionProxyConfigurator());
configurator_->SetConfigUpdatedCallback(base::BindRepeating(
&DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this)));
DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr;
std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config =
std::make_unique<DataReductionProxyMutableConfigValues>();
raw_mutable_config = mutable_config.get();
config_.reset(new DataReductionProxyConfig(
io_task_runner, ui_task_runner, network_connection_tracker_,
std::move(mutable_config), configurator_.get()));
request_options_.reset(
new DataReductionProxyRequestOptions(client_, config_.get()));
request_options_->Init();
request_options_->SetUpdateHeaderCallback(base::BindRepeating(
&DataReductionProxyIOData::UpdateProxyRequestHeaders,
base::Unretained(this)));
if (!params::IsIncludedInHoldbackFieldTrial()) {
config_client_.reset(new DataReductionProxyConfigServiceClient(
GetBackoffPolicy(), request_options_.get(), raw_mutable_config,
config_.get(), this, network_connection_tracker_,
base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig,
base::Unretained(this))));
}
network_properties_manager_.reset(new NetworkPropertiesManager(
base::DefaultClock::GetInstance(), prefs, ui_task_runner_));
}
| 172,421 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseCharRef(xmlParserCtxtPtr ctxt) {
unsigned int val = 0;
int count = 0;
unsigned int outofrange = 0;
/*
* Using RAW/CUR/NEXT is okay since we are working on ASCII range here
*/
if ((RAW == '&') && (NXT(1) == '#') &&
(NXT(2) == 'x')) {
SKIP(3);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 16 + (CUR - '0');
else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
val = val * 16 + (CUR - 'a') + 10;
else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
val = val * 16 + (CUR - 'A') + 10;
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else if ((RAW == '&') && (NXT(1) == '#')) {
SKIP(2);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 10 + (CUR - '0');
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else {
xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
}
/*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*/
if ((IS_CHAR(val) && (outofrange == 0))) {
return(val);
} else {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseCharRef: invalid xmlChar value %d\n",
val);
}
return(0);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseCharRef(xmlParserCtxtPtr ctxt) {
unsigned int val = 0;
int count = 0;
unsigned int outofrange = 0;
/*
* Using RAW/CUR/NEXT is okay since we are working on ASCII range here
*/
if ((RAW == '&') && (NXT(1) == '#') &&
(NXT(2) == 'x')) {
SKIP(3);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(0);
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 16 + (CUR - '0');
else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
val = val * 16 + (CUR - 'a') + 10;
else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
val = val * 16 + (CUR - 'A') + 10;
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else if ((RAW == '&') && (NXT(1) == '#')) {
SKIP(2);
GROW;
while (RAW != ';') { /* loop blocked by count */
if (count++ > 20) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(0);
}
if ((RAW >= '0') && (RAW <= '9'))
val = val * 10 + (CUR - '0');
else {
xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
val = 0;
break;
}
if (val > 0x10FFFF)
outofrange = val;
NEXT;
count++;
}
if (RAW == ';') {
/* on purpose to avoid reentrancy problems with NEXT and SKIP */
ctxt->input->col++;
ctxt->nbChars ++;
ctxt->input->cur++;
}
} else {
xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
}
/*
* [ WFC: Legal Character ]
* Characters referred to using character references must match the
* production for Char.
*/
if ((IS_CHAR(val) && (outofrange == 0))) {
return(val);
} else {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlParseCharRef: invalid xmlChar value %d\n",
val);
}
return(0);
}
| 171,276 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionItem(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestEventTarget::s_info))
return throwVMTypeError(exec);
JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info);
TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int index(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toUInt32(exec));
if (index < 0) {
setDOMException(exec, INDEX_SIZE_ERR);
return JSValue::encode(jsUndefined());
}
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->item(index)));
return JSValue::encode(result);
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionItem(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestEventTarget::s_info))
return throwVMTypeError(exec);
JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info);
TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
int index(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toUInt32(exec));
if (index < 0) {
setDOMException(exec, INDEX_SIZE_ERR);
return JSValue::encode(jsUndefined());
}
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->item(index)));
return JSValue::encode(result);
}
| 170,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: xmlParseEntityDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *value = NULL;
xmlChar *URI = NULL, *literal = NULL;
const xmlChar *ndata = NULL;
int isParameter = 0;
xmlChar *orig = NULL;
int skipped;
/* GROW; done in the caller */
if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) {
xmlParserInputPtr input = ctxt->input;
SHRINK;
SKIP(8);
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ENTITY'\n");
}
if (RAW == '%') {
NEXT;
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '%'\n");
}
isParameter = 1;
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityDecl: no name\n");
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colon are forbidden from entities names '%s'\n",
name, NULL, NULL);
}
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the entity name\n");
}
ctxt->instate = XML_PARSER_ENTITY_DECL;
/*
* handle the various case of definitions...
*/
if (isParameter) {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if (value) {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_PARAMETER_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *) URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) &&
(ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_PARAMETER_ENTITY,
literal, URI, NULL);
}
xmlFreeURI(uri);
}
}
}
} else {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
/*
* For expat compatibility in SAX mode.
*/
if ((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *)URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
}
xmlFreeURI(uri);
}
}
if ((RAW != '>') && (!IS_BLANK_CH(CUR))) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required before 'NDATA'\n");
}
SKIP_BLANKS;
if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
SKIP(5);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NDATA'\n");
}
SKIP_BLANKS;
ndata = xmlParseName(ctxt);
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->unparsedEntityDecl != NULL))
ctxt->sax->unparsedEntityDecl(ctxt->userData, name,
literal, URI, ndata);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
/*
* For expat compatibility in SAX mode.
* assuming the entity repalcement was asked for
*/
if ((ctxt->replaceEntities != 0) &&
((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
}
}
}
}
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
"xmlParseEntityDecl: entity %s not terminated\n", name);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Entity declaration doesn't start and stop in the same entity\n");
}
NEXT;
}
if (orig != NULL) {
/*
* Ugly mechanism to save the raw entity value.
*/
xmlEntityPtr cur = NULL;
if (isParameter) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
cur = ctxt->sax->getParameterEntity(ctxt->userData, name);
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getEntity != NULL))
cur = ctxt->sax->getEntity(ctxt->userData, name);
if ((cur == NULL) && (ctxt->userData==ctxt)) {
cur = xmlSAX2GetEntity(ctxt, name);
}
}
if (cur != NULL) {
if (cur->orig != NULL)
xmlFree(orig);
else
cur->orig = orig;
} else
xmlFree(orig);
}
if (value != NULL) xmlFree(value);
if (URI != NULL) xmlFree(URI);
if (literal != NULL) xmlFree(literal);
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseEntityDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *value = NULL;
xmlChar *URI = NULL, *literal = NULL;
const xmlChar *ndata = NULL;
int isParameter = 0;
xmlChar *orig = NULL;
int skipped;
/* GROW; done in the caller */
if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) {
xmlParserInputPtr input = ctxt->input;
SHRINK;
SKIP(8);
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ENTITY'\n");
}
if (RAW == '%') {
NEXT;
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '%'\n");
}
isParameter = 1;
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseEntityDecl: no name\n");
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colon are forbidden from entities names '%s'\n",
name, NULL, NULL);
}
skipped = SKIP_BLANKS;
if (skipped == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the entity name\n");
}
ctxt->instate = XML_PARSER_ENTITY_DECL;
/*
* handle the various case of definitions...
*/
if (isParameter) {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if (value) {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_PARAMETER_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *) URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) &&
(ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_PARAMETER_ENTITY,
literal, URI, NULL);
}
xmlFreeURI(uri);
}
}
}
} else {
if ((RAW == '"') || (RAW == '\'')) {
value = xmlParseEntityValue(ctxt, &orig);
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
/*
* For expat compatibility in SAX mode.
*/
if ((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY,
NULL, NULL, value);
}
} else {
URI = xmlParseExternalID(ctxt, &literal, 1);
if ((URI == NULL) && (literal == NULL)) {
xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
}
if (URI) {
xmlURIPtr uri;
uri = xmlParseURI((const char *)URI);
if (uri == NULL) {
xmlErrMsgStr(ctxt, XML_ERR_INVALID_URI,
"Invalid URI: %s\n", URI);
/*
* This really ought to be a well formedness error
* but the XML Core WG decided otherwise c.f. issue
* E26 of the XML erratas.
*/
} else {
if (uri->fragment != NULL) {
/*
* Okay this is foolish to block those but not
* invalid URIs.
*/
xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
}
xmlFreeURI(uri);
}
}
if ((RAW != '>') && (!IS_BLANK_CH(CUR))) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required before 'NDATA'\n");
}
SKIP_BLANKS;
if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
SKIP(5);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NDATA'\n");
}
SKIP_BLANKS;
ndata = xmlParseName(ctxt);
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->unparsedEntityDecl != NULL))
ctxt->sax->unparsedEntityDecl(ctxt->userData, name,
literal, URI, ndata);
} else {
if ((ctxt->sax != NULL) &&
(!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
ctxt->sax->entityDecl(ctxt->userData, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
/*
* For expat compatibility in SAX mode.
* assuming the entity repalcement was asked for
*/
if ((ctxt->replaceEntities != 0) &&
((ctxt->myDoc == NULL) ||
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
if (ctxt->myDoc == NULL) {
ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
if (ctxt->myDoc == NULL) {
xmlErrMemory(ctxt, "New Doc failed");
return;
}
ctxt->myDoc->properties = XML_DOC_INTERNAL;
}
if (ctxt->myDoc->intSubset == NULL)
ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
BAD_CAST "fake", NULL, NULL);
xmlSAX2EntityDecl(ctxt, name,
XML_EXTERNAL_GENERAL_PARSED_ENTITY,
literal, URI, NULL);
}
}
}
}
if (ctxt->instate == XML_PARSER_EOF)
return;
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
"xmlParseEntityDecl: entity %s not terminated\n", name);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Entity declaration doesn't start and stop in the same entity\n");
}
NEXT;
}
if (orig != NULL) {
/*
* Ugly mechanism to save the raw entity value.
*/
xmlEntityPtr cur = NULL;
if (isParameter) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
cur = ctxt->sax->getParameterEntity(ctxt->userData, name);
} else {
if ((ctxt->sax != NULL) &&
(ctxt->sax->getEntity != NULL))
cur = ctxt->sax->getEntity(ctxt->userData, name);
if ((cur == NULL) && (ctxt->userData==ctxt)) {
cur = xmlSAX2GetEntity(ctxt, name);
}
}
if (cur != NULL) {
if (cur->orig != NULL)
xmlFree(orig);
else
cur->orig = orig;
} else
xmlFree(orig);
}
if (value != NULL) xmlFree(value);
if (URI != NULL) xmlFree(URI);
if (literal != NULL) xmlFree(literal);
}
}
| 171,288 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy(
int32_t element_instance_id,
int32_t plugin_frame_routing_id) {
auto it = frame_navigation_helpers_.find(element_instance_id);
if (it == frame_navigation_helpers_.end()) {
return;
}
auto* plugin_rfh = content::RenderFrameHost::FromID(render_process_id_,
plugin_frame_routing_id);
auto* helper = it->second.get();
auto* guest_view = helper->GetGuestView();
if (!guest_view)
return;
if (plugin_rfh) {
DCHECK(
guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh));
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
helper->is_full_page_plugin());
} else {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_DestroyFrameContainer(element_instance_id));
guest_view->Destroy(true);
}
frame_navigation_helpers_.erase(element_instance_id);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | void ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy(
MimeHandlerViewAttachHelper::Get(render_process_id_)
->AttachToOuterWebContents(guest_view, embedder_render_process_id,
plugin_frame_routing_id, element_instance_id,
is_full_page_plugin);
}
| 173,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
__be32 daddr;
__be16 dport;
struct rds_message *rm = NULL;
struct rds_connection *conn;
int ret = 0;
int queued = 0, allocated_mr = 0;
int nonblock = msg->msg_flags & MSG_DONTWAIT;
long timeo = sock_sndtimeo(sk, nonblock);
/* Mirror Linux UDP mirror of BSD error message compatibility */
/* XXX: Perhaps MSG_MORE someday */
if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_CMSG_COMPAT)) {
ret = -EOPNOTSUPP;
goto out;
}
if (msg->msg_namelen) {
/* XXX fail non-unicast destination IPs? */
if (msg->msg_namelen < sizeof(*usin) || usin->sin_family != AF_INET) {
ret = -EINVAL;
goto out;
}
daddr = usin->sin_addr.s_addr;
dport = usin->sin_port;
} else {
/* We only care about consistency with ->connect() */
lock_sock(sk);
daddr = rs->rs_conn_addr;
dport = rs->rs_conn_port;
release_sock(sk);
}
/* racing with another thread binding seems ok here */
if (daddr == 0 || rs->rs_bound_addr == 0) {
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
if (payload_len > rds_sk_sndbuf(rs)) {
ret = -EMSGSIZE;
goto out;
}
/* size of rm including all sgs */
ret = rds_rm_size(msg, payload_len);
if (ret < 0)
goto out;
rm = rds_message_alloc(ret, GFP_KERNEL);
if (!rm) {
ret = -ENOMEM;
goto out;
}
/* Attach data to the rm */
if (payload_len) {
rm->data.op_sg = rds_message_alloc_sgs(rm, ceil(payload_len, PAGE_SIZE));
if (!rm->data.op_sg) {
ret = -ENOMEM;
goto out;
}
ret = rds_message_copy_from_user(rm, &msg->msg_iter);
if (ret)
goto out;
}
rm->data.op_active = 1;
rm->m_daddr = daddr;
/* rds_conn_create has a spinlock that runs with IRQ off.
* Caching the conn in the socket helps a lot. */
if (rs->rs_conn && rs->rs_conn->c_faddr == daddr)
conn = rs->rs_conn;
else {
conn = rds_conn_create_outgoing(sock_net(sock->sk),
rs->rs_bound_addr, daddr,
rs->rs_transport,
sock->sk->sk_allocation);
if (IS_ERR(conn)) {
ret = PTR_ERR(conn);
goto out;
}
rs->rs_conn = conn;
}
/* Parse any control messages the user may have included. */
ret = rds_cmsg_send(rs, rm, msg, &allocated_mr);
if (ret)
goto out;
if (rm->rdma.op_active && !conn->c_trans->xmit_rdma) {
printk_ratelimited(KERN_NOTICE "rdma_op %p conn xmit_rdma %p\n",
&rm->rdma, conn->c_trans->xmit_rdma);
ret = -EOPNOTSUPP;
goto out;
}
if (rm->atomic.op_active && !conn->c_trans->xmit_atomic) {
printk_ratelimited(KERN_NOTICE "atomic_op %p conn xmit_atomic %p\n",
&rm->atomic, conn->c_trans->xmit_atomic);
ret = -EOPNOTSUPP;
goto out;
}
rds_conn_connect_if_down(conn);
ret = rds_cong_wait(conn->c_fcong, dport, nonblock, rs);
if (ret) {
rs->rs_seen_congestion = 1;
goto out;
}
while (!rds_send_queue_rm(rs, conn, rm, rs->rs_bound_port,
dport, &queued)) {
rds_stats_inc(s_send_queue_full);
if (nonblock) {
ret = -EAGAIN;
goto out;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
rds_send_queue_rm(rs, conn, rm,
rs->rs_bound_port,
dport,
&queued),
timeo);
rdsdebug("sendmsg woke queued %d timeo %ld\n", queued, timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
goto out;
}
/*
* By now we've committed to the send. We reuse rds_send_worker()
* to retry sends in the rds thread if the transport asks us to.
*/
rds_stats_inc(s_send_queued);
ret = rds_send_xmit(conn);
if (ret == -ENOMEM || ret == -EAGAIN)
queue_delayed_work(rds_wq, &conn->c_send_w, 1);
rds_message_put(rm);
return payload_len;
out:
/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.
* If the sendmsg goes through, we keep the MR. If it fails with EAGAIN
* or in any other way, we need to destroy the MR again */
if (allocated_mr)
rds_rdma_unuse(rs, rds_rdma_cookie_key(rm->m_rdma_cookie), 1);
if (rm)
rds_message_put(rm);
return ret;
}
Commit Message: RDS: fix race condition when sending a message on unbound socket
Sasha's found a NULL pointer dereference in the RDS connection code when
sending a message to an apparently unbound socket. The problem is caused
by the code checking if the socket is bound in rds_sendmsg(), which checks
the rs_bound_addr field without taking a lock on the socket. This opens a
race where rs_bound_addr is temporarily set but where the transport is not
in rds_bind(), leading to a NULL pointer dereference when trying to
dereference 'trans' in __rds_conn_create().
Vegard wrote a reproducer for this issue, so kindly ask him to share if
you're interested.
I cannot reproduce the NULL pointer dereference using Vegard's reproducer
with this patch, whereas I could without.
Complete earlier incomplete fix to CVE-2015-6937:
74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection")
Cc: David S. Miller <[email protected]>
Cc: [email protected]
Reviewed-by: Vegard Nossum <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
__be32 daddr;
__be16 dport;
struct rds_message *rm = NULL;
struct rds_connection *conn;
int ret = 0;
int queued = 0, allocated_mr = 0;
int nonblock = msg->msg_flags & MSG_DONTWAIT;
long timeo = sock_sndtimeo(sk, nonblock);
/* Mirror Linux UDP mirror of BSD error message compatibility */
/* XXX: Perhaps MSG_MORE someday */
if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_CMSG_COMPAT)) {
ret = -EOPNOTSUPP;
goto out;
}
if (msg->msg_namelen) {
/* XXX fail non-unicast destination IPs? */
if (msg->msg_namelen < sizeof(*usin) || usin->sin_family != AF_INET) {
ret = -EINVAL;
goto out;
}
daddr = usin->sin_addr.s_addr;
dport = usin->sin_port;
} else {
/* We only care about consistency with ->connect() */
lock_sock(sk);
daddr = rs->rs_conn_addr;
dport = rs->rs_conn_port;
release_sock(sk);
}
lock_sock(sk);
if (daddr == 0 || rs->rs_bound_addr == 0) {
release_sock(sk);
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
release_sock(sk);
if (payload_len > rds_sk_sndbuf(rs)) {
ret = -EMSGSIZE;
goto out;
}
/* size of rm including all sgs */
ret = rds_rm_size(msg, payload_len);
if (ret < 0)
goto out;
rm = rds_message_alloc(ret, GFP_KERNEL);
if (!rm) {
ret = -ENOMEM;
goto out;
}
/* Attach data to the rm */
if (payload_len) {
rm->data.op_sg = rds_message_alloc_sgs(rm, ceil(payload_len, PAGE_SIZE));
if (!rm->data.op_sg) {
ret = -ENOMEM;
goto out;
}
ret = rds_message_copy_from_user(rm, &msg->msg_iter);
if (ret)
goto out;
}
rm->data.op_active = 1;
rm->m_daddr = daddr;
/* rds_conn_create has a spinlock that runs with IRQ off.
* Caching the conn in the socket helps a lot. */
if (rs->rs_conn && rs->rs_conn->c_faddr == daddr)
conn = rs->rs_conn;
else {
conn = rds_conn_create_outgoing(sock_net(sock->sk),
rs->rs_bound_addr, daddr,
rs->rs_transport,
sock->sk->sk_allocation);
if (IS_ERR(conn)) {
ret = PTR_ERR(conn);
goto out;
}
rs->rs_conn = conn;
}
/* Parse any control messages the user may have included. */
ret = rds_cmsg_send(rs, rm, msg, &allocated_mr);
if (ret)
goto out;
if (rm->rdma.op_active && !conn->c_trans->xmit_rdma) {
printk_ratelimited(KERN_NOTICE "rdma_op %p conn xmit_rdma %p\n",
&rm->rdma, conn->c_trans->xmit_rdma);
ret = -EOPNOTSUPP;
goto out;
}
if (rm->atomic.op_active && !conn->c_trans->xmit_atomic) {
printk_ratelimited(KERN_NOTICE "atomic_op %p conn xmit_atomic %p\n",
&rm->atomic, conn->c_trans->xmit_atomic);
ret = -EOPNOTSUPP;
goto out;
}
rds_conn_connect_if_down(conn);
ret = rds_cong_wait(conn->c_fcong, dport, nonblock, rs);
if (ret) {
rs->rs_seen_congestion = 1;
goto out;
}
while (!rds_send_queue_rm(rs, conn, rm, rs->rs_bound_port,
dport, &queued)) {
rds_stats_inc(s_send_queue_full);
if (nonblock) {
ret = -EAGAIN;
goto out;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
rds_send_queue_rm(rs, conn, rm,
rs->rs_bound_port,
dport,
&queued),
timeo);
rdsdebug("sendmsg woke queued %d timeo %ld\n", queued, timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
goto out;
}
/*
* By now we've committed to the send. We reuse rds_send_worker()
* to retry sends in the rds thread if the transport asks us to.
*/
rds_stats_inc(s_send_queued);
ret = rds_send_xmit(conn);
if (ret == -ENOMEM || ret == -EAGAIN)
queue_delayed_work(rds_wq, &conn->c_send_w, 1);
rds_message_put(rm);
return payload_len;
out:
/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.
* If the sendmsg goes through, we keep the MR. If it fails with EAGAIN
* or in any other way, we need to destroy the MR again */
if (allocated_mr)
rds_rdma_unuse(rs, rds_rdma_cookie_key(rm->m_rdma_cookie), 1);
if (rm)
rds_message_put(rm);
return ret;
}
| 166,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 l2tp_eth_dev_setup(struct net_device *dev)
{
ether_setup(dev);
dev->netdev_ops = &l2tp_eth_netdev_ops;
dev->destructor = free_netdev;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static void l2tp_eth_dev_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->netdev_ops = &l2tp_eth_netdev_ops;
dev->destructor = free_netdev;
}
| 165,738 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1597
CWE ID: CWE-125 | MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
number_channels;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
number_channels=MagickMin(MagickMin(MagickMin(
Ar_image->number_channels,Ai_image->number_channels),MagickMin(
Br_image->number_channels,Bi_image->number_channels)),MagickMin(
Cr_image->number_channels,Ci_image->number_channels));
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_channels; i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
| 169,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 FakeBluetoothAgentManagerClient::UnregisterAgent(
const dbus::ObjectPath& agent_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "UnregisterAgent: " << agent_path.value();
if (service_provider_ != NULL) {
error_callback.Run(bluetooth_agent_manager::kErrorInvalidArguments,
"Agent still registered");
} else {
callback.Run();
}
}
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 FakeBluetoothAgentManagerClient::UnregisterAgent(
const dbus::ObjectPath& agent_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "UnregisterAgent: " << agent_path.value();
if (service_provider_ == NULL) {
error_callback.Run(bluetooth_agent_manager::kErrorDoesNotExist,
"No agent registered");
} else if (service_provider_->object_path_ != agent_path) {
error_callback.Run(bluetooth_agent_manager::kErrorDoesNotExist,
"Agent still registered");
} else {
callback.Run();
}
}
| 171,213 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, strlen(dst) + 1);
return dst;
}
Commit Message:
CWE ID: CWE-200 | char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
size_t len;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
len = ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, len + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
dst[len] = '\0';
return dst;
}
| 164,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i)
ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random));
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
Commit Message:
CWE ID: CWE-310 | int ssl3_client_hello(SSL *s)
{
unsigned char *buf;
unsigned char *p, *d;
int i;
unsigned long l;
int al = 0;
#ifndef OPENSSL_NO_COMP
int j;
SSL_COMP *comp;
#endif
buf = (unsigned char *)s->init_buf->data;
if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
SSL_SESSION *sess = s->session;
if ((sess == NULL) ||
(sess->ssl_version != s->version) ||
!sess->session_id_length || (sess->not_resumable)) {
if (!ssl_get_new_session(s, 0))
goto err;
}
if (s->method->version == DTLS_ANY_VERSION) {
/* Determine which DTLS version to use */
int options = s->options;
/* If DTLS 1.2 disabled correct the version number */
if (options & SSL_OP_NO_DTLSv1_2) {
if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
/*
* Disabling all versions is silly: return an error.
*/
if (options & SSL_OP_NO_DTLSv1) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION);
goto err;
}
/*
* Update method so we don't use any DTLS 1.2 features.
*/
s->method = DTLSv1_client_method();
s->version = DTLS1_VERSION;
} else {
/*
* We only support one version: update method
*/
if (options & SSL_OP_NO_DTLSv1)
s->method = DTLSv1_2_client_method();
s->version = DTLS1_2_VERSION;
}
s->client_version = s->version;
}
/* else use the pre-loaded session */
p = s->s3->client_random;
/*
* for DTLS if client_random is initialized, reuse it, we are
* required to use same upon reply to HelloVerify
*/
if (SSL_IS_DTLS(s)) {
size_t idx;
i = 1;
for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
if (p[idx]) {
i = 0;
break;
}
}
} else
i = 1;
if (i && ssl_fill_hello_random(s, 0, p,
sizeof(s->s3->client_random)) <= 0)
goto err;
/* Do the message type and length last */
d = p = ssl_handshake_start(s);
/*-
* version indicates the negotiated version: for example from
* an SSLv2/v3 compatible client hello). The client_version
* field is the maximum version we permit and it is also
* used in RSA encrypted premaster secrets. Some servers can
* choke if we initially report a higher version then
* renegotiate to a lower one in the premaster secret. This
* didn't happen with TLS 1.0 as most servers supported it
* but it can with TLS 1.1 or later if the server only supports
* 1.0.
*
* Possible scenario with previous logic:
* 1. Client hello indicates TLS 1.2
* 2. Server hello says TLS 1.0
* 3. RSA encrypted premaster secret uses 1.2.
* 4. Handhaked proceeds using TLS 1.0.
* 5. Server sends hello request to renegotiate.
* 6. Client hello indicates TLS v1.0 as we now
* know that is maximum server supports.
* 7. Server chokes on RSA encrypted premaster secret
* containing version 1.0.
*
* For interoperability it should be OK to always use the
* maximum version we support in client hello and then rely
* on the checking of version to ensure the servers isn't
* being inconsistent: for example initially negotiating with
* TLS 1.0 and renegotiating with TLS 1.2. We do this by using
* client_version in client hello and not resetting it to
* the negotiated version.
*/
*(p++) = s->client_version >> 8;
*(p++) = s->client_version & 0xff;
/* Random stuff */
memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* Session ID */
if (s->new_session)
i = 0;
else
i = s->session->session_id_length;
*(p++) = i;
if (i != 0) {
if (i > (int)sizeof(s->session->session_id)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(p, s->session->session_id, i);
p += i;
}
/* cookie stuff for DTLS */
if (SSL_IS_DTLS(s)) {
if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
*(p++) = s->d1->cookie_len;
memcpy(p, s->d1->cookie, s->d1->cookie_len);
p += s->d1->cookie_len;
}
/* Ciphers supported */
i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
if (i == 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
goto err;
}
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
/*
* Some servers hang if client hello > 256 bytes as hack workaround
* chop number of supported ciphers to keep it well below this if we
* use TLS v1.2
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION
&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
#endif
s2n(i, p);
p += i;
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
*(p++) = 1;
#else
if (!ssl_allow_compression(s) || !s->ctx->comp_methods)
j = 0;
else
j = sk_SSL_COMP_num(s->ctx->comp_methods);
*(p++) = 1 + j;
for (i = 0; i < j; i++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
*(p++) = comp->id;
}
#endif
*(p++) = 0; /* Add the NULL method */
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (ssl_prepare_clienthello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
if ((p =
ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
&al)) == NULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto err;
}
#endif
l = p - d;
ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
s->state = SSL3_ST_CW_CLNT_HELLO_B;
}
/* SSL3_ST_CW_CLNT_HELLO_B */
return ssl_do_write(s);
err:
return (-1);
}
| 164,812 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ProfileSyncService::OnExperimentsChanged(
const browser_sync::Experiments& experiments) {
if (current_experiments.Matches(experiments))
return;
if (migrator_.get() &&
migrator_->state() != browser_sync::BackendMigrator::IDLE) {
DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
return;
}
const syncable::ModelTypeSet registered_types = GetRegisteredDataTypes();
syncable::ModelTypeSet to_add;
if (experiments.sync_tabs)
to_add.Put(syncable::SESSIONS);
const syncable::ModelTypeSet to_register =
Difference(to_add, registered_types);
DVLOG(2) << "OnExperimentsChanged called with types: "
<< syncable::ModelTypeSetToString(to_add);
DVLOG(2) << "Enabling types: " << syncable::ModelTypeSetToString(to_register);
for (syncable::ModelTypeSet::Iterator it = to_register.First();
it.Good(); it.Inc()) {
RegisterNewDataType(it.Get());
#if !defined(OS_ANDROID)
std::string experiment_name = GetExperimentNameForDataType(it.Get());
if (experiment_name.empty())
continue;
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
experiment_name,
true);
#endif // !defined(OS_ANDROID)
}
if (sync_prefs_.HasKeepEverythingSynced()) {
sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_.get()) {
DVLOG(1) << "Dynamically enabling new datatypes: "
<< syncable::ModelTypeSetToString(to_register);
OnMigrationNeededForTypes(to_register);
}
}
if (experiments.sync_tab_favicons) {
DVLOG(1) << "Enabling syncing of tab favicons.";
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
"sync-tab-favicons",
true);
}
current_experiments = experiments;
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void ProfileSyncService::OnExperimentsChanged(
const browser_sync::Experiments& experiments) {
if (current_experiments.Matches(experiments))
return;
if (migrator_.get() &&
migrator_->state() != browser_sync::BackendMigrator::IDLE) {
DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
return;
}
const syncable::ModelTypeSet registered_types = GetRegisteredDataTypes();
syncable::ModelTypeSet to_add;
const syncable::ModelTypeSet to_register =
Difference(to_add, registered_types);
DVLOG(2) << "OnExperimentsChanged called with types: "
<< syncable::ModelTypeSetToString(to_add);
DVLOG(2) << "Enabling types: " << syncable::ModelTypeSetToString(to_register);
for (syncable::ModelTypeSet::Iterator it = to_register.First();
it.Good(); it.Inc()) {
RegisterNewDataType(it.Get());
#if !defined(OS_ANDROID)
std::string experiment_name = GetExperimentNameForDataType(it.Get());
if (experiment_name.empty())
continue;
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
experiment_name,
true);
#endif // !defined(OS_ANDROID)
}
if (sync_prefs_.HasKeepEverythingSynced()) {
sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_.get()) {
DVLOG(1) << "Dynamically enabling new datatypes: "
<< syncable::ModelTypeSetToString(to_register);
OnMigrationNeededForTypes(to_register);
}
}
if (experiments.sync_tab_favicons) {
DVLOG(1) << "Enabling syncing of tab favicons.";
about_flags::SetExperimentEnabled(g_browser_process->local_state(),
"sync-tab-favicons",
true);
}
current_experiments = experiments;
}
| 170,787 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 my_csr_reader( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
REALTYPE** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return -1;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return -1;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return -1;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return -1;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
REALTYPE l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return -1;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return -1;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
return 0;
}
Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1).
CWE ID: CWE-119 | int my_csr_reader( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
REALTYPE** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return -1;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return -1;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) &&
0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count)
{
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return -1;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return -1;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
REALTYPE l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return -1;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return -1;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
return 0;
}
| 168,949 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && flags & TH_ACK))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption.
Do the length checking inline; that means we print stuff up to the point
at which we run out of option data.
First check to make sure we have at least 4 bytes of option, so we have
flags to check.
This fixes a buffer over-read discovered by Kim Gwan Yeong.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && (flags & TH_SYN)) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && (flags & TH_ACK)))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
| 167,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: InRegionScrollableArea::InRegionScrollableArea(WebPagePrivate* webPage, RenderLayer* layer)
: m_webPage(webPage)
, m_layer(layer)
{
ASSERT(webPage);
ASSERT(layer);
m_isNull = false;
RenderObject* layerRenderer = layer->renderer();
ASSERT(layerRenderer);
if (layerRenderer->isRenderView()) { // #document case
FrameView* view = toRenderView(layerRenderer)->frameView();
ASSERT(view);
Frame* frame = view->frame();
ASSERT_UNUSED(frame, frame);
m_scrollPosition = m_webPage->mapToTransformed(view->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(view->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(view->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_webPage->mapToTransformed(m_webPage->getRecursiveVisibleWindowRect(view));
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = view->contentsWidth() > view->visibleWidth();
m_scrollsVertically = view->contentsHeight() > view->visibleHeight();
m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition(
view->visibleContentRect().size(),
0.0 /*overscrollLimit*/));
m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition(
view->visibleContentRect().size(),
view->contentsSize(),
0.0 /*overscrollLimit*/));
} else { // RenderBox-based elements case (scrollable boxes (div's, p's, textarea's, etc)).
RenderBox* box = m_layer->renderBox();
ASSERT(box);
ASSERT(box->canBeScrolledAndHasScrollableArea());
ScrollableArea* scrollableArea = static_cast<ScrollableArea*>(m_layer);
m_scrollPosition = m_webPage->mapToTransformed(scrollableArea->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(scrollableArea->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(scrollableArea->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_layer->renderer()->absoluteClippedOverflowRect();
m_visibleWindowRect = m_layer->renderer()->frame()->view()->contentsToWindow(m_visibleWindowRect);
IntRect visibleFrameWindowRect = m_webPage->getRecursiveVisibleWindowRect(m_layer->renderer()->frame()->view());
m_visibleWindowRect.intersect(visibleFrameWindowRect);
m_visibleWindowRect = m_webPage->mapToTransformed(m_visibleWindowRect);
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = box->scrollWidth() != box->clientWidth() && box->scrollsOverflowX();
m_scrollsVertically = box->scrollHeight() != box->clientHeight() && box->scrollsOverflowY();
m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition(
Platform::IntSize(box->clientWidth(), box->clientHeight()),
0.0 /*overscrollLimit*/));
m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition(
Platform::IntSize(box->clientWidth(), box->clientHeight()),
Platform::IntSize(box->scrollWidth(), box->scrollHeight()),
0.0 /*overscrollLimit*/));
}
}
Commit Message: Remove minimum and maximum scroll position as they are no
longer required due to changes in ScrollViewBase.
https://bugs.webkit.org/show_bug.cgi?id=87298
Patch by Genevieve Mak <[email protected]> on 2012-05-23
Reviewed by Antonio Gomes.
* WebKitSupport/InRegionScrollableArea.cpp:
(BlackBerry::WebKit::InRegionScrollableArea::InRegionScrollableArea):
* WebKitSupport/InRegionScrollableArea.h:
(InRegionScrollableArea):
git-svn-id: svn://svn.chromium.org/blink/trunk@118233 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | InRegionScrollableArea::InRegionScrollableArea(WebPagePrivate* webPage, RenderLayer* layer)
: m_webPage(webPage)
, m_layer(layer)
{
ASSERT(webPage);
ASSERT(layer);
m_isNull = false;
RenderObject* layerRenderer = layer->renderer();
ASSERT(layerRenderer);
if (layerRenderer->isRenderView()) { // #document case
FrameView* view = toRenderView(layerRenderer)->frameView();
ASSERT(view);
Frame* frame = view->frame();
ASSERT_UNUSED(frame, frame);
m_scrollPosition = m_webPage->mapToTransformed(view->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(view->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(view->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_webPage->mapToTransformed(m_webPage->getRecursiveVisibleWindowRect(view));
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = view->contentsWidth() > view->visibleWidth();
m_scrollsVertically = view->contentsHeight() > view->visibleHeight();
m_overscrollLimitFactor = 0.0; // FIXME eventually support overscroll
} else { // RenderBox-based elements case (scrollable boxes (div's, p's, textarea's, etc)).
RenderBox* box = m_layer->renderBox();
ASSERT(box);
ASSERT(box->canBeScrolledAndHasScrollableArea());
ScrollableArea* scrollableArea = static_cast<ScrollableArea*>(m_layer);
m_scrollPosition = m_webPage->mapToTransformed(scrollableArea->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(scrollableArea->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(scrollableArea->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_layer->renderer()->absoluteClippedOverflowRect();
m_visibleWindowRect = m_layer->renderer()->frame()->view()->contentsToWindow(m_visibleWindowRect);
IntRect visibleFrameWindowRect = m_webPage->getRecursiveVisibleWindowRect(m_layer->renderer()->frame()->view());
m_visibleWindowRect.intersect(visibleFrameWindowRect);
m_visibleWindowRect = m_webPage->mapToTransformed(m_visibleWindowRect);
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = box->scrollWidth() != box->clientWidth() && box->scrollsOverflowX();
m_scrollsVertically = box->scrollHeight() != box->clientHeight() && box->scrollsOverflowY();
m_overscrollLimitFactor = 0.0; // FIXME eventually support overscroll
}
}
| 170,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int64_t AppCacheDatabase::GetOriginUsage(const url::Origin& origin) {
std::vector<CacheRecord> records;
if (!FindCachesForOrigin(origin, &records))
return 0;
int64_t origin_usage = 0;
for (const auto& record : records)
origin_usage += record.cache_size;
return origin_usage;
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | int64_t AppCacheDatabase::GetOriginUsage(const url::Origin& origin) {
std::vector<CacheRecord> caches;
if (!FindCachesForOrigin(origin, &caches))
return 0;
int64_t origin_usage = 0;
for (const auto& cache : caches)
origin_usage += cache.cache_size + cache.padding_size;
return origin_usage;
}
| 172,978 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
| 173,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void commitCompleteOnCCThread(CCLayerTreeHostImpl*)
{
m_numCommits++;
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | virtual void commitCompleteOnCCThread(CCLayerTreeHostImpl*)
{
EXPECT_EQ(0, m_numDraws);
m_numCommits++;
}
| 170,291 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
Commit Message:
CWE ID: | int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
const SSL_METHOD *new_method;
new_method = ssl23_get_server_method(s->version);
if (new_method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
s->method = new_method;
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 165,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {
int i;
ut8 *directory_base;
struct minidump_directory *entry;
directory_base = obj->b->buf + obj->hdr->stream_directory_rva;
sdb_num_set (obj->kv, "mdmp_directory.offset",
obj->hdr->stream_directory_rva, 0);
sdb_set (obj->kv, "mdmp_directory.format", "[4]E? "
"(mdmp_stream_type)StreamType "
"(mdmp_location_descriptor)Location", 0);
/* Parse each entry in the directory */
for (i = 0; i < (int)obj->hdr->number_of_streams; i++) {
entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory)));
r_bin_mdmp_init_directory_entry (obj, entry);
}
return true;
}
Commit Message: Fix #10464 - oobread crash in mdmp
CWE ID: CWE-125 | static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {
int i;
struct minidump_directory entry;
sdb_num_set (obj->kv, "mdmp_directory.offset",
obj->hdr->stream_directory_rva, 0);
sdb_set (obj->kv, "mdmp_directory.format", "[4]E? "
"(mdmp_stream_type)StreamType "
"(mdmp_location_descriptor)Location", 0);
/* Parse each entry in the directory */
ut64 rvadir = obj->hdr->stream_directory_rva;
for (i = 0; i < (int)obj->hdr->number_of_streams; i++) {
ut32 delta = i * sizeof (struct minidump_directory);
int r = r_buf_read_at (obj->b, rvadir + delta, (ut8*) &entry, sizeof (struct minidump_directory));
if (r) {
r_bin_mdmp_init_directory_entry (obj, &entry);
}
}
return true;
}
| 169,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
ASSERT(context);
ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks));
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
ASSERT(context);
ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
CallbackWrapper* wrapper = new CallbackWrapper(callbacks);
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
| 171,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead");
snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv);
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead))
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_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
strncpy(raead.type, "nivaead", sizeof(raead.type));
strncpy(raead.geniv, aead->geniv, sizeof(raead.geniv));
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef");
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetInteger(printing::kPreviewUIID, 4);
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
| 170,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebContents* DevToolsWindow::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
return inspected_web_contents ?
inspected_web_contents->OpenURL(params) : NULL;
}
bindings_->Reload();
return main_web_contents_;
}
Commit Message: [DevTools] Use no-referrer for DevTools links
Bug: 732751
Change-Id: I77753120e2424203dedcc7bc0847fb67f87fe2b2
Reviewed-on: https://chromium-review.googlesource.com/615021
Reviewed-by: Andrey Kosyakov <[email protected]>
Commit-Queue: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#494413}
CWE ID: CWE-668 | WebContents* DevToolsWindow::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
if (!inspected_web_contents)
return nullptr;
content::OpenURLParams modified = params;
modified.referrer = content::Referrer();
return inspected_web_contents->OpenURL(modified);
}
bindings_->Reload();
return main_web_contents_;
}
| 172,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuChannel::OnChannelConnected(int32 peer_pid) {
| 170,932 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
break;
}
if (c) { /* encoded mode */
int j;
OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
} else { /* absolute mode */
c = getc(IN);
if (c == EOF) {
break;
}
if (c == 0x00) { /* EOL */
x = 0;
y++;
pix = pData + y * stride;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
x += (OPJ_UINT32)c;
c = getc(IN);
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 : absolute mode */
int j;
OPJ_UINT8 c1 = 0U;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
if ((j & 1) == 0) {
c1 = (OPJ_UINT8)getc(IN);
}
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
getc(IN);
}
}
}
} /* while(y < height) */
return OPJ_TRUE;
}
Commit Message: convertbmp: detect invalid file dimensions early
width/length dimensions read from bmp headers are not necessarily
valid. For instance they may have been maliciously set to very large
values with the intention to cause DoS (large memory allocation, stack
overflow). In these cases we want to detect the invalid size as early
as possible.
This commit introduces a counter which verifies that the number of
written bytes corresponds to the advertized width/length.
See commit 8ee335227bbc for details.
Signed-off-by: Young Xiao <[email protected]>
CWE ID: CWE-400 | static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y, written;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = written = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
break;
}
if (c) { /* encoded mode */
int j;
OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
written++;
}
} else { /* absolute mode */
c = getc(IN);
if (c == EOF) {
break;
}
if (c == 0x00) { /* EOL */
x = 0;
y++;
pix = pData + y * stride;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
x += (OPJ_UINT32)c;
c = getc(IN);
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 : absolute mode */
int j;
OPJ_UINT8 c1 = 0U;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
if ((j & 1) == 0) {
c1 = (OPJ_UINT8)getc(IN);
}
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
written++;
}
if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
getc(IN);
}
}
}
} /* while(y < height) */
if (written != width * height) {
fprintf(stderr, "warning, image's actual size does not match advertized one\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
| 170,210 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 NavigationRateLimiter::CanProceed() {
if (!enabled)
return true;
static constexpr int kStateUpdateLimit = 200;
static constexpr base::TimeDelta kStateUpdateLimitResetInterval =
base::TimeDelta::FromSeconds(10);
if (++count_ <= kStateUpdateLimit)
return true;
const base::TimeTicks now = base::TimeTicks::Now();
if (now - time_first_count_ > kStateUpdateLimitResetInterval) {
time_first_count_ = now;
count_ = 1;
error_message_sent_ = false;
return true;
}
if (!error_message_sent_) {
error_message_sent_ = true;
if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) {
local_frame->Console().AddMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning,
"Throttling navigation to prevent the browser from hanging. See "
"https://crbug.com/882238. Command line switch "
"--disable-ipc-flooding-protection can be used to bypass the "
"protection"));
}
}
return false;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416 | bool NavigationRateLimiter::CanProceed() {
if (!enabled)
return true;
static constexpr int kStateUpdateLimit = 200;
static constexpr base::TimeDelta kStateUpdateLimitResetInterval =
base::TimeDelta::FromSeconds(10);
if (++count_ <= kStateUpdateLimit)
return true;
const base::TimeTicks now = base::TimeTicks::Now();
if (now - time_first_count_ > kStateUpdateLimitResetInterval) {
time_first_count_ = now;
count_ = 1;
error_message_sent_ = false;
return true;
}
// the browser process with the DidAddMessageToConsole Mojo call.
if (!error_message_sent_) {
error_message_sent_ = true;
if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) {
local_frame->Console().AddMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning,
"Throttling navigation to prevent the browser from hanging. See "
"https://crbug.com/882238. Command line switch "
"--disable-ipc-flooding-protection can be used to bypass the "
"protection"));
}
}
return false;
}
| 172,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long CuePoint::GetTime(const Segment* pSegment) const
{
assert(pSegment);
assert(m_timecode >= 0);
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long time = scale * m_timecode;
return time;
}
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 CuePoint::GetTime(const Segment* pSegment) const
| 174,364 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err gf_bin128_parse(const char *string, bin128 value)
{
u32 len;
u32 i=0;
if (!strnicmp(string, "0x", 2)) string += 2;
len = (u32) strlen(string);
if (len >= 32) {
u32 j;
for (j=0; j<len; j+=2) {
u32 v;
char szV[5];
while (string[j] && !isalnum(string[j]))
j++;
if (!string[j])
break;
sprintf(szV, "%c%c", string[j], string[j+1]);
sscanf(szV, "%x", &v);
value[i] = v;
i++;
}
}
if (i != 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string));
return GF_BAD_PARAM;
}
return GF_OK;
}
Commit Message: fix buffer overrun in gf_bin128_parse
closes #1204
closes #1205
CWE ID: CWE-119 | GF_Err gf_bin128_parse(const char *string, bin128 value)
{
u32 len;
u32 i=0;
if (!strnicmp(string, "0x", 2)) string += 2;
len = (u32) strlen(string);
if (len >= 32) {
u32 j;
for (j=0; j<len; j+=2) {
u32 v;
char szV[5];
while (string[j] && !isalnum(string[j]))
j++;
if (!string[j])
break;
sprintf(szV, "%c%c", string[j], string[j+1]);
sscanf(szV, "%x", &v);
value[i] = v;
i++;
if (i > 15) {
// force error check below
i++;
break;
}
}
}
if (i != 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string));
return GF_BAD_PARAM;
}
return GF_OK;
}
| 169,708 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 rds_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
__be32 saddr, __be32 daddr, int flip)
{
struct rds_info_message minfo;
minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo.len = be32_to_cpu(inc->i_hdr.h_len);
if (flip) {
minfo.laddr = daddr;
minfo.faddr = saddr;
minfo.lport = inc->i_hdr.h_dport;
minfo.fport = inc->i_hdr.h_sport;
} else {
minfo.laddr = saddr;
minfo.faddr = daddr;
minfo.lport = inc->i_hdr.h_sport;
minfo.fport = inc->i_hdr.h_dport;
}
rds_info_copy(iter, &minfo, sizeof(minfo));
}
Commit Message: rds: fix an infoleak in rds_inc_info_copy
The last field "flags" of object "minfo" is not initialized.
Copying this object out may leak kernel stack data.
Assign 0 to it to avoid leak.
Signed-off-by: Kangjie Lu <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | void rds_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
__be32 saddr, __be32 daddr, int flip)
{
struct rds_info_message minfo;
minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo.len = be32_to_cpu(inc->i_hdr.h_len);
if (flip) {
minfo.laddr = daddr;
minfo.faddr = saddr;
minfo.lport = inc->i_hdr.h_dport;
minfo.fport = inc->i_hdr.h_sport;
} else {
minfo.laddr = saddr;
minfo.faddr = daddr;
minfo.lport = inc->i_hdr.h_sport;
minfo.fport = inc->i_hdr.h_dport;
}
minfo.flags = 0;
rds_info_copy(iter, &minfo, sizeof(minfo));
}
| 167,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y,
ExceptionInfo *exception)
{
size_t bit; ssize_t x;
register Quantum *q;
Quantum index;
index=0;
switch (depth)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) >= 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) >= 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
p++;
q+=GetPixelChannels(image);
}
(void) SyncAuthenticPixels(image,exception);
break;
}
}
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1162
CWE ID: CWE-787 | static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y,
static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p,
ssize_t y,ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
if (index < image->colors)
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
| 169,042 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pud_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pud_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
| 170,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebURLLoaderImpl::Context::OnReceivedResponse(
const ResourceResponseInfo& info) {
if (!client_)
return;
WebURLResponse response;
response.initialize();
PopulateURLResponse(request_.url(), info, &response);
bool show_raw_listing = (GURL(request_.url()).query() == "raw");
if (info.mime_type == "text/vnd.chromium.ftp-dir") {
if (show_raw_listing) {
response.setMIMEType("text/plain");
} else {
response.setMIMEType("text/html");
}
}
client_->didReceiveResponse(loader_, response);
if (!client_)
return;
DCHECK(!ftp_listing_delegate_.get());
DCHECK(!multipart_delegate_.get());
if (info.headers && info.mime_type == "multipart/x-mixed-replace") {
std::string content_type;
info.headers->EnumerateHeader(NULL, "content-type", &content_type);
std::string mime_type;
std::string charset;
bool had_charset = false;
std::string boundary;
net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
&had_charset, &boundary);
TrimString(boundary, " \"", &boundary);
if (!boundary.empty()) {
multipart_delegate_.reset(
new MultipartResponseDelegate(client_, loader_, response, boundary));
}
} else if (info.mime_type == "text/vnd.chromium.ftp-dir" &&
!show_raw_listing) {
ftp_listing_delegate_.reset(
new FtpDirectoryListingResponseDelegate(client_, loader_, response));
}
}
Commit Message: Protect WebURLLoaderImpl::Context while receiving responses.
A client's didReceiveResponse can cancel a request; by protecting the
Context we avoid a use after free in this case.
Interestingly, we really had very good warning about this problem, see
https://codereview.chromium.org/11900002/ back in January.
R=darin
BUG=241139
Review URL: https://chromiumcodereview.appspot.com/15738007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void WebURLLoaderImpl::Context::OnReceivedResponse(
const ResourceResponseInfo& info) {
if (!client_)
return;
WebURLResponse response;
response.initialize();
PopulateURLResponse(request_.url(), info, &response);
bool show_raw_listing = (GURL(request_.url()).query() == "raw");
if (info.mime_type == "text/vnd.chromium.ftp-dir") {
if (show_raw_listing) {
response.setMIMEType("text/plain");
} else {
response.setMIMEType("text/html");
}
}
scoped_refptr<Context> protect(this);
client_->didReceiveResponse(loader_, response);
if (!client_)
return;
DCHECK(!ftp_listing_delegate_.get());
DCHECK(!multipart_delegate_.get());
if (info.headers && info.mime_type == "multipart/x-mixed-replace") {
std::string content_type;
info.headers->EnumerateHeader(NULL, "content-type", &content_type);
std::string mime_type;
std::string charset;
bool had_charset = false;
std::string boundary;
net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
&had_charset, &boundary);
TrimString(boundary, " \"", &boundary);
if (!boundary.empty()) {
multipart_delegate_.reset(
new MultipartResponseDelegate(client_, loader_, response, boundary));
}
} else if (info.mime_type == "text/vnd.chromium.ftp-dir" &&
!show_raw_listing) {
ftp_listing_delegate_.reset(
new FtpDirectoryListingResponseDelegate(client_, loader_, response));
}
}
| 171,266 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
Commit Message: Fix bounds checks again.
CWE ID: CWE-119 | cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
| 165,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
ALOGV("configureCodec protected=%d",
(mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
if (!(mFlags & kIgnoreCodecSpecificData)) {
uint32_t type;
const void *data;
size_t size;
if (meta->findData(kKeyESDS, &type, &data, &size)) {
ESDS esds((const char *)data, size);
CHECK_EQ(esds.InitCheck(), (status_t)OK);
const void *codec_specific_data;
size_t codec_specific_data_size;
esds.getCodecSpecificInfo(
&codec_specific_data, &codec_specific_data_size);
addCodecSpecificData(
codec_specific_data, codec_specific_data_size);
} else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseAVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed AVC codec specific data.");
return err;
}
CODEC_LOGI(
"AVC profile = %u (%s), level = %u",
profile, AVCProfileToString(profile), level);
} else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseHEVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed HEVC codec specific data.");
return err;
}
CODEC_LOGI(
"HEVC profile = %u , level = %u",
profile, level);
} else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
addCodecSpecificData(data, size);
} else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusCodecDelay, &type, &data, &size));
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size));
addCodecSpecificData(data, size);
}
}
int32_t bitRate = 0;
if (mIsEncoder) {
CHECK(meta->findInt32(kKeyBitRate, &bitRate));
}
if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
setAMRFormat(false /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
setAMRFormat(true /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
int32_t numChannels, sampleRate, aacProfile;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
aacProfile = OMX_AUDIO_AACObjectNull;
}
int32_t isADTS;
if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
isADTS = false;
}
status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
if (err != OK) {
CODEC_LOGE("setAACFormat() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_MPEG, mMIME)) {
int32_t numChannels, sampleRate;
if (meta->findInt32(kKeyChannelCount, &numChannels)
&& meta->findInt32(kKeySampleRate, &sampleRate)) {
setRawAudioFormat(
mIsEncoder ? kPortIndexInput : kPortIndexOutput,
sampleRate,
numChannels);
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AC3, mMIME)) {
int32_t numChannels;
int32_t sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
status_t err = setAC3Format(numChannels, sampleRate);
if (err != OK) {
CODEC_LOGE("setAC3Format() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
|| !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
int32_t sampleRate;
int32_t numChannels;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
if (!meta->findInt32(kKeySampleRate, &sampleRate)) {
sampleRate = 8000;
}
setG711Format(sampleRate, numChannels);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
CHECK(!mIsEncoder);
int32_t numChannels, sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
}
if (!strncasecmp(mMIME, "video/", 6)) {
if (mIsEncoder) {
setVideoInputFormat(mMIME, meta);
} else {
status_t err = setVideoOutputFormat(
mMIME, meta);
if (err != OK) {
return err;
}
}
}
int32_t maxInputSize;
if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
}
initOutputFormat(meta);
if ((mFlags & kClientNeedsFramebuffer)
&& !strncmp(mComponentName, "OMX.SEC.", 8)) {
OMX_INDEXTYPE index;
status_t err =
mOMX->getExtensionIndex(
mNode,
"OMX.SEC.index.ThumbnailMode",
&index);
if (err != OK) {
return err;
}
OMX_BOOL enable = OMX_TRUE;
err = mOMX->setConfig(mNode, index, &enable, sizeof(enable));
if (err != OK) {
CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') "
"returned error 0x%08x", err);
return err;
}
mQuirks &= ~kOutputBuffersAreUnreadable;
}
if (mNativeWindow != NULL
&& !mIsEncoder
&& !strncasecmp(mMIME, "video/", 6)
&& !strncmp(mComponentName, "OMX.", 4)) {
status_t err = initNativeWindow();
if (err != OK) {
return err;
}
}
return OK;
}
Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits
since it doesn't follow the OMX convention. And remove support
for the kClientNeedsFrameBuffer flag.
Bug: 27207275
Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255
CWE ID: CWE-119 | status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
ALOGV("configureCodec protected=%d",
(mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
if (!(mFlags & kIgnoreCodecSpecificData)) {
uint32_t type;
const void *data;
size_t size;
if (meta->findData(kKeyESDS, &type, &data, &size)) {
ESDS esds((const char *)data, size);
CHECK_EQ(esds.InitCheck(), (status_t)OK);
const void *codec_specific_data;
size_t codec_specific_data_size;
esds.getCodecSpecificInfo(
&codec_specific_data, &codec_specific_data_size);
addCodecSpecificData(
codec_specific_data, codec_specific_data_size);
} else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseAVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed AVC codec specific data.");
return err;
}
CODEC_LOGI(
"AVC profile = %u (%s), level = %u",
profile, AVCProfileToString(profile), level);
} else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
unsigned profile, level;
status_t err;
if ((err = parseHEVCCodecSpecificData(
data, size, &profile, &level)) != OK) {
ALOGE("Malformed HEVC codec specific data.");
return err;
}
CODEC_LOGI(
"HEVC profile = %u , level = %u",
profile, level);
} else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
addCodecSpecificData(data, size);
} else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusCodecDelay, &type, &data, &size));
addCodecSpecificData(data, size);
CHECK(meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size));
addCodecSpecificData(data, size);
}
}
int32_t bitRate = 0;
if (mIsEncoder) {
CHECK(meta->findInt32(kKeyBitRate, &bitRate));
}
if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
setAMRFormat(false /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
setAMRFormat(true /* isWAMR */, bitRate);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
int32_t numChannels, sampleRate, aacProfile;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
aacProfile = OMX_AUDIO_AACObjectNull;
}
int32_t isADTS;
if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
isADTS = false;
}
status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
if (err != OK) {
CODEC_LOGE("setAACFormat() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_MPEG, mMIME)) {
int32_t numChannels, sampleRate;
if (meta->findInt32(kKeyChannelCount, &numChannels)
&& meta->findInt32(kKeySampleRate, &sampleRate)) {
setRawAudioFormat(
mIsEncoder ? kPortIndexInput : kPortIndexOutput,
sampleRate,
numChannels);
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AC3, mMIME)) {
int32_t numChannels;
int32_t sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
status_t err = setAC3Format(numChannels, sampleRate);
if (err != OK) {
CODEC_LOGE("setAC3Format() failed (err = %d)", err);
return err;
}
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
|| !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
int32_t sampleRate;
int32_t numChannels;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
if (!meta->findInt32(kKeySampleRate, &sampleRate)) {
sampleRate = 8000;
}
setG711Format(sampleRate, numChannels);
} else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
CHECK(!mIsEncoder);
int32_t numChannels, sampleRate;
CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
}
if (!strncasecmp(mMIME, "video/", 6)) {
if (mIsEncoder) {
setVideoInputFormat(mMIME, meta);
} else {
status_t err = setVideoOutputFormat(
mMIME, meta);
if (err != OK) {
return err;
}
}
}
int32_t maxInputSize;
if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
}
initOutputFormat(meta);
if (mNativeWindow != NULL
&& !mIsEncoder
&& !strncasecmp(mMIME, "video/", 6)
&& !strncmp(mComponentName, "OMX.", 4)) {
status_t err = initNativeWindow();
if (err != OK) {
return err;
}
}
return OK;
}
| 173,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: int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
features, supported_features);
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
Commit Message:
CWE ID: CWE-119 | int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
int32_t config_len;
uint32_t num;
uint32_t features;
uint32_t supported_features;
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
features, supported_features);
return -1;
}
config_len = qemu_get_be32(f);
if (config_len != vdev->config_len) {
error_report("Unexpected config length 0x%x. Expected 0x%zx",
config_len, vdev->config_len);
return -1;
}
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
| 165,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
Commit Message:
CWE ID: CWE-264 | nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
chmod (ss.str().c_str(), 0600);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
| 165,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
if(subobj_len == 0)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
Commit Message: CVE-2017-13051/RSVP: fix bounds checks for UNI
Fixup the part of rsvp_obj_print() that decodes the GENERALIZED_UNI
object from RFC 3476 Section 3.1 to check the sub-objects inside that
object more thoroughly.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
/* If RFC 3476 Section 3.1 defined that a sub-object of the
* GENERALIZED_UNI RSVP object must have the Length field as
* a multiple of 4, instead of the check below it would be
* better to test total_subobj_len only once before the loop.
* So long as it does not define it and this while loop does
* not implement such a requirement, let's accept that within
* each iteration subobj_len may happen to be a multiple of 1
* and test it and total_subobj_len respectively.
*/
if (total_subobj_len < 4)
goto invalid;
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
/* In addition to what is explained above, the same spec does not
* explicitly say that the same Length field includes the 4-octet
* sub-object header, but as long as this while loop implements it
* as it does include, let's keep the check below consistent with
* the rest of the code.
*/
if(subobj_len < 4 || subobj_len > total_subobj_len)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
| 167,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __mincore_unmapped_range(unsigned long addr, unsigned long end,
struct vm_area_struct *vma, unsigned char *vec)
{
unsigned long nr = (end - addr) >> PAGE_SHIFT;
int i;
if (vma->vm_file) {
pgoff_t pgoff;
pgoff = linear_page_index(vma, addr);
for (i = 0; i < nr; i++, pgoff++)
vec[i] = mincore_page(vma->vm_file->f_mapping, pgoff);
} else {
for (i = 0; i < nr; i++)
vec[i] = 0;
}
return nr;
}
Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages
The semantics of what "in core" means for the mincore() system call are
somewhat unclear, but Linux has always (since 2.3.52, which is when
mincore() was initially done) treated it as "page is available in page
cache" rather than "page is mapped in the mapping".
The problem with that traditional semantic is that it exposes a lot of
system cache state that it really probably shouldn't, and that users
shouldn't really even care about.
So let's try to avoid that information leak by simply changing the
semantics to be that mincore() counts actual mapped pages, not pages
that might be cheaply mapped if they were faulted (note the "might be"
part of the old semantics: being in the cache doesn't actually guarantee
that you can access them without IO anyway, since things like network
filesystems may have to revalidate the cache before use).
In many ways the old semantics were somewhat insane even aside from the
information leak issue. From the very beginning (and that beginning is
a long time ago: 2.3.52 was released in March 2000, I think), the code
had a comment saying
Later we can get more picky about what "in core" means precisely.
and this is that "later". Admittedly it is much later than is really
comfortable.
NOTE! This is a real semantic change, and it is for example known to
change the output of "fincore", since that program literally does a
mmmap without populating it, and then doing "mincore()" on that mapping
that doesn't actually have any pages in it.
I'm hoping that nobody actually has any workflow that cares, and the
info leak is real.
We may have to do something different if it turns out that people have
valid reasons to want the old semantics, and if we can limit the
information leak sanely.
Cc: Kevin Easton <[email protected]>
Cc: Jiri Kosina <[email protected]>
Cc: Masatake YAMATO <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Greg KH <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michal Hocko <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int __mincore_unmapped_range(unsigned long addr, unsigned long end,
| 169,745 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
{
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
Commit Message:
CWE ID: CWE-264 | main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
| 165,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 aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata;
return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg);
}
Commit Message: aacraid: missing capable() check in compat ioctl
In commit d496f94d22d1 ('[SCSI] aacraid: fix security weakness') we
added a check on CAP_SYS_RAWIO to the ioctl. The compat ioctls need the
check as well.
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg);
}
| 165,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: void DelegatedFrameHost::ClearDelegatedFrame() {
EvictDelegatedFrame();
}
Commit Message: mac: Make RWHVMac::ClearCompositorFrame clear locks
Ensure that the BrowserCompositorMac not hold on to a compositor lock
when requested to clear its compositor frame. This lock may be held
indefinitely (if the renderer hangs) and so the frame will never be
cleared.
Bug: 739621
Change-Id: I15d0e82bdf632f3379a48e959f198afb8a4ac218
Reviewed-on: https://chromium-review.googlesource.com/608239
Commit-Queue: ccameron chromium <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#493563}
CWE ID: CWE-20 | void DelegatedFrameHost::ClearDelegatedFrame() {
// Ensure that we are able to swap in a new blank frame to replace any old
// content. This will result in a white flash if we switch back to this
// content.
// https://crbug.com/739621
released_front_lock_.reset();
EvictDelegatedFrame();
}
| 172,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void sem_getref_and_unlock(struct sem_array *sma)
{
ipc_rcu_getref(sma);
ipc_unlock(&(sma)->sem_perm);
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static inline void sem_getref_and_unlock(struct sem_array *sma)
{
WARN_ON_ONCE(!ipc_rcu_getref(sma));
sem_unlock(sma, -1);
}
| 165,974 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,
struct sk_buff *skb,
struct gnttab_copy **gopp)
{
struct gnttab_copy *gop = *gopp;
u16 pending_idx = *((u16 *)skb->data);
struct pending_tx_info *pending_tx_info = netbk->pending_tx_info;
struct xenvif *vif = pending_tx_info[pending_idx].vif;
struct xen_netif_tx_request *txp;
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i, err, start;
/* Check status of header. */
err = gop->status;
if (unlikely(err)) {
pending_ring_idx_t index;
index = pending_index(netbk->pending_prod++);
txp = &pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
}
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < nr_frags; i++) {
int j, newerr;
pending_ring_idx_t index;
pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
/* Check error status: if okay then remember grant handle. */
newerr = (++gop)->status;
if (likely(!newerr)) {
/* Had a previous error? Invalidate this fragment. */
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx);
continue;
}
/* Error on this fragment: respond to client with an error. */
txp = &netbk->pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
/* Not the first error? Preceding frags already invalidated. */
if (err)
continue;
/* First error: invalidate header and preceding fragments. */
pending_idx = *((u16 *)skb->data);
xen_netbk_idx_release(netbk, pending_idx);
for (j = start; j < i; j++) {
pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
xen_netbk_idx_release(netbk, pending_idx);
}
/* Remember the error: invalidate all subsequent fragments. */
err = newerr;
}
*gopp = gop + 1;
return err;
}
Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.
Signed-off-by: Matthew Daley <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Ian Campbell <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,
struct sk_buff *skb,
struct gnttab_copy **gopp)
{
struct gnttab_copy *gop = *gopp;
u16 pending_idx = *((u16 *)skb->data);
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i, err, start;
/* Check status of header. */
err = gop->status;
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < nr_frags; i++) {
int j, newerr;
pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
/* Check error status: if okay then remember grant handle. */
newerr = (++gop)->status;
if (likely(!newerr)) {
/* Had a previous error? Invalidate this fragment. */
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
continue;
}
/* Error on this fragment: respond to client with an error. */
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
/* Not the first error? Preceding frags already invalidated. */
if (err)
continue;
/* First error: invalidate header and preceding fragments. */
pending_idx = *((u16 *)skb->data);
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
for (j = start; j < i; j++) {
pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
}
/* Remember the error: invalidate all subsequent fragments. */
err = newerr;
}
*gopp = gop + 1;
return err;
}
| 166,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 pgx_validate(jas_stream_t *in)
{
uchar buf[PGX_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < PGX_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (buf[0] << 8) | buf[1];
/* Ensure that the signature is correct for this format. */
if (magic != PGX_MAGIC) {
return -1;
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | int pgx_validate(jas_stream_t *in)
{
jas_uchar buf[PGX_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < PGX_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (buf[0] << 8) | buf[1];
/* Ensure that the signature is correct for this format. */
if (magic != PGX_MAGIC) {
return -1;
}
return 0;
}
| 168,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_handler (void *opaque, int fd)
{
struct io_cb_data *data = (struct io_cb_data *) opaque;
engine_uiserver_t uiserver = (engine_uiserver_t) data->handler_value;
gpgme_error_t err = 0;
char *line;
size_t linelen;
do
{
err = assuan_read_line (uiserver->assuan_ctx, &line, &linelen);
if (err)
{
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: error from assuan (%d) getting status line : %s",
fd, err, gpg_strerror (err));
}
else if (linelen >= 3
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& (line[3] == '\0' || line[3] == ' '))
{
if (line[3] == ' ')
err = atoi (&line[4]);
if (! err)
err = gpg_error (GPG_ERR_GENERAL);
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: ERR line - mapped to: %s",
fd, err ? gpg_strerror (err) : "ok");
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
}
else if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value,
GPGME_STATUS_EOF, "");
if (!err && uiserver->colon.fnc && uiserver->colon.any)
{
/* We must tell a colon function about the EOF. We do
this only when we have seen any data lines. Note
that this inlined use of colon data lines will
eventually be changed into using a regular data
channel. */
uiserver->colon.any = 0;
err = uiserver->colon.fnc (uiserver->colon.fnc_value, NULL);
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: OK line - final status: %s",
fd, err ? gpg_strerror (err) : "ok");
_gpgme_io_close (uiserver->status_cb.fd);
return err;
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->colon.fnc)
{
/* We are using the colon handler even for plain inline data
- strange name for that function but for historic reasons
we keep it. */
/* FIXME We can't use this for binary data because we
assume this is a string. For the current usage of colon
output it is correct. */
char *src = line + 2;
char *end = line + linelen;
char *dst;
char **aline = &uiserver->colon.attic.line;
int *alinelen = &uiserver->colon.attic.linelen;
if (uiserver->colon.attic.linesize < *alinelen + linelen + 1)
{
char *newline = realloc (*aline, *alinelen + linelen + 1);
if (!newline)
err = gpg_error_from_syserror ();
else
{
*aline = newline;
uiserver->colon.attic.linesize += linelen + 1;
}
}
if (!err)
{
dst = *aline + *alinelen;
while (!err && src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst = _gpgme_hextobyte (src);
(*alinelen)++;
src += 2;
}
else
{
*dst = *src++;
(*alinelen)++;
}
if (*dst == '\n')
{
/* Terminate the pending line, pass it to the colon
handler and reset it. */
uiserver->colon.any = 1;
if (*alinelen > 1 && *(dst - 1) == '\r')
dst--;
*dst = '\0';
/* FIXME How should we handle the return code? */
err = uiserver->colon.fnc (uiserver->colon.fnc_value, *aline);
if (!err)
{
dst = *aline;
*alinelen = 0;
}
}
else
dst++;
}
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D line; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->inline_data)
{
char *src = line + 2;
char *end = line + linelen;
char *dst = src;
gpgme_ssize_t nwritten;
linelen = 0;
while (src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst++ = _gpgme_hextobyte (src);
src += 2;
}
else
*dst++ = *src++;
linelen++;
}
src = line + 2;
while (linelen > 0)
{
nwritten = gpgme_data_write (uiserver->inline_data, src, linelen);
if (!nwritten || (nwritten < 0 && errno != EINTR)
|| nwritten > linelen)
{
err = gpg_error_from_syserror ();
break;
}
src += nwritten;
linelen -= nwritten;
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D inlinedata; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0)
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value, r, rest);
}
else
fprintf (stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: S line (%s) - final status: %s",
fd, line+2, err? gpg_strerror (err):"ok");
}
else if (linelen >= 7
&& line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
&& line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
&& line[6] == 'E'
&& (line[7] == '\0' || line[7] == ' '))
{
char *keyword = line+7;
while (*keyword == ' ')
keyword++;;
default_inq_cb (uiserver, keyword);
assuan_write_line (uiserver->assuan_ctx, "END");
}
}
while (!err && assuan_pending_line (uiserver->assuan_ctx));
return err;
}
Commit Message:
CWE ID: CWE-119 | status_handler (void *opaque, int fd)
{
struct io_cb_data *data = (struct io_cb_data *) opaque;
engine_uiserver_t uiserver = (engine_uiserver_t) data->handler_value;
gpgme_error_t err = 0;
char *line;
size_t linelen;
do
{
err = assuan_read_line (uiserver->assuan_ctx, &line, &linelen);
if (err)
{
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: error from assuan (%d) getting status line : %s",
fd, err, gpg_strerror (err));
}
else if (linelen >= 3
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& (line[3] == '\0' || line[3] == ' '))
{
if (line[3] == ' ')
err = atoi (&line[4]);
if (! err)
err = gpg_error (GPG_ERR_GENERAL);
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: ERR line - mapped to: %s",
fd, err ? gpg_strerror (err) : "ok");
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
}
else if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value,
GPGME_STATUS_EOF, "");
if (!err && uiserver->colon.fnc && uiserver->colon.any)
{
/* We must tell a colon function about the EOF. We do
this only when we have seen any data lines. Note
that this inlined use of colon data lines will
eventually be changed into using a regular data
channel. */
uiserver->colon.any = 0;
err = uiserver->colon.fnc (uiserver->colon.fnc_value, NULL);
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: OK line - final status: %s",
fd, err ? gpg_strerror (err) : "ok");
_gpgme_io_close (uiserver->status_cb.fd);
return err;
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->colon.fnc)
{
/* We are using the colon handler even for plain inline data
- strange name for that function but for historic reasons
we keep it. */
/* FIXME We can't use this for binary data because we
assume this is a string. For the current usage of colon
output it is correct. */
char *src = line + 2;
char *end = line + linelen;
char *dst;
char **aline = &uiserver->colon.attic.line;
int *alinelen = &uiserver->colon.attic.linelen;
if (uiserver->colon.attic.linesize < *alinelen + linelen + 1)
{
char *newline = realloc (*aline, *alinelen + linelen + 1);
if (!newline)
err = gpg_error_from_syserror ();
else
{
*aline = newline;
uiserver->colon.attic.linesize = *alinelen + linelen + 1;
}
}
if (!err)
{
dst = *aline + *alinelen;
while (!err && src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst = _gpgme_hextobyte (src);
(*alinelen)++;
src += 2;
}
else
{
*dst = *src++;
(*alinelen)++;
}
if (*dst == '\n')
{
/* Terminate the pending line, pass it to the colon
handler and reset it. */
uiserver->colon.any = 1;
if (*alinelen > 1 && *(dst - 1) == '\r')
dst--;
*dst = '\0';
/* FIXME How should we handle the return code? */
err = uiserver->colon.fnc (uiserver->colon.fnc_value, *aline);
if (!err)
{
dst = *aline;
*alinelen = 0;
}
}
else
dst++;
}
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D line; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->inline_data)
{
char *src = line + 2;
char *end = line + linelen;
char *dst = src;
gpgme_ssize_t nwritten;
linelen = 0;
while (src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst++ = _gpgme_hextobyte (src);
src += 2;
}
else
*dst++ = *src++;
linelen++;
}
src = line + 2;
while (linelen > 0)
{
nwritten = gpgme_data_write (uiserver->inline_data, src, linelen);
if (!nwritten || (nwritten < 0 && errno != EINTR)
|| nwritten > linelen)
{
err = gpg_error_from_syserror ();
break;
}
src += nwritten;
linelen -= nwritten;
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D inlinedata; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0)
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value, r, rest);
}
else
fprintf (stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: S line (%s) - final status: %s",
fd, line+2, err? gpg_strerror (err):"ok");
}
else if (linelen >= 7
&& line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
&& line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
&& line[6] == 'E'
&& (line[7] == '\0' || line[7] == ' '))
{
char *keyword = line+7;
while (*keyword == ' ')
keyword++;;
default_inq_cb (uiserver, keyword);
assuan_write_line (uiserver->assuan_ctx, "END");
}
}
while (!err && assuan_pending_line (uiserver->assuan_ctx));
return err;
}
| 165,162 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScopedSharedBufferHandle WrapSharedMemoryHandle(
const base::SharedMemoryHandle& memory_handle,
size_t size,
bool read_only) {
if (!memory_handle.IsValid())
return ScopedSharedBufferHandle();
MojoPlatformHandle platform_handle;
platform_handle.struct_size = sizeof(MojoPlatformHandle);
platform_handle.type = kPlatformSharedBufferHandleType;
#if defined(OS_MACOSX) && !defined(OS_IOS)
platform_handle.value =
static_cast<uint64_t>(memory_handle.GetMemoryObject());
#else
platform_handle.value =
PlatformHandleValueFromPlatformFile(memory_handle.GetHandle());
#endif
MojoPlatformSharedBufferHandleFlags flags =
MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_NONE;
if (read_only)
flags |= MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_READ_ONLY;
MojoSharedBufferGuid guid;
guid.high = memory_handle.GetGUID().GetHighForSerialization();
guid.low = memory_handle.GetGUID().GetLowForSerialization();
MojoHandle mojo_handle;
MojoResult result = MojoWrapPlatformSharedBufferHandle(
&platform_handle, size, &guid, flags, &mojo_handle);
CHECK_EQ(result, MOJO_RESULT_OK);
return ScopedSharedBufferHandle(SharedBufferHandle(mojo_handle));
}
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 | ScopedSharedBufferHandle WrapSharedMemoryHandle(
const base::SharedMemoryHandle& memory_handle,
size_t size,
UnwrappedSharedMemoryHandleProtection protection) {
if (!memory_handle.IsValid())
return ScopedSharedBufferHandle();
MojoPlatformHandle platform_handle;
platform_handle.struct_size = sizeof(MojoPlatformHandle);
platform_handle.type = kPlatformSharedBufferHandleType;
#if defined(OS_MACOSX) && !defined(OS_IOS)
platform_handle.value =
static_cast<uint64_t>(memory_handle.GetMemoryObject());
#else
platform_handle.value =
PlatformHandleValueFromPlatformFile(memory_handle.GetHandle());
#endif
MojoPlatformSharedBufferHandleFlags flags =
MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_NONE;
if (protection == UnwrappedSharedMemoryHandleProtection::kReadOnly)
flags |= MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_HANDLE_IS_READ_ONLY;
MojoSharedBufferGuid guid;
guid.high = memory_handle.GetGUID().GetHighForSerialization();
guid.low = memory_handle.GetGUID().GetLowForSerialization();
MojoHandle mojo_handle;
MojoResult result = MojoWrapPlatformSharedBufferHandle(
&platform_handle, size, &guid, flags, &mojo_handle);
CHECK_EQ(result, MOJO_RESULT_OK);
return ScopedSharedBufferHandle(SharedBufferHandle(mojo_handle));
}
| 172,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: static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119 | static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (!r->iov.iov_base) {
r->buflen = SCSI_DMA_BUF_SIZE;
r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
}
r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
| 166,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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
WORD32 buf_size;
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
/* If dynamic bitstream buffer is not allocated and
* header decode is done, then allocate dynamic bitstream buffer
*/
if((NULL == ps_dec->pu1_bits_buf_dynamic) &&
(ps_dec->i4_header_decoded & 1))
{
WORD32 size;
void *pv_buf;
void *pv_mem_ctxt = ps_dec->pv_mem_ctxt;
size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2);
pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_dynamic = pv_buf;
ps_dec->u4_dynamic_bits_buf_size = size;
}
if(ps_dec->pu1_bits_buf_dynamic)
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic;
buf_size = ps_dec->u4_dynamic_bits_buf_size;
}
else
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static;
buf_size = ps_dec->u4_static_bits_buf_size;
}
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
buflen = MIN(buflen, buf_size);
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
/* Decoder may read extra 8 bytes near end of the frame */
if((buflen + 8) < buf_size)
{
memset(pu1_bitstrm_buf + buflen, 0, 8);
}
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& (ret != IVD_MEM_ALLOC_FAILED)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T))
{
return IV_FAIL;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
Commit Message: Decoder: Do not conceal slices with invalid SPS/PPS
Bug: 28835995
CWE ID: CWE-172 | WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
WORD32 buf_size;
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
/* If dynamic bitstream buffer is not allocated and
* header decode is done, then allocate dynamic bitstream buffer
*/
if((NULL == ps_dec->pu1_bits_buf_dynamic) &&
(ps_dec->i4_header_decoded & 1))
{
WORD32 size;
void *pv_buf;
void *pv_mem_ctxt = ps_dec->pv_mem_ctxt;
size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2);
pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_dynamic = pv_buf;
ps_dec->u4_dynamic_bits_buf_size = size;
}
if(ps_dec->pu1_bits_buf_dynamic)
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic;
buf_size = ps_dec->u4_dynamic_bits_buf_size;
}
else
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static;
buf_size = ps_dec->u4_static_bits_buf_size;
}
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
buflen = MIN(buflen, buf_size);
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
/* Decoder may read extra 8 bytes near end of the frame */
if((buflen + 8) < buf_size)
{
memset(pu1_bitstrm_buf + buflen, 0, 8);
}
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
ps_dec->u4_slice_start_code_found = 0;
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& (ret != IVD_MEM_ALLOC_FAILED)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T))
{
return IV_FAIL;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
| 173,516 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 em_syscall(struct x86_emulate_ctxt *ctxt)
{
struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_EFER, &efer);
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_STAR, &msr_data);
msr_data >>= 32;
cs_sel = (u16)(msr_data & 0xfffc);
ss_sel = (u16)(msr_data + 8);
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip;
if (efer & EFER_LMA) {
#ifdef CONFIG_X86_64
ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF;
ops->get_msr(ctxt,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~(msr_data | EFLG_RF);
#endif
} else {
/* legacy mode */
ops->get_msr(ctxt, MSR_STAR, &msr_data);
ctxt->_eip = (u32)msr_data;
ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF);
}
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: fix missing checks in syscall emulation
On hosts without this patch, 32bit guests will crash (and 64bit guests
may behave in a wrong way) for example by simply executing following
nasm-demo-application:
[bits 32]
global _start
SECTION .text
_start: syscall
(I tested it with winxp and linux - both always crashed)
Disassembly of section .text:
00000000 <_start>:
0: 0f 05 syscall
The reason seems a missing "invalid opcode"-trap (int6) for the
syscall opcode "0f05", which is not available on Intel CPUs
within non-longmodes, as also on some AMD CPUs within legacy-mode.
(depending on CPU vendor, MSR_EFER and cpuid)
Because previous mentioned OSs may not engage corresponding
syscall target-registers (STAR, LSTAR, CSTAR), they remain
NULL and (non trapping) syscalls are leading to multiple
faults and finally crashs.
Depending on the architecture (AMD or Intel) pretended by
guests, various checks according to vendor's documentation
are implemented to overcome the current issue and behave
like the CPUs physical counterparts.
[mtosatti: cleanup/beautify code]
Signed-off-by: Stephan Baerwolf <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: | static int em_syscall(struct x86_emulate_ctxt *ctxt)
{
struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
/* syscall is not available in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_ud(ctxt);
if (!(em_syscall_is_enabled(ctxt)))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_EFER, &efer);
setup_syscalls_segments(ctxt, &cs, &ss);
if (!(efer & EFER_SCE))
return emulate_ud(ctxt);
ops->get_msr(ctxt, MSR_STAR, &msr_data);
msr_data >>= 32;
cs_sel = (u16)(msr_data & 0xfffc);
ss_sel = (u16)(msr_data + 8);
if (efer & EFER_LMA) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->regs[VCPU_REGS_RCX] = ctxt->_eip;
if (efer & EFER_LMA) {
#ifdef CONFIG_X86_64
ctxt->regs[VCPU_REGS_R11] = ctxt->eflags & ~EFLG_RF;
ops->get_msr(ctxt,
ctxt->mode == X86EMUL_MODE_PROT64 ?
MSR_LSTAR : MSR_CSTAR, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
ctxt->eflags &= ~(msr_data | EFLG_RF);
#endif
} else {
/* legacy mode */
ops->get_msr(ctxt, MSR_STAR, &msr_data);
ctxt->_eip = (u32)msr_data;
ctxt->eflags &= ~(EFLG_VM | EFLG_IF | EFLG_RF);
}
return X86EMUL_CONTINUE;
}
| 165,654 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch(vs->clientds.pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->clientds.pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) &&
(vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) &&
(vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 &&
vs->clientds.pf.gshift > 7 &&
vs->clientds.pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
Commit Message:
CWE ID: CWE-125 | static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = vs->client_be;
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch (vs->client_pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->client_pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) &&
(vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) &&
(vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->client_pf.rshift > 7 &&
vs->client_pf.gshift > 7 &&
vs->client_pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
| 165,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
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 | int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
| 169,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: static int kvm_iommu_unmap_memslots(struct kvm *kvm)
{
int idx;
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
idx = srcu_read_lock(&kvm->srcu);
slots = kvm_memslots(kvm);
kvm_for_each_memslot(memslot, slots)
kvm_iommu_put_pages(kvm, memslot->base_gfn, memslot->npages);
srcu_read_unlock(&kvm->srcu, idx);
return 0;
}
Commit Message: KVM: unmap pages from the iommu when slots are removed
commit 32f6daad4651a748a58a3ab6da0611862175722f upstream.
We've been adding new mappings, but not destroying old mappings.
This can lead to a page leak as pages are pinned using
get_user_pages, but only unpinned with put_page if they still
exist in the memslots list on vm shutdown. A memslot that is
destroyed while an iommu domain is enabled for the guest will
therefore result in an elevated page reference count that is
never cleared.
Additionally, without this fix, the iommu is only programmed
with the first translation for a gpa. This can result in
peer-to-peer errors if a mapping is destroyed and replaced by a
new mapping at the same gpa as the iommu will still be pointing
to the original, pinned memory address.
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264 | static int kvm_iommu_unmap_memslots(struct kvm *kvm)
{
int idx;
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
idx = srcu_read_lock(&kvm->srcu);
slots = kvm_memslots(kvm);
kvm_for_each_memslot(memslot, slots)
kvm_iommu_unmap_pages(kvm, memslot);
srcu_read_unlock(&kvm->srcu, idx);
return 0;
}
| 165,617 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo(
const ChildProcessLauncherHelper::Process& process,
bool known_dead) {
ChildProcessTerminationInfo info;
if (!java_peer_avaiable_on_client_thread_)
return info;
Java_ChildProcessLauncherHelperImpl_getTerminationInfo(
AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info));
base::android::ApplicationState app_state =
base::android::ApplicationStatusListener::GetState();
bool app_foreground =
app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES ||
app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES;
if (app_foreground &&
(info.binding_state == base::android::ChildBindingState::MODERATE ||
info.binding_state == base::android::ChildBindingState::STRONG)) {
info.status = base::TERMINATION_STATUS_OOM_PROTECTED;
} else {
info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
}
return info;
}
Commit Message: android: Stop child process in GetTerminationInfo
Android currently abuses TerminationStatus to pass whether process is
"oom protected" rather than whether it has died or not. This confuses
cross-platform code about the state process.
Only TERMINATION_STATUS_STILL_RUNNING is treated as still running, which
android never passes. Also it appears to be ok to kill the process in
getTerminationInfo as it's only called when the child process is dead or
dying. Also posix kills the process on some calls.
Bug: 940245
Change-Id: Id165711848c279bbe77ef8a784c8cf0b14051877
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1516284
Reviewed-by: Robert Sesek <[email protected]>
Reviewed-by: ssid <[email protected]>
Commit-Queue: Bo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#639639}
CWE ID: CWE-664 | ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo(
const ChildProcessLauncherHelper::Process& process,
bool known_dead) {
ChildProcessTerminationInfo info;
if (!java_peer_avaiable_on_client_thread_)
return info;
Java_ChildProcessLauncherHelperImpl_getTerminationInfoAndStop(
AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info));
base::android::ApplicationState app_state =
base::android::ApplicationStatusListener::GetState();
bool app_foreground =
app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES ||
app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES;
if (app_foreground &&
(info.binding_state == base::android::ChildBindingState::MODERATE ||
info.binding_state == base::android::ChildBindingState::STRONG)) {
info.status = base::TERMINATION_STATUS_OOM_PROTECTED;
} else {
info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
}
return info;
}
| 173,016 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 RenderFrameHostManager::CanSubframeSwapProcess(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* dest_instance,
bool was_server_redirect) {
DCHECK(!source_instance || !dest_instance);
GURL resolved_url = dest_url;
if (url::Origin::Create(resolved_url).unique()) {
if (source_instance) {
resolved_url = source_instance->GetSiteURL();
} else if (dest_instance) {
resolved_url = dest_instance->GetSiteURL();
} else {
if (!was_server_redirect)
return false;
}
}
if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(),
resolved_url)) {
DCHECK(!dest_instance ||
dest_instance == render_frame_host_->GetSiteInstance());
return false;
}
return true;
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285 | bool RenderFrameHostManager::CanSubframeSwapProcess(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* dest_instance) {
DCHECK(!source_instance || !dest_instance);
GURL resolved_url = dest_url;
if (url::Origin::Create(resolved_url).unique()) {
if (source_instance) {
resolved_url = source_instance->GetSiteURL();
} else if (dest_instance) {
resolved_url = dest_instance->GetSiteURL();
} else {
// then check whether it is safe to put into the parent frame's process.
// This is the case for about:blank URLs (with or without fragments),
// since they contain no active data. This is also the case for
// about:srcdoc, since such URLs only get active content from their parent
// frame. Using the parent frame's process avoids putting blank frames
// into OOPIFs and preserves scripting for about:srcdoc.
//
// Allow a process swap for other unique origin URLs, such as data: URLs.
// These have active content and may have come from an untrusted source,
// such as a restored frame from a different site or a redirect.
// (Normally, redirects to data: or about: URLs are disallowed as
// example, see ExtensionWebRequestApiTest.WebRequestDeclarative1).)
if (resolved_url.IsAboutBlank() ||
resolved_url == GURL(content::kAboutSrcDocURL)) {
return false;
}
}
}
if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(),
resolved_url)) {
DCHECK(!dest_instance ||
dest_instance == render_frame_host_->GetSiteInstance());
return false;
}
return true;
}
| 173,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture(
const scoped_refptr<H264Picture>& pic) {
scoped_refptr<VaapiDecodeSurface> dec_surface =
H264PictureToVaapiDecodeSurface(pic);
dec_surface->set_visible_rect(pic->visible_rect);
vaapi_dec_->SurfaceReady(dec_surface);
return true;
}
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372}
CWE ID: CWE-362 | bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture(
const scoped_refptr<H264Picture>& pic) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
scoped_refptr<VaapiDecodeSurface> dec_surface =
H264PictureToVaapiDecodeSurface(pic);
dec_surface->set_visible_rect(pic->visible_rect);
vaapi_dec_->SurfaceReady(dec_surface);
return true;
}
| 172,804 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_write_finish_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
int ret;
png_debug(1, "in png_write_finish_row");
/* Next row */
png_ptr->row_number++;
/* See if we are done */
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, go to next pass */
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
if (png_ptr->transformations & PNG_INTERLACE)
{
png_ptr->pass++;
}
else
{
/* Loop until we find a non-zero width or height pass */
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->usr_width = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (png_ptr->transformations & PNG_INTERLACE)
break;
} while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
}
/* Reset the row above the image for the next pass */
if (png_ptr->pass < 7)
{
if (png_ptr->prev_row != NULL)
png_memset(png_ptr->prev_row, 0,
(png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
png_ptr->usr_bit_depth, png_ptr->width)) + 1);
return;
}
}
#endif
/* If we get here, we've just written the last row, so we need
to flush the compressor */
do
{
/* Tell the compressor we are done */
ret = deflate(&png_ptr->zstream, Z_FINISH);
/* Check for an error */
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
}
}
else if (ret != Z_STREAM_END)
{
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Write any extra space */
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
png_ptr->zstream.avail_out);
}
deflateReset(&png_ptr->zstream);
png_ptr->zstream.data_type = Z_BINARY;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_write_finish_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif
int ret;
png_debug(1, "in png_write_finish_row");
/* Next row */
png_ptr->row_number++;
/* See if we are done */
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, go to next pass */
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
if (png_ptr->transformations & PNG_INTERLACE)
{
png_ptr->pass++;
}
else
{
/* Loop until we find a non-zero width or height pass */
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->usr_width = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (png_ptr->transformations & PNG_INTERLACE)
break;
} while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
}
/* Reset the row above the image for the next pass */
if (png_ptr->pass < 7)
{
if (png_ptr->prev_row != NULL)
png_memset(png_ptr->prev_row, 0,
(png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
png_ptr->usr_bit_depth, png_ptr->width)) + 1);
return;
}
}
#endif
/* If we get here, we've just written the last row, so we need
to flush the compressor */
do
{
/* Tell the compressor we are done */
ret = deflate(&png_ptr->zstream, Z_FINISH);
/* Check for an error */
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
}
}
else if (ret != Z_STREAM_END)
{
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Write any extra space */
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
png_ptr->zstream.avail_out);
}
deflateReset(&png_ptr->zstream);
png_ptr->zstream.data_type = Z_BINARY;
}
| 172,195 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID: | RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
| 172,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::CreateVP9Picture() {
scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface();
if (!va_surface)
return nullptr;
return new VaapiVP9Picture(std::move(va_surface));
}
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372}
CWE ID: CWE-362 | VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::CreateVP9Picture() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface();
if (!va_surface)
return nullptr;
return new VaapiVP9Picture(std::move(va_surface));
}
| 172,799 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
hdrlen += printer(ndo, h, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
Commit Message: CVE-2017-13007/PKTAP: Pass a properly updated struct pcap_pkthdr to the sub-dissector.
The sub-dissector expects that the length and captured length will
reflect the actual remaining data in the packet, not the raw amount
including the PKTAP header; pass an updated header, just as we do for
PPI.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
struct pcap_pkthdr nhdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
nhdr = *h;
nhdr.caplen = caplen;
nhdr.len = length;
hdrlen += printer(ndo, &nhdr, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
| 167,888 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_zfs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = NULL;
int dev;
int part;
ulong addr = 0;
disk_partition_t info;
struct blk_desc *dev_desc;
char buf[12];
unsigned long count;
const char *addr_str;
struct zfs_file zfile;
struct device_s vdev;
if (argc < 3)
return CMD_RET_USAGE;
count = 0;
addr = simple_strtoul(argv[3], NULL, 16);
filename = env_get("bootfile");
switch (argc) {
case 3:
addr_str = env_get("loadaddr");
if (addr_str != NULL)
addr = simple_strtoul(addr_str, NULL, 16);
else
addr = CONFIG_SYS_LOAD_ADDR;
break;
case 4:
break;
case 5:
filename = argv[4];
break;
case 6:
filename = argv[4];
count = simple_strtoul(argv[5], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (!filename) {
puts("** No boot file defined **\n");
return 1;
}
part = blk_get_device_part_str(argv[1], argv[2], &dev_desc, &info, 1);
if (part < 0)
return 1;
dev = dev_desc->devnum;
printf("Loading file \"%s\" from %s device %d%c%c\n",
filename, argv[1], dev,
part ? ':' : ' ', part ? part + '0' : ' ');
zfs_set_blk_dev(dev_desc, &info);
vdev.part_length = info.size;
memset(&zfile, 0, sizeof(zfile));
zfile.device = &vdev;
if (zfs_open(&zfile, filename)) {
printf("** File not found %s **\n", filename);
return 1;
}
if ((count < zfile.size) && (count != 0))
zfile.size = (uint64_t)count;
if (zfs_read(&zfile, (char *)addr, zfile.size) != zfile.size) {
printf("** Unable to read \"%s\" from %s %d:%d **\n",
filename, argv[1], dev, part);
zfs_close(&zfile);
return 1;
}
zfs_close(&zfile);
/* Loading ok, update default load address */
image_load_addr = addr;
printf("%llu bytes read\n", zfile.size);
env_set_hex("filesize", zfile.size);
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | static int do_zfs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = NULL;
int dev;
int part;
ulong addr = 0;
disk_partition_t info;
struct blk_desc *dev_desc;
unsigned long count;
const char *addr_str;
struct zfs_file zfile;
struct device_s vdev;
if (argc < 3)
return CMD_RET_USAGE;
count = 0;
addr = simple_strtoul(argv[3], NULL, 16);
filename = env_get("bootfile");
switch (argc) {
case 3:
addr_str = env_get("loadaddr");
if (addr_str != NULL)
addr = simple_strtoul(addr_str, NULL, 16);
else
addr = CONFIG_SYS_LOAD_ADDR;
break;
case 4:
break;
case 5:
filename = argv[4];
break;
case 6:
filename = argv[4];
count = simple_strtoul(argv[5], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (!filename) {
puts("** No boot file defined **\n");
return 1;
}
part = blk_get_device_part_str(argv[1], argv[2], &dev_desc, &info, 1);
if (part < 0)
return 1;
dev = dev_desc->devnum;
printf("Loading file \"%s\" from %s device %d%c%c\n",
filename, argv[1], dev,
part ? ':' : ' ', part ? part + '0' : ' ');
zfs_set_blk_dev(dev_desc, &info);
vdev.part_length = info.size;
memset(&zfile, 0, sizeof(zfile));
zfile.device = &vdev;
if (zfs_open(&zfile, filename)) {
printf("** File not found %s **\n", filename);
return 1;
}
if ((count < zfile.size) && (count != 0))
zfile.size = (uint64_t)count;
if (zfs_read(&zfile, (char *)addr, zfile.size) != zfile.size) {
printf("** Unable to read \"%s\" from %s %d:%d **\n",
filename, argv[1], dev, part);
zfs_close(&zfile);
return 1;
}
zfs_close(&zfile);
/* Loading ok, update default load address */
image_load_addr = addr;
printf("%llu bytes read\n", zfile.size);
env_set_hex("filesize", zfile.size);
return 0;
}
| 169,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndDRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
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 | parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
mode_t new_umask_val;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
{"umask", required_argument, NULL, 'u'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 'u':
new_umask_val = set_umask(optarg);
if (umask_cmdline)
umask_val = new_umask_val;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
| 168,983 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
time_t timestamp = 0;
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
assert(ms != NULL);
memset(ssb, 0, sizeof(php_stream_statbuf));
/* read-only across the board */
ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666;
ssb->sb.st_size = ms->fsize;
ssb->sb.st_mode |= S_IFREG; /* regular file */
#ifdef NETWARE
ssb->sb.st_mtime.tv_sec = timestamp;
ssb->sb.st_atime.tv_sec = timestamp;
ssb->sb.st_ctime.tv_sec = timestamp;
#else
ssb->sb.st_mtime = timestamp;
ssb->sb.st_atime = timestamp;
ssb->sb.st_ctime = timestamp;
#endif
ssb->sb.st_nlink = 1;
ssb->sb.st_rdev = -1;
/* this is only for APC, so use /dev/null device - no chance of conflict there! */
ssb->sb.st_dev = 0xC;
/* generate unique inode number for alias/filename, so no phars will conflict */
ssb->sb.st_ino = 0;
#ifndef PHP_WIN32
ssb->sb.st_blksize = -1;
#endif
#if !defined(PHP_WIN32) && !defined(__BEOS__)
ssb->sb.st_blocks = -1;
#endif
return 0;
}
/* }}} */
Commit Message:
CWE ID: CWE-20 | static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
time_t timestamp = 0;
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
assert(ms != NULL);
memset(ssb, 0, sizeof(php_stream_statbuf));
/* read-only across the board */
ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666;
ssb->sb.st_size = ms->fsize;
ssb->sb.st_mode |= S_IFREG; /* regular file */
#ifdef NETWARE
ssb->sb.st_mtime.tv_sec = timestamp;
ssb->sb.st_atime.tv_sec = timestamp;
ssb->sb.st_ctime.tv_sec = timestamp;
#else
ssb->sb.st_mtime = timestamp;
ssb->sb.st_atime = timestamp;
ssb->sb.st_ctime = timestamp;
#endif
ssb->sb.st_nlink = 1;
ssb->sb.st_rdev = -1;
/* this is only for APC, so use /dev/null device - no chance of conflict there! */
ssb->sb.st_dev = 0xC;
/* generate unique inode number for alias/filename, so no phars will conflict */
ssb->sb.st_ino = 0;
#ifndef PHP_WIN32
ssb->sb.st_blksize = -1;
#endif
#if !defined(PHP_WIN32) && !defined(__BEOS__)
ssb->sb.st_blocks = -1;
#endif
return 0;
}
/* }}} */
| 165,477 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code,
uintptr_t abort_msg_address, bool dump_sibling_threads,
bool* detach_failed, int* total_sleep_time_usec) {
log_t log;
log.current_tid = tid;
log.crashed_tid = tid;
if ((mkdir(TOMBSTONE_DIR, 0755) == -1) && (errno != EEXIST)) {
_LOG(&log, logtype::ERROR, "failed to create %s: %s\n", TOMBSTONE_DIR, strerror(errno));
}
if (chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM) == -1) {
_LOG(&log, logtype::ERROR, "failed to change ownership of %s: %s\n", TOMBSTONE_DIR, strerror(errno));
}
int fd = -1;
char* path = NULL;
if (selinux_android_restorecon(TOMBSTONE_DIR, 0) == 0) {
path = find_and_open_tombstone(&fd);
} else {
_LOG(&log, logtype::ERROR, "Failed to restore security context, not writing tombstone.\n");
}
if (fd < 0) {
_LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n");
*detach_failed = false;
return NULL;
}
log.tfd = fd;
int amfd = activity_manager_connect();
log.amfd = amfd;
*detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address,
dump_sibling_threads, total_sleep_time_usec);
ALOGI("\nTombstone written to: %s\n", path);
close(amfd);
close(fd);
return path;
}
Commit Message: Don't create tombstone directory.
Partial backport of cf79748.
Bug: http://b/26403620
Change-Id: Ib877ab6cfab6aef079830c5a50ba81141ead35ee
CWE ID: CWE-264 | char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code,
uintptr_t abort_msg_address, bool dump_sibling_threads,
bool* detach_failed, int* total_sleep_time_usec) {
log_t log;
log.current_tid = tid;
log.crashed_tid = tid;
int fd = -1;
char* path = find_and_open_tombstone(&fd);
if (fd < 0) {
_LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n");
*detach_failed = false;
return NULL;
}
log.tfd = fd;
int amfd = activity_manager_connect();
log.amfd = amfd;
*detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address,
dump_sibling_threads, total_sleep_time_usec);
ALOGI("\nTombstone written to: %s\n", path);
close(amfd);
close(fd);
return path;
}
| 173,890 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset,
guint32 str_tbl, guint8 *level,
guint8 *codepage_stag, guint8 *codepage_attr)
{
guint32 tvb_len = tvb_reported_length (tvb);
guint32 off = offset;
guint32 len;
guint str_len;
guint32 ent;
guint32 idx;
guint8 peek;
guint32 tag_len; /* Length of the idx (uintvar) from a LITERAL tag */
guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */
guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */
const char *tag_save_literal; /* Will contain the LITERAL tag identity */
const char *tag_new_literal; /* Will contain the LITERAL tag identity */
char *tag_save_buf = NULL; /* Will contain "tag_0x%02X" */
char *tag_new_buf = NULL; /* Will contain "tag_0x%02X" */
guint8 parsing_tag_content = FALSE; /* Are we parsing content from a
tag with content: <x>Content</x>
The initial state is FALSE.
This state will trigger recursion. */
tag_save_literal = NULL; /* Prevents compiler warning */
DebugLog(("parse_wbxml_tag (level = %u, offset = %u)\n", *level, offset));
while (off < tvb_len) {
peek = tvb_get_guint8 (tvb, off);
DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len));
if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG
but not the LITERAL tokens */
case 0x00: /* SWITCH_PAGE */
*codepage_stag = tvb_get_guint8 (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 2,
" | Tag | T -->%3d "
"| SWITCH_PAGE (Tag code page) "
"|",
*codepage_stag);
off += 2;
break;
case 0x01: /* END: only possible for Tag with Content */
if (tag_save_known) { /* Known TAG */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| END (Known Tag 0x%02X) "
"| %s</%s>",
*level, *codepage_stag, tag_save_known,
Indent (*level),
tag_save_literal); /* We already looked it up! */
} else { /* Literal TAG */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| END (Literal Tag) "
"| %s</%s>",
*level, *codepage_stag, Indent (*level),
tag_save_literal ? tag_save_literal : "");
}
(*level)--;
off++;
/* Reset code page: not needed as return from recursion */
DebugLog(("STAG: level = %u, Return: len = %u\n",
*level, off - offset));
return (off - offset);
case 0x02: /* ENTITY */
ent = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| ENTITY "
"| %s'&#%u;'",
*level, *codepage_stag, Indent (*level), ent);
off += 1+len;
break;
case 0x03: /* STR_I */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| STR_I (Inline string) "
"| %s\'%s\'",
*level, *codepage_stag, Indent(*level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x40: /* EXT_I_0 */
case 0x41: /* EXT_I_1 */
case 0x42: /* EXT_I_2 */
/* Extension tokens */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| EXT_I_%1x (Extension Token) "
"| %s(Inline string extension: \'%s\')",
*level, *codepage_stag, peek & 0x0f, Indent (*level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x43: /* PI */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| PI (XML Processing Instruction) "
"| %s<?xml",
*level, *codepage_stag, Indent (*level));
len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl,
*level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (PI) "
"| %s?>",
*level, *codepage_stag, Indent (*level));
break;
case 0x80: /* EXT_T_0 */
case 0x81: /* EXT_T_1 */
case 0x82: /* EXT_T_2 */
/* Extension tokens */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| EXT_T_%1x (Extension Token) "
"| %s(Extension Token, integer value: %u)",
*level, *codepage_stag, peek & 0x0f, Indent (*level),
idx);
off += 1+len;
break;
case 0x83: /* STR_T */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| STR_T (Tableref string) "
"| %s\'%s\'",
*level, *codepage_stag, Indent (*level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
case 0xC0: /* EXT_0 */
case 0xC1: /* EXT_1 */
case 0xC2: /* EXT_2 */
/* Extension tokens */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| EXT_%1x (Extension Token) "
"| %s(Single-byte extension)",
*level, *codepage_stag, peek & 0x0f, Indent (*level));
off++;
break;
case 0xC3: /* OPAQUE - WBXML 1.1 and newer */
if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1 + len + idx,
" %3d | Tag | T %3d "
"| OPAQUE (Opaque data) "
"| %s(%d bytes of opaque data)",
*level, *codepage_stag, Indent (*level), idx);
off += 1+len+idx;
} else { /* WBXML 1.0 - RESERVED_2 token (invalid) */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| RESERVED_2 (Invalid Token!) "
"| WBXML 1.0 parsing stops here.",
*level, *codepage_stag);
/* Stop processing as it is impossible to parse now */
off = tvb_len;
DebugLog(("STAG: level = %u, Return: len = %u\n",
*level, off - offset));
return (off - offset);
}
break;
/* No default clause, as all cases have been treated */
} else { /* LITERAL or Known TAG */
/* We must store the initial tag, and also retrieve the new tag.
* For efficiency reasons, we store the literal tag representation
* for known tags too, so we can easily close the tag without the
* need of a new lookup and avoiding storage of token codepage.
*
* There are 4 possibilities:
*
* 1. Known tag followed by a known tag
* 2. Known tag followed by a LITERAL tag
* 3. LITERAL tag followed by Known tag
* 4. LITERAL tag followed by LITERAL tag
*/
/* Store the new tag */
tag_len = 0;
if ((peek & 0x3F) == 4) { /* LITERAL */
DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u)"
" - TableRef follows!\n", peek, off));
idx = tvb_get_guintvar (tvb, off+1, &tag_len);
str_len = tvb_strsize (tvb, str_tbl+idx);
tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len);
tag_new_known = 0; /* invalidate known tag_new */
} else { /* Known tag */
tag_new_known = peek & 0x3F;
tag_new_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X",
tag_new_known);
tag_new_literal = tag_new_buf;
/* Stored looked up tag name string */
}
/* Parsing of TAG starts HERE */
if (peek & 0x40) { /* Content present */
/* Content follows
* [!] An explicit END token is expected in these cases!
* ==> Recursion possible if we encounter a tag with content;
* recursion will return at the explicit END token.
*/
if (parsing_tag_content) { /* Recurse */
DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off));
/* Do not process the attribute list:
* recursion will take care of it */
(*level)++;
len = parse_wbxml_tag (tree, tvb, off, str_tbl, level,
codepage_stag, codepage_attr);
off += len;
} else { /* Now we will have content to parse */
/* Save the start tag so we can properly close it later. */
if ((peek & 0x3F) == 4) { /* Literal tag */
tag_save_literal = tag_new_literal;
tag_save_known = 0;
} else { /* Known tag */
tag_save_known = tag_new_known;
tag_save_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X",
tag_new_known);
tag_save_literal = tag_save_buf;
/* The last statement avoids needless lookups */
}
/* Process the attribute list if present */
if (peek & 0x80) { /* Content and Attribute list present */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (AC) "
"| %s<%s",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_AC (Literal tag) (AC) "
"| %s<%s",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (attribute list) "
"| %s>",
*level, *codepage_stag, Indent (*level));
} else { /* Content, no Attribute list */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (.C) "
"| %s<%s>",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_C (Literal Tag) (.C) "
"| %s<%s>",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
}
/* The data that follows in the parsing process
* represents content for the opening tag
* we've just processed in the lines above.
* Next time we encounter a tag with content: recurse
*/
parsing_tag_content = TRUE;
DebugLog(("Tag in Tag - No recursion this time! "
"(off = %u)\n", off));
}
} else { /* No Content */
DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off));
(*level)++;
if (peek & 0x80) { /* No Content, Attribute list present */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (A.) "
"| %s<%s",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (Known Tag) "
"| %s/>",
*level, *codepage_stag, Indent (*level));
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_A (Literal Tag) (A.) "
"| %s<%s",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (Literal Tag) "
"| %s/>",
*level, *codepage_stag, Indent (*level));
}
} else { /* No Content, No Attribute list */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02x (..) "
"| %s<%s />",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL (Literal Tag) (..) "
"| %s<%s />",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
}
(*level)--;
/* TODO: Do I have to reset code page here? */
}
} /* if (tag & 0x3F) >= 5 */
} /* while */
DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n",
*level, off - offset));
return (off - offset);
}
Commit Message: WBXML: add a basic sanity check for offset overflow
This is a naive approach allowing to detact that something went wrong,
without the need to replace all proto_tree_add_text() calls as what was
done in master-2.0 branch.
Bug: 12408
Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108
Reviewed-on: https://code.wireshark.org/review/15310
Reviewed-by: Michael Mann <[email protected]>
Reviewed-by: Pascal Quantin <[email protected]>
CWE ID: CWE-119 | parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset,
guint32 str_tbl, guint8 *level,
guint8 *codepage_stag, guint8 *codepage_attr)
{
guint32 tvb_len = tvb_reported_length (tvb);
guint32 off = offset, last_off;
guint32 len;
guint str_len;
guint32 ent;
guint32 idx;
guint8 peek;
guint32 tag_len; /* Length of the idx (uintvar) from a LITERAL tag */
guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */
guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */
const char *tag_save_literal; /* Will contain the LITERAL tag identity */
const char *tag_new_literal; /* Will contain the LITERAL tag identity */
char *tag_save_buf = NULL; /* Will contain "tag_0x%02X" */
char *tag_new_buf = NULL; /* Will contain "tag_0x%02X" */
guint8 parsing_tag_content = FALSE; /* Are we parsing content from a
tag with content: <x>Content</x>
The initial state is FALSE.
This state will trigger recursion. */
tag_save_literal = NULL; /* Prevents compiler warning */
DebugLog(("parse_wbxml_tag (level = %u, offset = %u)\n", *level, offset));
last_off = off;
while (off < tvb_len) {
peek = tvb_get_guint8 (tvb, off);
DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len));
if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG
but not the LITERAL tokens */
case 0x00: /* SWITCH_PAGE */
*codepage_stag = tvb_get_guint8 (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 2,
" | Tag | T -->%3d "
"| SWITCH_PAGE (Tag code page) "
"|",
*codepage_stag);
off += 2;
break;
case 0x01: /* END: only possible for Tag with Content */
if (tag_save_known) { /* Known TAG */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| END (Known Tag 0x%02X) "
"| %s</%s>",
*level, *codepage_stag, tag_save_known,
Indent (*level),
tag_save_literal); /* We already looked it up! */
} else { /* Literal TAG */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| END (Literal Tag) "
"| %s</%s>",
*level, *codepage_stag, Indent (*level),
tag_save_literal ? tag_save_literal : "");
}
(*level)--;
off++;
/* Reset code page: not needed as return from recursion */
DebugLog(("STAG: level = %u, Return: len = %u\n",
*level, off - offset));
return (off - offset);
case 0x02: /* ENTITY */
ent = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| ENTITY "
"| %s'&#%u;'",
*level, *codepage_stag, Indent (*level), ent);
off += 1+len;
break;
case 0x03: /* STR_I */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| STR_I (Inline string) "
"| %s\'%s\'",
*level, *codepage_stag, Indent(*level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x40: /* EXT_I_0 */
case 0x41: /* EXT_I_1 */
case 0x42: /* EXT_I_2 */
/* Extension tokens */
len = tvb_strsize (tvb, off+1);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| EXT_I_%1x (Extension Token) "
"| %s(Inline string extension: \'%s\')",
*level, *codepage_stag, peek & 0x0f, Indent (*level),
tvb_format_text (tvb, off+1, len-1));
off += 1+len;
break;
case 0x43: /* PI */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| PI (XML Processing Instruction) "
"| %s<?xml",
*level, *codepage_stag, Indent (*level));
len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl,
*level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (PI) "
"| %s?>",
*level, *codepage_stag, Indent (*level));
break;
case 0x80: /* EXT_T_0 */
case 0x81: /* EXT_T_1 */
case 0x82: /* EXT_T_2 */
/* Extension tokens */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| EXT_T_%1x (Extension Token) "
"| %s(Extension Token, integer value: %u)",
*level, *codepage_stag, peek & 0x0f, Indent (*level),
idx);
off += 1+len;
break;
case 0x83: /* STR_T */
idx = tvb_get_guintvar (tvb, off+1, &len);
str_len = tvb_strsize (tvb, str_tbl+idx);
proto_tree_add_text (tree, tvb, off, 1+len,
" %3d | Tag | T %3d "
"| STR_T (Tableref string) "
"| %s\'%s\'",
*level, *codepage_stag, Indent (*level),
tvb_format_text (tvb, str_tbl+idx, str_len-1));
off += 1+len;
break;
case 0xC0: /* EXT_0 */
case 0xC1: /* EXT_1 */
case 0xC2: /* EXT_2 */
/* Extension tokens */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| EXT_%1x (Extension Token) "
"| %s(Single-byte extension)",
*level, *codepage_stag, peek & 0x0f, Indent (*level));
off++;
break;
case 0xC3: /* OPAQUE - WBXML 1.1 and newer */
if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */
idx = tvb_get_guintvar (tvb, off+1, &len);
proto_tree_add_text (tree, tvb, off, 1 + len + idx,
" %3d | Tag | T %3d "
"| OPAQUE (Opaque data) "
"| %s(%d bytes of opaque data)",
*level, *codepage_stag, Indent (*level), idx);
off += 1+len+idx;
} else { /* WBXML 1.0 - RESERVED_2 token (invalid) */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| RESERVED_2 (Invalid Token!) "
"| WBXML 1.0 parsing stops here.",
*level, *codepage_stag);
/* Stop processing as it is impossible to parse now */
off = tvb_len;
DebugLog(("STAG: level = %u, Return: len = %u\n",
*level, off - offset));
return (off - offset);
}
break;
/* No default clause, as all cases have been treated */
} else { /* LITERAL or Known TAG */
/* We must store the initial tag, and also retrieve the new tag.
* For efficiency reasons, we store the literal tag representation
* for known tags too, so we can easily close the tag without the
* need of a new lookup and avoiding storage of token codepage.
*
* There are 4 possibilities:
*
* 1. Known tag followed by a known tag
* 2. Known tag followed by a LITERAL tag
* 3. LITERAL tag followed by Known tag
* 4. LITERAL tag followed by LITERAL tag
*/
/* Store the new tag */
tag_len = 0;
if ((peek & 0x3F) == 4) { /* LITERAL */
DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u)"
" - TableRef follows!\n", peek, off));
idx = tvb_get_guintvar (tvb, off+1, &tag_len);
str_len = tvb_strsize (tvb, str_tbl+idx);
tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len);
tag_new_known = 0; /* invalidate known tag_new */
} else { /* Known tag */
tag_new_known = peek & 0x3F;
tag_new_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X",
tag_new_known);
tag_new_literal = tag_new_buf;
/* Stored looked up tag name string */
}
/* Parsing of TAG starts HERE */
if (peek & 0x40) { /* Content present */
/* Content follows
* [!] An explicit END token is expected in these cases!
* ==> Recursion possible if we encounter a tag with content;
* recursion will return at the explicit END token.
*/
if (parsing_tag_content) { /* Recurse */
DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off));
/* Do not process the attribute list:
* recursion will take care of it */
(*level)++;
len = parse_wbxml_tag (tree, tvb, off, str_tbl, level,
codepage_stag, codepage_attr);
off += len;
} else { /* Now we will have content to parse */
/* Save the start tag so we can properly close it later. */
if ((peek & 0x3F) == 4) { /* Literal tag */
tag_save_literal = tag_new_literal;
tag_save_known = 0;
} else { /* Known tag */
tag_save_known = tag_new_known;
tag_save_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X",
tag_new_known);
tag_save_literal = tag_save_buf;
/* The last statement avoids needless lookups */
}
/* Process the attribute list if present */
if (peek & 0x80) { /* Content and Attribute list present */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (AC) "
"| %s<%s",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_AC (Literal tag) (AC) "
"| %s<%s",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (attribute list) "
"| %s>",
*level, *codepage_stag, Indent (*level));
} else { /* Content, no Attribute list */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (.C) "
"| %s<%s>",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_C (Literal Tag) (.C) "
"| %s<%s>",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
}
/* The data that follows in the parsing process
* represents content for the opening tag
* we've just processed in the lines above.
* Next time we encounter a tag with content: recurse
*/
parsing_tag_content = TRUE;
DebugLog(("Tag in Tag - No recursion this time! "
"(off = %u)\n", off));
}
} else { /* No Content */
DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off));
(*level)++;
if (peek & 0x80) { /* No Content, Attribute list present */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02X (A.) "
"| %s<%s",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (Known Tag) "
"| %s/>",
*level, *codepage_stag, Indent (*level));
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL_A (Literal Tag) (A.) "
"| %s<%s",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
len = parse_wbxml_attribute_list (tree, tvb,
off, str_tbl, *level, codepage_attr);
/* Check that there is still room in packet */
off += len;
if (off >= tvb_len) {
DebugLog(("STAG: level = %u, ThrowException: "
"len = %u (short frame)\n",
*level, off - offset));
/*
* TODO - Do we need to free g_malloc()ed memory?
*/
THROW(ReportedBoundsError);
}
proto_tree_add_text (tree, tvb, off-1, 1,
" %3d | Tag | T %3d "
"| END (Literal Tag) "
"| %s/>",
*level, *codepage_stag, Indent (*level));
}
} else { /* No Content, No Attribute list */
if (tag_new_known) { /* Known tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| Known Tag 0x%02x (..) "
"| %s<%s />",
*level, *codepage_stag, tag_new_known,
Indent (*level), tag_new_literal);
/* Tag string already looked up earlier! */
off++;
} else { /* LITERAL tag */
proto_tree_add_text (tree, tvb, off, 1,
" %3d | Tag | T %3d "
"| LITERAL (Literal Tag) (..) "
"| %s<%s />",
*level, *codepage_stag, Indent (*level),
tag_new_literal);
off += 1 + tag_len;
}
}
(*level)--;
/* TODO: Do I have to reset code page here? */
}
} /* if (tag & 0x3F) >= 5 */
if (off < last_off) {
THROW(ReportedBoundsError);
}
last_off = off;
} /* while */
DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n",
*level, off - offset));
return (off - offset);
}
| 167,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
BMPInfo
bmp_info;
const char
*option;
const StringInfo
*profile;
MagickBooleanType
have_color_info,
status;
MagickOffsetType
scene;
MemoryInfo
*pixel_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
bytes_per_line,
type;
ssize_t
y;
unsigned char
*bmp_data,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
type=4;
if (LocaleCompare(image_info->magick,"BMP2") == 0)
type=2;
else
if (LocaleCompare(image_info->magick,"BMP3") == 0)
type=3;
option=GetImageOption(image_info,"bmp:format");
if (option != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",option);
if (LocaleCompare(option,"bmp2") == 0)
type=2;
if (LocaleCompare(option,"bmp3") == 0)
type=3;
if (LocaleCompare(option,"bmp4") == 0)
type=4;
}
scene=0;
do
{
/*
Initialize BMP raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
bmp_info.file_size=14+12;
if (type > 2)
bmp_info.file_size+=28;
bmp_info.offset_bits=bmp_info.file_size;
bmp_info.compression=BI_RGB;
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->storage_class != DirectClass)
{
/*
Colormapped BMP raster.
*/
bmp_info.bits_per_pixel=8;
if (image->colors <= 2)
bmp_info.bits_per_pixel=1;
else
if (image->colors <= 16)
bmp_info.bits_per_pixel=4;
else
if (image->colors <= 256)
bmp_info.bits_per_pixel=8;
if (image_info->compression == RLECompression)
bmp_info.bits_per_pixel=8;
bmp_info.number_colors=1U << bmp_info.bits_per_pixel;
if (image->alpha_trait != UndefinedPixelTrait)
(void) SetImageStorageClass(image,DirectClass,exception);
else
if ((size_t) bmp_info.number_colors < image->colors)
(void) SetImageStorageClass(image,DirectClass,exception);
else
{
bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);
if (type > 2)
{
bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);
}
}
}
if (image->storage_class == DirectClass)
{
/*
Full color BMP raster.
*/
bmp_info.number_colors=0;
bmp_info.bits_per_pixel=(unsigned short)
((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24);
bmp_info.compression=(unsigned int) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB);
if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait))
{
option=GetImageOption(image_info,"bmp3:alpha");
if (IsStringTrue(option))
bmp_info.bits_per_pixel=32;
}
}
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
bmp_info.ba_offset=0;
profile=GetImageProfile(image,"icc");
have_color_info=(image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue :
MagickFalse;
if (type == 2)
bmp_info.size=12;
else
if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) &&
(have_color_info == MagickFalse)))
{
type=3;
bmp_info.size=40;
}
else
{
int
extra_size;
bmp_info.size=108;
extra_size=68;
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
bmp_info.size=124;
extra_size+=16;
}
bmp_info.file_size+=extra_size;
bmp_info.offset_bits+=extra_size;
}
bmp_info.width=(ssize_t) image->columns;
bmp_info.height=(ssize_t) image->rows;
bmp_info.planes=1;
bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);
bmp_info.file_size+=bmp_info.image_size;
bmp_info.x_pixels=75*39;
bmp_info.y_pixels=75*39;
switch (image->units)
{
case UndefinedResolution:
case PixelsPerInchResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
break;
}
case PixelsPerCentimeterResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
break;
}
}
bmp_info.colors_important=bmp_info.number_colors;
/*
Convert MIFF to BMP raster pixels.
*/
pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size);
switch (bmp_info.bits_per_pixel)
{
case 1:
{
size_t
bit,
byte;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
ssize_t
offset;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00;
bit++;
if (bit == 8)
{
*q++=(unsigned char) byte;
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
*q++=(unsigned char) (byte << (8-bit));
x++;
}
offset=(ssize_t) (image->columns+7)/8;
for (x=offset; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 4:
{
size_t
byte,
nibble;
ssize_t
offset;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
nibble=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=4;
byte|=((size_t) GetPixelIndex(image,p) & 0x0f);
nibble++;
if (nibble == 2)
{
*q++=(unsigned char) byte;
nibble=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (nibble != 0)
{
*q++=(unsigned char) (byte << 4);
x++;
}
offset=(ssize_t) (image->columns+1)/2;
for (x=offset; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 8:
{
/*
Convert PseudoClass packet to BMP pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert DirectClass packet to ARGB8888 pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
if ((type > 2) && (bmp_info.bits_per_pixel == 8))
if (image_info->compression != NoCompression)
{
MemoryInfo
*rle_info;
/*
Convert run-length encoded raster pixels.
*/
rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),
(image->rows+2)*sizeof(*pixels));
if (rle_info == (MemoryInfo *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);
bmp_info.file_size-=bmp_info.image_size;
bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,
pixels,bmp_data);
bmp_info.file_size+=bmp_info.image_size;
pixel_info=RelinquishVirtualMemory(pixel_info);
pixel_info=rle_info;
pixels=bmp_data;
bmp_info.compression=BI_RLE8;
}
/*
Write BMP for Windows, all versions, 14-byte header.
*/
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing BMP version %.20g datastream",(double) type);
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=DirectClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image depth=%.20g",(double) image->depth);
if (image->alpha_trait != UndefinedPixelTrait)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=MagickFalse");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel);
switch ((int) bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RGB");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_BITFIELDS");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=UNKNOWN (%lu)",bmp_info.compression);
break;
}
}
if (bmp_info.number_colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=unspecified");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=%lu",bmp_info.number_colors);
}
(void) WriteBlob(image,2,(unsigned char *) "BM");
(void) WriteBlobLSBLong(image,bmp_info.file_size);
(void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */
(void) WriteBlobLSBLong(image,bmp_info.offset_bits);
if (type == 2)
{
/*
Write 12-byte version 2 bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);
(void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
}
else
{
/*
Write 40-byte version 3+ bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width);
(void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
(void) WriteBlobLSBLong(image,bmp_info.compression);
(void) WriteBlobLSBLong(image,bmp_info.image_size);
(void) WriteBlobLSBLong(image,bmp_info.x_pixels);
(void) WriteBlobLSBLong(image,bmp_info.y_pixels);
(void) WriteBlobLSBLong(image,bmp_info.number_colors);
(void) WriteBlobLSBLong(image,bmp_info.colors_important);
}
if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) ||
(have_color_info != MagickFalse)))
{
/*
Write the rest of the 108-byte BMP Version 4 header.
*/
(void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */
(void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */
(void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */
(void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */
(void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.red_primary.x+
image->chromaticity.red_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.green_primary.x+
image->chromaticity.green_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.blue_primary.x+
image->chromaticity.blue_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.x*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.y*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.z*0x10000));
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
ssize_t
intent;
switch ((int) image->rendering_intent)
{
case SaturationIntent:
{
intent=LCS_GM_BUSINESS;
break;
}
case RelativeIntent:
{
intent=LCS_GM_GRAPHICS;
break;
}
case PerceptualIntent:
{
intent=LCS_GM_IMAGES;
break;
}
case AbsoluteIntent:
{
intent=LCS_GM_ABS_COLORIMETRIC;
break;
}
default:
{
intent=0;
break;
}
}
(void) WriteBlobLSBLong(image,(unsigned int) intent);
(void) WriteBlobLSBLong(image,0x00); /* dummy profile data */
(void) WriteBlobLSBLong(image,0x00); /* dummy profile length */
(void) WriteBlobLSBLong(image,0x00); /* reserved */
}
}
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
/*
Dump colormap to file.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Colormap: %.20g entries",(double) image->colors);
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<
bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
q=bmp_colormap;
for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
if (type > 2)
*q++=(unsigned char) 0x0;
}
for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)
{
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
if (type > 2)
*q++=(unsigned char) 0x00;
}
if (type <= 2)
(void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
else
(void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Pixels: %lu bytes",bmp_info.image_size);
(void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: Prevent buffer overflow in BMP coder (bug report from pwchen of tencent).
CWE ID: CWE-190 | static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
BMPInfo
bmp_info;
const char
*option;
const StringInfo
*profile;
MagickBooleanType
have_color_info,
status;
MagickOffsetType
scene;
MemoryInfo
*pixel_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
bytes_per_line,
type;
ssize_t
y;
unsigned char
*bmp_data,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
type=4;
if (LocaleCompare(image_info->magick,"BMP2") == 0)
type=2;
else
if (LocaleCompare(image_info->magick,"BMP3") == 0)
type=3;
option=GetImageOption(image_info,"bmp:format");
if (option != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",option);
if (LocaleCompare(option,"bmp2") == 0)
type=2;
if (LocaleCompare(option,"bmp3") == 0)
type=3;
if (LocaleCompare(option,"bmp4") == 0)
type=4;
}
scene=0;
do
{
/*
Initialize BMP raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
bmp_info.file_size=14+12;
if (type > 2)
bmp_info.file_size+=28;
bmp_info.offset_bits=bmp_info.file_size;
bmp_info.compression=BI_RGB;
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->storage_class != DirectClass)
{
/*
Colormapped BMP raster.
*/
bmp_info.bits_per_pixel=8;
if (image->colors <= 2)
bmp_info.bits_per_pixel=1;
else
if (image->colors <= 16)
bmp_info.bits_per_pixel=4;
else
if (image->colors <= 256)
bmp_info.bits_per_pixel=8;
if (image_info->compression == RLECompression)
bmp_info.bits_per_pixel=8;
bmp_info.number_colors=1U << bmp_info.bits_per_pixel;
if (image->alpha_trait != UndefinedPixelTrait)
(void) SetImageStorageClass(image,DirectClass,exception);
else
if ((size_t) bmp_info.number_colors < image->colors)
(void) SetImageStorageClass(image,DirectClass,exception);
else
{
bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);
if (type > 2)
{
bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);
}
}
}
if (image->storage_class == DirectClass)
{
/*
Full color BMP raster.
*/
bmp_info.number_colors=0;
bmp_info.bits_per_pixel=(unsigned short)
((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24);
bmp_info.compression=(unsigned int) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB);
if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait))
{
option=GetImageOption(image_info,"bmp3:alpha");
if (IsStringTrue(option))
bmp_info.bits_per_pixel=32;
}
}
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
bmp_info.ba_offset=0;
profile=GetImageProfile(image,"icc");
have_color_info=(image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue :
MagickFalse;
if (type == 2)
bmp_info.size=12;
else
if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) &&
(have_color_info == MagickFalse)))
{
type=3;
bmp_info.size=40;
}
else
{
int
extra_size;
bmp_info.size=108;
extra_size=68;
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
bmp_info.size=124;
extra_size+=16;
}
bmp_info.file_size+=extra_size;
bmp_info.offset_bits+=extra_size;
}
if ((image->columns != (signed int) image->columns) ||
(image->rows != (signed int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
bmp_info.width=(ssize_t) image->columns;
bmp_info.height=(ssize_t) image->rows;
bmp_info.planes=1;
bmp_info.image_size=(unsigned long) (bytes_per_line*image->rows);
bmp_info.file_size+=bmp_info.image_size;
bmp_info.x_pixels=75*39;
bmp_info.y_pixels=75*39;
switch (image->units)
{
case UndefinedResolution:
case PixelsPerInchResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
break;
}
case PixelsPerCentimeterResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
break;
}
}
bmp_info.colors_important=bmp_info.number_colors;
/*
Convert MIFF to BMP raster pixels.
*/
pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size);
switch (bmp_info.bits_per_pixel)
{
case 1:
{
size_t
bit,
byte;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
ssize_t
offset;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00;
bit++;
if (bit == 8)
{
*q++=(unsigned char) byte;
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
*q++=(unsigned char) (byte << (8-bit));
x++;
}
offset=(ssize_t) (image->columns+7)/8;
for (x=offset; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 4:
{
size_t
byte,
nibble;
ssize_t
offset;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
nibble=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=4;
byte|=((size_t) GetPixelIndex(image,p) & 0x0f);
nibble++;
if (nibble == 2)
{
*q++=(unsigned char) byte;
nibble=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (nibble != 0)
{
*q++=(unsigned char) (byte << 4);
x++;
}
offset=(ssize_t) (image->columns+1)/2;
for (x=offset; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 8:
{
/*
Convert PseudoClass packet to BMP pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert DirectClass packet to ARGB8888 pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
if ((type > 2) && (bmp_info.bits_per_pixel == 8))
if (image_info->compression != NoCompression)
{
MemoryInfo
*rle_info;
/*
Convert run-length encoded raster pixels.
*/
rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),
(image->rows+2)*sizeof(*pixels));
if (rle_info == (MemoryInfo *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);
bmp_info.file_size-=bmp_info.image_size;
bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,
pixels,bmp_data);
bmp_info.file_size+=bmp_info.image_size;
pixel_info=RelinquishVirtualMemory(pixel_info);
pixel_info=rle_info;
pixels=bmp_data;
bmp_info.compression=BI_RLE8;
}
/*
Write BMP for Windows, all versions, 14-byte header.
*/
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing BMP version %.20g datastream",(double) type);
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=DirectClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image depth=%.20g",(double) image->depth);
if (image->alpha_trait != UndefinedPixelTrait)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=MagickFalse");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel);
switch ((int) bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RGB");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_BITFIELDS");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=UNKNOWN (%lu)",bmp_info.compression);
break;
}
}
if (bmp_info.number_colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=unspecified");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=%lu",bmp_info.number_colors);
}
(void) WriteBlob(image,2,(unsigned char *) "BM");
(void) WriteBlobLSBLong(image,bmp_info.file_size);
(void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */
(void) WriteBlobLSBLong(image,bmp_info.offset_bits);
if (type == 2)
{
/*
Write 12-byte version 2 bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);
(void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
}
else
{
/*
Write 40-byte version 3+ bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width);
(void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
(void) WriteBlobLSBLong(image,bmp_info.compression);
(void) WriteBlobLSBLong(image,bmp_info.image_size);
(void) WriteBlobLSBLong(image,bmp_info.x_pixels);
(void) WriteBlobLSBLong(image,bmp_info.y_pixels);
(void) WriteBlobLSBLong(image,bmp_info.number_colors);
(void) WriteBlobLSBLong(image,bmp_info.colors_important);
}
if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) ||
(have_color_info != MagickFalse)))
{
/*
Write the rest of the 108-byte BMP Version 4 header.
*/
(void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */
(void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */
(void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */
(void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */
(void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.red_primary.x+
image->chromaticity.red_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.green_primary.x+
image->chromaticity.green_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.blue_primary.x+
image->chromaticity.blue_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.x*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.y*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.z*0x10000));
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
ssize_t
intent;
switch ((int) image->rendering_intent)
{
case SaturationIntent:
{
intent=LCS_GM_BUSINESS;
break;
}
case RelativeIntent:
{
intent=LCS_GM_GRAPHICS;
break;
}
case PerceptualIntent:
{
intent=LCS_GM_IMAGES;
break;
}
case AbsoluteIntent:
{
intent=LCS_GM_ABS_COLORIMETRIC;
break;
}
default:
{
intent=0;
break;
}
}
(void) WriteBlobLSBLong(image,(unsigned int) intent);
(void) WriteBlobLSBLong(image,0x00); /* dummy profile data */
(void) WriteBlobLSBLong(image,0x00); /* dummy profile length */
(void) WriteBlobLSBLong(image,0x00); /* reserved */
}
}
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
/*
Dump colormap to file.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Colormap: %.20g entries",(double) image->colors);
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<
bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
q=bmp_colormap;
for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
if (type > 2)
*q++=(unsigned char) 0x0;
}
for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)
{
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
if (type > 2)
*q++=(unsigned char) 0x00;
}
if (type <= 2)
(void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
else
(void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Pixels: %lu bytes",bmp_info.image_size);
(void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 168,824 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
QuicFecGroupNumber fec_group) {
header_.packet_sequence_number = number;
header_.flags = PACKET_FLAGS_NONE;
header_.fec_group = fec_group;
QuicFrames frames;
QuicFrame frame(&frame1_);
frames.push_back(frame);
QuicPacket* packet;
framer_.ConstructFragementDataPacket(header_, frames, &packet);
return packet;
}
Commit Message: Fix uninitialized access in QuicConnectionHelperTest
BUG=159928
Review URL: https://chromiumcodereview.appspot.com/11360153
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
QuicFecGroupNumber fec_group) {
header_.guid = guid_;
header_.packet_sequence_number = number;
header_.transmission_time = 0;
header_.retransmission_count = 0;
header_.flags = PACKET_FLAGS_NONE;
header_.fec_group = fec_group;
QuicFrames frames;
QuicFrame frame(&frame1_);
frames.push_back(frame);
QuicPacket* packet;
framer_.ConstructFragementDataPacket(header_, frames, &packet);
return packet;
}
| 171,410 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 HTMLFormControlElement::isAutofocusable() const
{
if (!fastHasAttribute(autofocusAttr))
return false;
if (hasTagName(inputTag))
return !toHTMLInputElement(this)->isInputTypeHidden();
if (hasTagName(selectTag))
return true;
if (hasTagName(keygenTag))
return true;
if (hasTagName(buttonTag))
return true;
if (hasTagName(textareaTag))
return true;
return false;
}
Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment.
This virtual function should return true if the form control can hanlde
'autofocucs' attribute if it is specified.
Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent
because interactiveness is required for autofocus capability.
BUG=none
TEST=none; no behavior changes.
Review URL: https://codereview.chromium.org/143343003
git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool HTMLFormControlElement::isAutofocusable() const
bool HTMLFormControlElement::supportsAutofocus() const
{
return false;
}
| 171,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end,
void *dbuf, void *ticket_buf)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, dbuf,
TEMP_TICKET_BUF_LEN);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
tp = ticket_buf;
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf,
TEMP_TICKET_BUF_LEN);
if (dlen < 0) {
ret = dlen;
goto out;
}
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
return ret;
bad:
ret = -EINVAL;
goto out;
}
Commit Message: libceph: do not hard code max auth ticket len
We hard code cephx auth ticket buffer size to 256 bytes. This isn't
enough for any moderate setups and, in case tickets themselves are not
encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but
ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the
buffer is allocated dynamically anyway, allocated it a bit later, at
the point where we know how much is going to be needed.
Fixes: http://tracker.ceph.com/issues/8979
Cc: [email protected]
Signed-off-by: Ilya Dryomov <[email protected]>
Reviewed-by: Sage Weil <[email protected]>
CWE ID: CWE-399 | static int process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dbuf = NULL;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *ticket_buf = NULL;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, &dbuf, 0);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0);
if (dlen < 0) {
ret = dlen;
goto out;
}
tp = ticket_buf;
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ticket_buf = kmalloc(dlen, GFP_NOFS);
if (!ticket_buf) {
ret = -ENOMEM;
goto out;
}
tp = ticket_buf;
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
kfree(ticket_buf);
kfree(dbuf);
return ret;
bad:
ret = -EINVAL;
goto out;
}
| 166,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IPV6DefragInOrderSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p1, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p3, NULL);
if (reassembled == NULL)
goto end;
if (IPV6_GET_PLEN(reassembled) != 19)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | IPV6DefragInOrderSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p1, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p3, NULL);
if (reassembled == NULL)
goto end;
if (IPV6_GET_PLEN(reassembled) != 19)
goto end;
/* 40 bytes in we should find 8 bytes of A. */
for (i = 40; i < 40 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A')
goto end;
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 48; i < 48 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B')
goto end;
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 56; i < 56 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
| 168,309 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 copy_creds(struct task_struct *p, unsigned long clone_flags)
{
#ifdef CONFIG_KEYS
struct thread_group_cred *tgcred;
#endif
struct cred *new;
int ret;
if (
#ifdef CONFIG_KEYS
!p->cred->thread_keyring &&
#endif
clone_flags & CLONE_THREAD
) {
p->real_cred = get_cred(p->cred);
get_cred(p->cred);
alter_cred_subscribers(p->cred, 2);
kdebug("share_creds(%p{%d,%d})",
p->cred, atomic_read(&p->cred->usage),
read_cred_subscribers(p->cred));
atomic_inc(&p->cred->user->processes);
return 0;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
goto error_put;
}
/* cache user_ns in cred. Doesn't need a refcount because it will
* stay pinned by cred->user
*/
new->user_ns = new->user->user_ns;
#ifdef CONFIG_KEYS
/* new threads get their own thread keyrings if their parent already
* had one */
if (new->thread_keyring) {
key_put(new->thread_keyring);
new->thread_keyring = NULL;
if (clone_flags & CLONE_THREAD)
install_thread_keyring_to_cred(new);
}
/* we share the process and session keyrings between all the threads in
* a process - this is slightly icky as we violate COW credentials a
* bit */
if (!(clone_flags & CLONE_THREAD)) {
tgcred = kmalloc(sizeof(*tgcred), GFP_KERNEL);
if (!tgcred) {
ret = -ENOMEM;
goto error_put;
}
atomic_set(&tgcred->usage, 1);
spin_lock_init(&tgcred->lock);
tgcred->process_keyring = NULL;
tgcred->session_keyring = key_get(new->tgcred->session_keyring);
release_tgcred(new);
new->tgcred = tgcred;
}
#endif
atomic_inc(&new->user->processes);
p->cred = p->real_cred = get_cred(new);
alter_cred_subscribers(new, 2);
validate_creds(new);
return 0;
error_put:
put_cred(new);
return ret;
}
Commit Message: cred: copy_process() should clear child->replacement_session_keyring
keyctl_session_to_parent(task) sets ->replacement_session_keyring,
it should be processed and cleared by key_replace_session_keyring().
However, this task can fork before it notices TIF_NOTIFY_RESUME and
the new child gets the bogus ->replacement_session_keyring copied by
dup_task_struct(). This is obviously wrong and, if nothing else, this
leads to put_cred(already_freed_cred).
change copy_creds() to clear this member. If copy_process() fails
before this point the wrong ->replacement_session_keyring doesn't
matter, exit_creds() won't be called.
Cc: <[email protected]>
Signed-off-by: Oleg Nesterov <[email protected]>
Acked-by: David Howells <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | int copy_creds(struct task_struct *p, unsigned long clone_flags)
{
#ifdef CONFIG_KEYS
struct thread_group_cred *tgcred;
#endif
struct cred *new;
int ret;
p->replacement_session_keyring = NULL;
if (
#ifdef CONFIG_KEYS
!p->cred->thread_keyring &&
#endif
clone_flags & CLONE_THREAD
) {
p->real_cred = get_cred(p->cred);
get_cred(p->cred);
alter_cred_subscribers(p->cred, 2);
kdebug("share_creds(%p{%d,%d})",
p->cred, atomic_read(&p->cred->usage),
read_cred_subscribers(p->cred));
atomic_inc(&p->cred->user->processes);
return 0;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
goto error_put;
}
/* cache user_ns in cred. Doesn't need a refcount because it will
* stay pinned by cred->user
*/
new->user_ns = new->user->user_ns;
#ifdef CONFIG_KEYS
/* new threads get their own thread keyrings if their parent already
* had one */
if (new->thread_keyring) {
key_put(new->thread_keyring);
new->thread_keyring = NULL;
if (clone_flags & CLONE_THREAD)
install_thread_keyring_to_cred(new);
}
/* we share the process and session keyrings between all the threads in
* a process - this is slightly icky as we violate COW credentials a
* bit */
if (!(clone_flags & CLONE_THREAD)) {
tgcred = kmalloc(sizeof(*tgcred), GFP_KERNEL);
if (!tgcred) {
ret = -ENOMEM;
goto error_put;
}
atomic_set(&tgcred->usage, 1);
spin_lock_init(&tgcred->lock);
tgcred->process_keyring = NULL;
tgcred->session_keyring = key_get(new->tgcred->session_keyring);
release_tgcred(new);
new->tgcred = tgcred;
}
#endif
atomic_inc(&new->user->processes);
p->cred = p->real_cred = get_cred(new);
alter_cred_subscribers(new, 2);
validate_creds(new);
return 0;
error_put:
put_cred(new);
return ret;
}
| 165,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
if (url.SchemeIsBlob()) {
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285 | GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
// that might allow two URLs created by different sites to share a process.
// See https://crbug.com/863623 and https://crbug.com/863069.
// schemes, such as file:.
// TODO(creis): This currently causes problems with tests on Android and
// Android WebView. For now, skip it when Site Isolation is not enabled,
// since there's no need to isolate data and blob URLs from each other in
// that case.
bool is_site_isolation_enabled =
SiteIsolationPolicy::UseDedicatedProcessesForAllSites() ||
SiteIsolationPolicy::AreIsolatedOriginsEnabled();
if (is_site_isolation_enabled &&
(url.SchemeIsBlob() || url.scheme() == url::kDataScheme)) {
// origins from each other. We also get here for browser-initiated
// navigations to data URLs, which have a unique origin and should only
// share a process when they are identical. Remove hash from the URL in
// either case, since same-document navigations shouldn't use a different
// site URL.
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
| 173,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
spinlock_t *ptl;
struct vm_area_struct *vma = walk->vma;
pte_t *ptep;
unsigned char *vec = walk->private;
int nr = (end - addr) >> PAGE_SHIFT;
ptl = pmd_trans_huge_lock(pmd, vma);
if (ptl) {
memset(vec, 1, nr);
spin_unlock(ptl);
goto out;
}
if (pmd_trans_unstable(pmd)) {
__mincore_unmapped_range(addr, end, vma, vec);
goto out;
}
ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; ptep++, addr += PAGE_SIZE) {
pte_t pte = *ptep;
if (pte_none(pte))
__mincore_unmapped_range(addr, addr + PAGE_SIZE,
vma, vec);
else if (pte_present(pte))
*vec = 1;
else { /* pte is a swap entry */
swp_entry_t entry = pte_to_swp_entry(pte);
if (non_swap_entry(entry)) {
/*
* migration or hwpoison entries are always
* uptodate
*/
*vec = 1;
} else {
#ifdef CONFIG_SWAP
*vec = mincore_page(swap_address_space(entry),
swp_offset(entry));
#else
WARN_ON(1);
*vec = 1;
#endif
}
}
vec++;
}
pte_unmap_unlock(ptep - 1, ptl);
out:
walk->private += nr;
cond_resched();
return 0;
}
Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages
The semantics of what "in core" means for the mincore() system call are
somewhat unclear, but Linux has always (since 2.3.52, which is when
mincore() was initially done) treated it as "page is available in page
cache" rather than "page is mapped in the mapping".
The problem with that traditional semantic is that it exposes a lot of
system cache state that it really probably shouldn't, and that users
shouldn't really even care about.
So let's try to avoid that information leak by simply changing the
semantics to be that mincore() counts actual mapped pages, not pages
that might be cheaply mapped if they were faulted (note the "might be"
part of the old semantics: being in the cache doesn't actually guarantee
that you can access them without IO anyway, since things like network
filesystems may have to revalidate the cache before use).
In many ways the old semantics were somewhat insane even aside from the
information leak issue. From the very beginning (and that beginning is
a long time ago: 2.3.52 was released in March 2000, I think), the code
had a comment saying
Later we can get more picky about what "in core" means precisely.
and this is that "later". Admittedly it is much later than is really
comfortable.
NOTE! This is a real semantic change, and it is for example known to
change the output of "fincore", since that program literally does a
mmmap without populating it, and then doing "mincore()" on that mapping
that doesn't actually have any pages in it.
I'm hoping that nobody actually has any workflow that cares, and the
info leak is real.
We may have to do something different if it turns out that people have
valid reasons to want the old semantics, and if we can limit the
information leak sanely.
Cc: Kevin Easton <[email protected]>
Cc: Jiri Kosina <[email protected]>
Cc: Masatake YAMATO <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Greg KH <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michal Hocko <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
spinlock_t *ptl;
struct vm_area_struct *vma = walk->vma;
pte_t *ptep;
unsigned char *vec = walk->private;
int nr = (end - addr) >> PAGE_SHIFT;
ptl = pmd_trans_huge_lock(pmd, vma);
if (ptl) {
memset(vec, 1, nr);
spin_unlock(ptl);
goto out;
}
/* We'll consider a THP page under construction to be there */
if (pmd_trans_unstable(pmd)) {
memset(vec, 1, nr);
goto out;
}
ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; ptep++, addr += PAGE_SIZE) {
pte_t pte = *ptep;
if (pte_none(pte))
*vec = 0;
else if (pte_present(pte))
*vec = 1;
else { /* pte is a swap entry */
swp_entry_t entry = pte_to_swp_entry(pte);
/*
* migration or hwpoison entries are always
* uptodate
*/
*vec = !!non_swap_entry(entry);
}
vec++;
}
pte_unmap_unlock(ptep - 1, ptl);
out:
walk->private += nr;
cond_resched();
return 0;
}
| 169,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
register Quantum *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(image,depth,BImgBuff,i,exception);
}
(void) SyncImage(image,exception);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,exception) != MagickFalse))
{
if(GetCutColors(image,exception)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(image,q) == ScaleCharToQuantum(1))
{
SetPixelRed(image,QuantumRange,q);
SetPixelGreen(image,QuantumRange,q);
SetPixelBlue(image,QuantumRange,q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1599
CWE ID: CWE-20 | static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
register Quantum *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
(void) memset(BImgBuff,0,(size_t) ldblk*sizeof(*BImgBuff));
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(image,depth,BImgBuff,i,exception);
}
(void) SyncImage(image,exception);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,exception) != MagickFalse))
{
if(GetCutColors(image,exception)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(image,q) == ScaleCharToQuantum(1))
{
SetPixelRed(image,QuantumRange,q);
SetPixelGreen(image,QuantumRange,q);
SetPixelBlue(image,QuantumRange,q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 169,621 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned int subpel_avg_variance_ref(const uint8_t *ref,
const uint8_t *src,
const uint8_t *second_pred,
int l2w, int l2h,
int xoff, int yoff,
unsigned int *sse_ptr) {
int se = 0;
unsigned int sse = 0;
const int w = 1 << l2w, h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x];
se += diff;
sse += diff * diff;
}
}
*sse_ptr = sse;
return sse - (((int64_t) se * se) >> (l2w + l2h));
}
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 | unsigned int subpel_avg_variance_ref(const uint8_t *ref,
| 174,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-12999/IS-IS: Add a missing length check.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
| 167,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: void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params,
int nav_entry_id,
bool did_create_new_entry,
const GURL& url,
ui::PageTransition transition) {
params->nav_entry_id = nav_entry_id;
params->url = url;
params->referrer = Referrer();
params->transition = transition;
params->redirects = std::vector<GURL>();
params->should_update_history = false;
params->searchable_form_url = GURL();
params->searchable_form_encoding = std::string();
params->did_create_new_entry = did_create_new_entry;
params->gesture = NavigationGestureUser;
params->was_within_same_document = false;
params->method = "GET";
params->page_state = PageState::CreateFromURL(url);
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254 | void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params,
int nav_entry_id,
bool did_create_new_entry,
const GURL& url,
ui::PageTransition transition) {
params->nav_entry_id = nav_entry_id;
params->url = url;
params->origin = url::Origin(url);
params->referrer = Referrer();
params->transition = transition;
params->redirects = std::vector<GURL>();
params->should_update_history = false;
params->searchable_form_url = GURL();
params->searchable_form_encoding = std::string();
params->did_create_new_entry = did_create_new_entry;
params->gesture = NavigationGestureUser;
params->was_within_same_document = false;
params->method = "GET";
params->page_state = PageState::CreateFromURL(url);
}
| 171,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
struct user_element *ue = kcontrol->private_data;
change = memcmp(&ucontrol->value, ue->elem_data, ue->elem_data_size) != 0;
if (change)
memcpy(ue->elem_data, &ucontrol->value, ue->elem_data_size);
return change;
}
Commit Message: ALSA: control: Protect user controls against concurrent access
The user-control put and get handlers as well as the tlv do not protect against
concurrent access from multiple threads. Since the state of the control is not
updated atomically it is possible that either two write operations or a write
and a read operation race against each other. Both can lead to arbitrary memory
disclosure. This patch introduces a new lock that protects user-controls from
concurrent access. Since applications typically access controls sequentially
than in parallel a single lock per card should be fine.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362 | static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int change;
struct user_element *ue = kcontrol->private_data;
mutex_lock(&ue->card->user_ctl_lock);
change = memcmp(&ucontrol->value, ue->elem_data, ue->elem_data_size) != 0;
if (change)
memcpy(ue->elem_data, &ucontrol->value, ue->elem_data_size);
mutex_unlock(&ue->card->user_ctl_lock);
return change;
}
| 166,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 v9fs_read(void *opaque)
{
int32_t fid;
uint64_t off;
ssize_t err = 0;
int32_t count = 0;
size_t offset = 7;
uint32_t max_count;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_DIR) {
if (off == 0) {
v9fs_co_rewinddir(pdu, fidp);
}
count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
if (count < 0) {
err = count;
goto out;
}
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
} else if (fidp->fid_type == P9_FID_FILE) {
QEMUIOVector qiov_full;
QEMUIOVector qiov;
int32_t len;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
count += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out;
}
} while (count < max_count && len > 0);
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
qemu_iovec_destroy(&qiov);
qemu_iovec_destroy(&qiov_full);
} else if (fidp->fid_type == P9_FID_XATTR) {
} else {
err = -EINVAL;
}
trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399 | static void v9fs_read(void *opaque)
{
int32_t fid;
uint64_t off;
ssize_t err = 0;
int32_t count = 0;
size_t offset = 7;
uint32_t max_count;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_DIR) {
if (off == 0) {
v9fs_co_rewinddir(pdu, fidp);
}
count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
if (count < 0) {
err = count;
goto out;
}
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out;
}
err += offset + count;
} else if (fidp->fid_type == P9_FID_FILE) {
QEMUIOVector qiov_full;
QEMUIOVector qiov;
int32_t len;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
count += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out_free_iovec;
}
} while (count < max_count && len > 0);
err = pdu_marshal(pdu, offset, "d", count);
if (err < 0) {
goto out_free_iovec;
}
err += offset + count;
out_free_iovec:
qemu_iovec_destroy(&qiov);
qemu_iovec_destroy(&qiov_full);
} else if (fidp->fid_type == P9_FID_XATTR) {
} else {
err = -EINVAL;
}
trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
| 164,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, memory_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
Commit Message: fixed invalid memory reads detected by the address sanitizer
CWE ID: CWE-119 | void queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
size_t original_length = memory_length;
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, original_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
| 168,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
int bufsize)
{
/* If this function is being called, the buffer should not have been
initialized yet. */
assert(!stream->bufbase_);
if (bufmode != JAS_STREAM_UNBUF) {
/* The full- or line-buffered mode is being employed. */
if (!buf) {
/* The caller has not specified a buffer to employ, so allocate
one. */
if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
JAS_STREAM_MAXPUTBACK))) {
stream->bufmode_ |= JAS_STREAM_FREEBUF;
stream->bufsize_ = JAS_STREAM_BUFSIZE;
} else {
/* The buffer allocation has failed. Resort to unbuffered
operation. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
} else {
/* The caller has specified a buffer to employ. */
/* The buffer must be large enough to accommodate maximum
putback. */
assert(bufsize > JAS_STREAM_MAXPUTBACK);
stream->bufbase_ = JAS_CAST(uchar *, buf);
stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
}
} else {
/* The unbuffered mode is being employed. */
/* A buffer should not have been supplied by the caller. */
assert(!buf);
/* Use a trivial one-character buffer. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
stream->ptr_ = stream->bufstart_;
stream->cnt_ = 0;
stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
int bufsize)
{
/* If this function is being called, the buffer should not have been
initialized yet. */
assert(!stream->bufbase_);
if (bufmode != JAS_STREAM_UNBUF) {
/* The full- or line-buffered mode is being employed. */
if (!buf) {
/* The caller has not specified a buffer to employ, so allocate
one. */
if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
JAS_STREAM_MAXPUTBACK))) {
stream->bufmode_ |= JAS_STREAM_FREEBUF;
stream->bufsize_ = JAS_STREAM_BUFSIZE;
} else {
/* The buffer allocation has failed. Resort to unbuffered
operation. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
} else {
/* The caller has specified a buffer to employ. */
/* The buffer must be large enough to accommodate maximum
putback. */
assert(bufsize > JAS_STREAM_MAXPUTBACK);
stream->bufbase_ = JAS_CAST(jas_uchar *, buf);
stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
}
} else {
/* The unbuffered mode is being employed. */
/* A buffer should not have been supplied by the caller. */
assert(!buf);
/* Use a trivial one-character buffer. */
stream->bufbase_ = stream->tinybuf_;
stream->bufsize_ = 1;
}
stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
stream->ptr_ = stream->bufstart_;
stream->cnt_ = 0;
stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
}
| 168,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 DownloadCoreServiceImpl::SetDownloadManagerDelegateForTesting(
std::unique_ptr<ChromeDownloadManagerDelegate> new_delegate) {
manager_delegate_.swap(new_delegate);
DownloadManager* dm = BrowserContext::GetDownloadManager(profile_);
dm->SetDelegate(manager_delegate_.get());
manager_delegate_->SetDownloadManager(dm);
if (new_delegate)
new_delegate->Shutdown();
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125 | void DownloadCoreServiceImpl::SetDownloadManagerDelegateForTesting(
std::unique_ptr<ChromeDownloadManagerDelegate> new_delegate) {
manager_delegate_.swap(new_delegate);
DownloadManager* dm = BrowserContext::GetDownloadManager(profile_);
dm->SetDelegate(manager_delegate_.get());
if (manager_delegate_)
manager_delegate_->SetDownloadManager(dm);
download_manager_created_ = !!manager_delegate_;
if (new_delegate)
new_delegate->Shutdown();
}
| 173,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IHEVCD_ERROR_T ihevcd_parse_slice_data(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 end_of_slice_flag;
sps_t *ps_sps;
pps_t *ps_pps;
slice_header_t *ps_slice_hdr;
WORD32 end_of_pic;
tile_t *ps_tile, *ps_tile_prev;
WORD32 i;
WORD32 ctb_addr;
WORD32 tile_idx;
WORD32 cabac_init_idc;
WORD32 ctb_size;
WORD32 num_ctb_in_row;
WORD32 num_min4x4_in_ctb;
WORD32 slice_qp;
WORD32 slice_start_ctb_idx;
WORD32 tile_start_ctb_idx;
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base;
ps_pps = ps_codec->s_parse.ps_pps_base;
ps_sps = ps_codec->s_parse.ps_sps_base;
/* Get current slice header, pps and sps */
ps_slice_hdr += (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
ps_pps += ps_slice_hdr->i1_pps_id;
ps_sps += ps_pps->i1_sps_id;
if(0 != ps_codec->s_parse.i4_cur_slice_idx)
{
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_codec->s_parse.i4_cur_independent_slice_idx =
ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1);
}
}
ctb_size = 1 << ps_sps->i1_log2_ctb_size;
num_min4x4_in_ctb = (ctb_size / 4) * (ctb_size / 4);
num_ctb_in_row = ps_sps->i2_pic_wd_in_ctb;
/* Update the parse context */
if(0 == ps_codec->i4_slice_error)
{
ps_codec->s_parse.i4_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_codec->s_parse.i4_ctb_y = ps_slice_hdr->i2_ctb_y;
}
ps_codec->s_parse.ps_pps = ps_pps;
ps_codec->s_parse.ps_sps = ps_sps;
ps_codec->s_parse.ps_slice_hdr = ps_slice_hdr;
/* Derive Tile positions for the current CTB */
/* Change this to lookup if required */
ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x,
ps_codec->s_parse.i4_ctb_y,
&ps_codec->s_parse.i4_ctb_tile_x,
&ps_codec->s_parse.i4_ctb_tile_y,
&tile_idx);
ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx;
ps_codec->s_parse.i4_cur_tile_idx = tile_idx;
ps_tile = ps_codec->s_parse.ps_tile;
if(tile_idx)
ps_tile_prev = ps_tile - 1;
else
ps_tile_prev = ps_tile;
/* If the present slice is dependent, then store the previous
* independent slices' ctb x and y values for decoding process */
if(0 == ps_codec->i4_slice_error)
{
if(1 == ps_slice_hdr->i1_dependent_slice_flag)
{
/*If slice is present at the start of a new tile*/
if((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
ps_codec->s_parse.i4_ctb_slice_x = 0;
ps_codec->s_parse.i4_ctb_slice_y = 0;
}
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_codec->s_parse.i4_ctb_slice_x = 0;
ps_codec->s_parse.i4_ctb_slice_y = 0;
}
}
/* Frame level initializations */
if((0 == ps_codec->s_parse.i4_ctb_y) &&
(0 == ps_codec->s_parse.i4_ctb_x))
{
ret = ihevcd_parse_pic_init(ps_codec);
RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret);
ps_codec->s_parse.pu4_pic_tu_idx[0] = 0;
ps_codec->s_parse.pu4_pic_pu_idx[0] = 0;
ps_codec->s_parse.i4_cur_independent_slice_idx = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_tile_y = 0;
}
{
/* Updating the poc list of current slice to ps_mv_buf */
mv_buf_t *ps_mv_buf = ps_codec->s_parse.ps_cur_mv_buf;
if(ps_slice_hdr->i1_num_ref_idx_l1_active != 0)
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++)
{
ps_mv_buf->ai4_l1_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->i4_abs_poc;
ps_mv_buf->ai1_l1_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->u1_used_as_ref;
}
}
if(ps_slice_hdr->i1_num_ref_idx_l0_active != 0)
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++)
{
ps_mv_buf->ai4_l0_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->i4_abs_poc;
ps_mv_buf->ai1_l0_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->u1_used_as_ref;
}
}
}
/*Initialize the low delay flag at the beginning of every slice*/
if((0 == ps_codec->s_parse.i4_ctb_slice_x) || (0 == ps_codec->s_parse.i4_ctb_slice_y))
{
/* Lowdelay flag */
WORD32 cur_poc, ref_list_poc, flag = 1;
cur_poc = ps_slice_hdr->i4_abs_pic_order_cnt;
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++)
{
ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_mv_buf)->i4_abs_poc;
if(ref_list_poc > cur_poc)
{
flag = 0;
break;
}
}
if(flag && (ps_slice_hdr->i1_slice_type == BSLICE))
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++)
{
ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_mv_buf)->i4_abs_poc;
if(ref_list_poc > cur_poc)
{
flag = 0;
break;
}
}
}
ps_slice_hdr->i1_low_delay_flag = flag;
}
/* initialize the cabac init idc based on slice type */
if(ps_slice_hdr->i1_slice_type == ISLICE)
{
cabac_init_idc = 0;
}
else if(ps_slice_hdr->i1_slice_type == PSLICE)
{
cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 2 : 1;
}
else
{
cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 1 : 2;
}
slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp;
slice_qp = CLIP3(slice_qp, 0, 51);
/*Update QP value for every indepndent slice or for every dependent slice that begins at the start of a new tile*/
if((0 == ps_slice_hdr->i1_dependent_slice_flag) ||
((1 == ps_slice_hdr->i1_dependent_slice_flag) && ((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))))
{
ps_codec->s_parse.u4_qp = slice_qp;
}
/*Cabac init at the beginning of a slice*/
if((1 == ps_slice_hdr->i1_dependent_slice_flag) && (!((ps_codec->s_parse.i4_ctb_tile_x == 0) && (ps_codec->s_parse.i4_ctb_tile_y == 0))))
{
if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x)))
{
ihevcd_cabac_reset(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm);
}
}
else if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x)))
{
ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
}
do
{
{
WORD32 cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if(1 == ps_codec->i4_num_cores && 0 == cur_ctb_idx % RESET_TU_BUF_NCTB)
{
ps_codec->s_parse.ps_tu = ps_codec->s_parse.ps_pic_tu;
ps_codec->s_parse.i4_pic_tu_idx = 0;
}
}
end_of_pic = 0;
/* Section:7.3.7 Coding tree unit syntax */
/* coding_tree_unit() inlined here */
/* If number of cores is greater than 1, then add job to the queue */
/* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */
ps_codec->s_parse.i4_ctb_num_pcm_blks = 0;
/*At the beginning of each tile-which is not the beginning of a slice, cabac context must be initialized.
* Hence, check for the tile beginning here */
if(((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))
&& (!((ps_tile->u1_pos_x == 0) && (ps_tile->u1_pos_y == 0)))
&& (!((0 == ps_codec->s_parse.i4_ctb_slice_x) && (0 == ps_codec->s_parse.i4_ctb_slice_y))))
{
slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp;
slice_qp = CLIP3(slice_qp, 0, 51);
ps_codec->s_parse.u4_qp = slice_qp;
ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x,
ps_codec->s_parse.i4_ctb_y,
&ps_codec->s_parse.i4_ctb_tile_x,
&ps_codec->s_parse.i4_ctb_tile_y,
&tile_idx);
ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx;
ps_codec->s_parse.i4_cur_tile_idx = tile_idx;
ps_tile_prev = ps_tile - 1;
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
/*For slices that span across multiple tiles*/
if(slice_start_ctb_idx < tile_start_ctb_idx)
{ /* 2 Cases
* 1 - slice spans across frame-width- but does not start from 1st column
* 2 - Slice spans across multiple tiles anywhere is a frame
*/
ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y;
if(!(((ps_slice_hdr->i2_ctb_x + ps_tile_prev->u2_wd) % ps_sps->i2_pic_wd_in_ctb) == ps_tile->u1_pos_x)) //Case 2
{
if(ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y)
{
if(ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x)
{
ps_codec->s_parse.i4_ctb_slice_y -= 1;
}
}
}
/*ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y;
if (ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y)
{
if (ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x )
{
ps_codec->s_parse.i4_ctb_slice_y -= 1 ;
}
}*/
}
/* Cabac init is done unconditionally at the start of the tile irrespective
* of whether it is a dependent or an independent slice */
{
ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
}
}
/* If number of cores is greater than 1, then add job to the queue */
/* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */
if(0 == ps_codec->s_parse.i4_ctb_tile_x)
{
if(1 < ps_codec->i4_num_cores)
{
proc_job_t s_job;
IHEVCD_ERROR_T ret;
s_job.i4_cmd = CMD_PROCESS;
s_job.i2_ctb_cnt = (WORD16)ps_tile->u2_wd;
s_job.i2_ctb_x = (WORD16)ps_codec->s_parse.i4_ctb_x;
s_job.i2_ctb_y = (WORD16)ps_codec->s_parse.i4_ctb_y;
s_job.i2_slice_idx = (WORD16)ps_codec->s_parse.i4_cur_slice_idx;
s_job.i4_tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data -
(UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data;
ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
return ret;
}
else
{
process_ctxt_t *ps_proc = &ps_codec->as_process[0];
WORD32 tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data -
(UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data;
/* If the codec is running in single core mode,
* initialize zeroth process context
* TODO: Dual core mode might need a different implementation instead of jobq
*/
ps_proc->i4_ctb_cnt = ps_tile->u2_wd;
ps_proc->i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
ps_proc->i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
ps_proc->i4_cur_slice_idx = ps_codec->s_parse.i4_cur_slice_idx;
ihevcd_init_proc_ctxt(ps_proc, tu_coeff_data_ofst);
}
}
/* Restore cabac context model from top right CTB if entropy sync is enabled */
if(ps_pps->i1_entropy_coding_sync_enabled_flag)
{
/*TODO Handle single CTB and top-right belonging to a different slice */
if(0 == ps_codec->s_parse.i4_ctb_x)
{
WORD32 default_ctxt = 0;
if((0 == ps_codec->s_parse.i4_ctb_slice_y) && (!ps_slice_hdr->i1_dependent_slice_flag))
default_ctxt = 1;
if(1 == ps_sps->i2_pic_wd_in_ctb)
default_ctxt = 1;
ps_codec->s_parse.u4_qp = slice_qp;
if(default_ctxt)
{
ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
}
else
{
ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
(const UWORD8 *)&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync);
}
}
}
if(0 == ps_codec->i4_slice_error)
{
if(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag)
ihevcd_parse_sao(ps_codec);
}
else
{
sao_t *ps_sao = ps_codec->s_parse.ps_pic_sao +
ps_codec->s_parse.i4_ctb_x +
ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb;
/* Default values */
ps_sao->b3_y_type_idx = 0;
ps_sao->b3_cb_type_idx = 0;
ps_sao->b3_cr_type_idx = 0;
}
{
WORD32 ctb_indx;
ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y;
ps_codec->s_parse.s_bs_ctxt.pu1_pic_qp_const_in_ctb[ctb_indx >> 3] |= (1 << (ctb_indx & 7));
{
UWORD16 *pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx;
pu1_slice_idx[ctb_indx] = ps_codec->s_parse.i4_cur_independent_slice_idx;
}
}
if(0 == ps_codec->i4_slice_error)
{
ihevcd_parse_coding_quadtree(ps_codec,
(ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size),
(ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size),
ps_sps->i1_log2_ctb_size,
0);
}
else
{
tu_t *ps_tu = ps_codec->s_parse.ps_tu;
pu_t *ps_pu = ps_codec->s_parse.ps_pu;
ps_tu->b1_cb_cbf = 0;
ps_tu->b1_cr_cbf = 0;
ps_tu->b1_y_cbf = 0;
ps_tu->b4_pos_x = 0;
ps_tu->b4_pos_y = 0;
ps_tu->b1_transquant_bypass = 0;
ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2);
ps_tu->b7_qp = ps_codec->s_parse.u4_qp;
ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE;
ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE;
ps_tu->b1_first_tu_in_cu = 1;
ps_codec->s_parse.ps_tu++;
ps_codec->s_parse.s_cu.i4_tu_cnt++;
ps_codec->s_parse.i4_pic_tu_idx++;
ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP;
ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N;
ps_pu->b2_part_idx = 0;
ps_pu->b4_pos_x = 0;
ps_pu->b4_pos_y = 0;
ps_pu->b4_wd = (ctb_size >> 2) - 1;
ps_pu->b4_ht = (ctb_size >> 2) - 1;
ps_pu->b1_intra_flag = 0;
ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode;
ps_pu->b1_merge_flag = 1;
ps_pu->b3_merge_idx = 0;
ps_codec->s_parse.ps_pu++;
ps_codec->s_parse.i4_pic_pu_idx++;
}
if(0 == ps_codec->i4_slice_error)
end_of_slice_flag = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm);
else
end_of_slice_flag = 0;
AEV_TRACE("end_of_slice_flag", end_of_slice_flag, ps_codec->s_parse.s_cabac.u4_range);
/* In case of tiles or entropy sync, terminate cabac and copy cabac context backed up at the end of top-right CTB */
if(ps_pps->i1_tiles_enabled_flag || ps_pps->i1_entropy_coding_sync_enabled_flag)
{
WORD32 end_of_tile = 0;
WORD32 end_of_tile_row = 0;
/* Take a back up of cabac context models if entropy sync is enabled */
if(ps_pps->i1_entropy_coding_sync_enabled_flag || ps_pps->i1_tiles_enabled_flag)
{
if(1 == ps_codec->s_parse.i4_ctb_x)
{
WORD32 size = sizeof(ps_codec->s_parse.s_cabac.au1_ctxt_models);
memcpy(&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync, &ps_codec->s_parse.s_cabac.au1_ctxt_models, size);
}
}
/* Since tiles and entropy sync are not enabled simultaneously, the following will not result in any problems */
if((ps_codec->s_parse.i4_ctb_tile_x + 1) == (ps_tile->u2_wd))
{
end_of_tile_row = 1;
if((ps_codec->s_parse.i4_ctb_tile_y + 1) == ps_tile->u2_ht)
end_of_tile = 1;
}
if((0 == end_of_slice_flag) &&
((ps_pps->i1_tiles_enabled_flag && end_of_tile) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag && end_of_tile_row)))
{
WORD32 end_of_sub_stream_one_bit;
end_of_sub_stream_one_bit = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm);
AEV_TRACE("end_of_sub_stream_one_bit", end_of_sub_stream_one_bit, ps_codec->s_parse.s_cabac.u4_range);
/* TODO: Remove the check for offset when HM is updated to include a byte unconditionally even for aligned location */
/* For Ittiam streams this check should not be there, for HM9.1 streams this should be there */
if(ps_codec->s_parse.s_bitstrm.u4_bit_ofst % 8)
ihevcd_bits_flush_to_byte_boundary(&ps_codec->s_parse.s_bitstrm);
UNUSED(end_of_sub_stream_one_bit);
}
}
{
WORD32 ctb_indx;
ctb_addr = ps_codec->s_parse.i4_ctb_y * num_ctb_in_row + ps_codec->s_parse.i4_ctb_x;
ctb_indx = ++ctb_addr;
/* Store pu_idx for next CTB in frame level pu_idx array */
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = ctb_addr; //Next continuous ctb address
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.pu4_pic_pu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_pu_idx;
ps_codec->s_parse.i4_next_pu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu1_pu_map += num_min4x4_in_ctb;
/* Store tu_idx for next CTB in frame level tu_idx array */
if(1 == ps_codec->i4_num_cores)
{
ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ?
RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB;
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ?
RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB;
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx;
}
else
{
ctb_indx = ctb_addr;
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = ctb_addr;
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx;
}
ps_codec->s_parse.pu1_tu_map += num_min4x4_in_ctb;
}
/* QP array population has to be done if deblocking is enabled in the picture
* but some of the slices in the pic have it disabled */
if((0 != ps_codec->i4_disable_deblk_pic) &&
(1 == ps_slice_hdr->i1_slice_disable_deblocking_filter_flag))
{
bs_ctxt_t *ps_bs_ctxt = &ps_codec->s_parse.s_bs_ctxt;
WORD32 log2_ctb_size = ps_sps->i1_log2_ctb_size;
UWORD8 *pu1_qp;
WORD32 qp_strd;
WORD32 u4_qp_const_in_ctb;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 cur_tu_idx;
WORD32 i4_ctb_tu_cnt;
tu_t *ps_tu;
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y;
/* ctb_size/8 elements per CTB */
qp_strd = ps_sps->i2_pic_wd_in_ctb << (log2_ctb_size - 3);
pu1_qp = ps_bs_ctxt->pu1_pic_qp + ((ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * qp_strd) << (log2_ctb_size - 3));
u4_qp_const_in_ctb = ps_bs_ctxt->pu1_pic_qp_const_in_ctb[cur_ctb_idx >> 3] & (1 << (cur_ctb_idx & 7));
next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt;
if(1 == ps_codec->i4_num_cores)
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
}
else
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
}
ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx];
if(u4_qp_const_in_ctb)
{
pu1_qp[0] = ps_tu->b7_qp;
}
else
{
for(i = 0; i < i4_ctb_tu_cnt; i++, ps_tu++)
{
WORD32 start_pos_x;
WORD32 start_pos_y;
WORD32 tu_size;
/* start_pos_x and start_pos_y are in units of min TU size (4x4) */
start_pos_x = ps_tu->b4_pos_x;
start_pos_y = ps_tu->b4_pos_y;
tu_size = 1 << (ps_tu->b3_size + 2);
tu_size >>= 2; /* TU size divided by 4 */
if(0 == (start_pos_x & 1) && 0 == (start_pos_y & 1))
{
WORD32 row, col;
for(row = start_pos_y; row < start_pos_y + tu_size; row += 2)
{
for(col = start_pos_x; col < start_pos_x + tu_size; col += 2)
{
pu1_qp[(row >> 1) * qp_strd + (col >> 1)] = ps_tu->b7_qp;
}
}
}
}
}
}
if(ps_codec->i4_num_cores <= MV_PRED_NUM_CORES_THRESHOLD)
{
/*************************************************/
/**************** MV pred **********************/
/*************************************************/
WORD8 u1_top_ctb_avail = 1;
WORD8 u1_left_ctb_avail = 1;
WORD8 u1_top_lt_ctb_avail = 1;
WORD8 u1_top_rt_ctb_avail = 1;
WORD16 i2_wd_in_ctb;
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if((slice_start_ctb_idx < tile_start_ctb_idx))
{
i2_wd_in_ctb = ps_sps->i2_pic_wd_in_ctb;
}
else
{
i2_wd_in_ctb = ps_tile->u2_wd;
}
/* slice and tile boundaries */
if((0 == ps_codec->s_parse.i4_ctb_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
u1_top_rt_ctb_avail = 0;
}
if((0 == ps_codec->s_parse.i4_ctb_x) || (0 == ps_codec->s_parse.i4_ctb_tile_x))
{
u1_left_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) //TODO: For tile, not implemented
{
u1_top_rt_ctb_avail = 0;
}
}
}
/*For slices not beginning at start of a ctb row*/
else if(ps_codec->s_parse.i4_ctb_x > 0)
{
if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
if(0 == ps_codec->s_parse.i4_ctb_slice_x)
{
u1_left_ctb_avail = 0;
}
if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x)
{
u1_top_rt_ctb_avail = 0;
}
}
else if((1 == ps_codec->s_parse.i4_ctb_slice_y) && (0 == ps_codec->s_parse.i4_ctb_slice_x))
{
u1_top_lt_ctb_avail = 0;
}
}
if(((ps_sps->i2_pic_wd_in_ctb - 1) == ps_codec->s_parse.i4_ctb_x) || ((ps_tile->u2_wd - 1) == ps_codec->s_parse.i4_ctb_tile_x))
{
u1_top_rt_ctb_avail = 0;
}
if(PSLICE == ps_slice_hdr->i1_slice_type
|| BSLICE == ps_slice_hdr->i1_slice_type)
{
mv_ctxt_t s_mv_ctxt;
process_ctxt_t *ps_proc;
UWORD32 *pu4_ctb_top_pu_idx;
UWORD32 *pu4_ctb_left_pu_idx;
UWORD32 *pu4_ctb_top_left_pu_idx;
WORD32 i4_ctb_pu_cnt;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 cur_pu_idx;
ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt;
i4_ctb_pu_cnt = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx]
- ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
pu4_ctb_top_pu_idx = ps_proc->pu4_pic_pu_idx_top
+ (ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE);
pu4_ctb_left_pu_idx = ps_proc->pu4_pic_pu_idx_left;
pu4_ctb_top_left_pu_idx = &ps_proc->u4_ctb_top_left_pu_idx;
/* Initializing s_mv_ctxt */
{
s_mv_ctxt.ps_pps = ps_pps;
s_mv_ctxt.ps_sps = ps_sps;
s_mv_ctxt.ps_slice_hdr = ps_slice_hdr;
s_mv_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
s_mv_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
s_mv_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx];
s_mv_ctxt.ps_pic_pu = ps_codec->s_parse.ps_pic_pu;
s_mv_ctxt.ps_tile = ps_tile;
s_mv_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map;
s_mv_ctxt.pu4_pic_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx;
s_mv_ctxt.pu1_pic_pu_map = ps_codec->s_parse.pu1_pic_pu_map;
s_mv_ctxt.i4_ctb_pu_cnt = i4_ctb_pu_cnt;
s_mv_ctxt.i4_ctb_start_pu_idx = cur_pu_idx;
s_mv_ctxt.u1_top_ctb_avail = u1_top_ctb_avail;
s_mv_ctxt.u1_top_rt_ctb_avail = u1_top_rt_ctb_avail;
s_mv_ctxt.u1_top_lt_ctb_avail = u1_top_lt_ctb_avail;
s_mv_ctxt.u1_left_ctb_avail = u1_left_ctb_avail;
}
ihevcd_get_mv_ctb(&s_mv_ctxt, pu4_ctb_top_pu_idx,
pu4_ctb_left_pu_idx, pu4_ctb_top_left_pu_idx);
}
else
{
WORD32 num_minpu_in_ctb = (ctb_size / MIN_PU_SIZE) * (ctb_size / MIN_PU_SIZE);
UWORD8 *pu1_pic_pu_map_ctb = ps_codec->s_parse.pu1_pic_pu_map +
(ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb) * num_minpu_in_ctb;
process_ctxt_t *ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
WORD32 row, col;
WORD32 pu_cnt;
WORD32 num_pu_per_ctb;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 ctb_start_pu_idx;
UWORD32 *pu4_nbr_pu_idx = ps_proc->pu4_pic_pu_idx_map;
WORD32 nbr_pu_idx_strd = MAX_CTB_SIZE / MIN_PU_SIZE + 2;
pu_t *ps_pu;
for(row = 0; row < ctb_size / MIN_PU_SIZE; row++)
{
for(col = 0; col < ctb_size / MIN_PU_SIZE; col++)
{
pu1_pic_pu_map_ctb[row * ctb_size / MIN_PU_SIZE + col] = 0;
}
}
/* Neighbor PU idx update inside CTB */
/* 1byte per 4x4. Indicates the PU idx that 4x4 block belongs to */
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt;
num_pu_per_ctb = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx]
- ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
ctb_start_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
ps_pu = &ps_codec->s_parse.ps_pic_pu[ctb_start_pu_idx];
for(pu_cnt = 0; pu_cnt < num_pu_per_ctb; pu_cnt++, ps_pu++)
{
UWORD32 cur_pu_idx;
WORD32 pu_ht = (ps_pu->b4_ht + 1) << 2;
WORD32 pu_wd = (ps_pu->b4_wd + 1) << 2;
cur_pu_idx = ctb_start_pu_idx + pu_cnt;
for(row = 0; row < pu_ht / MIN_PU_SIZE; row++)
for(col = 0; col < pu_wd / MIN_PU_SIZE; col++)
pu4_nbr_pu_idx[(1 + ps_pu->b4_pos_x + col)
+ (1 + ps_pu->b4_pos_y + row)
* nbr_pu_idx_strd] =
cur_pu_idx;
}
/* Updating Top and Left pointers */
{
WORD32 rows_remaining = ps_sps->i2_pic_height_in_luma_samples
- (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size);
WORD32 ctb_size_left = MIN(ctb_size, rows_remaining);
/* Top Left */
/* saving top left before updating top ptr, as updating top ptr will overwrite the top left for the next ctb */
ps_proc->u4_ctb_top_left_pu_idx = ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + ctb_size / MIN_PU_SIZE - 1];
for(i = 0; i < ctb_size / MIN_PU_SIZE; i++)
{
/* Left */
/* Last column of au4_nbr_pu_idx */
ps_proc->pu4_pic_pu_idx_left[i] = pu4_nbr_pu_idx[(ctb_size / MIN_PU_SIZE)
+ (i + 1) * nbr_pu_idx_strd];
/* Top */
/* Last row of au4_nbr_pu_idx */
ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + i] =
pu4_nbr_pu_idx[(ctb_size_left / MIN_PU_SIZE) * nbr_pu_idx_strd + i + 1];
}
}
}
/*************************************************/
/****************** BS, QP *********************/
/*************************************************/
/* Check if deblock is disabled for the current slice or if it is disabled for the current picture
* because of disable deblock api
*/
if(0 == ps_codec->i4_disable_deblk_pic)
{
/* Boundary strength calculation is done irrespective of whether deblocking is disabled
* in the slice or not, to handle deblocking slice boundaries */
if((0 == ps_codec->i4_slice_error))
{
WORD32 i4_ctb_tu_cnt;
WORD32 cur_ctb_idx, next_ctb_idx;
WORD32 cur_pu_idx;
WORD32 cur_tu_idx;
process_ctxt_t *ps_proc;
ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt;
if(1 == ps_codec->i4_num_cores)
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
}
else
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
}
ps_codec->s_parse.s_bs_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_bs_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_bs_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tu_cnt = i4_ctb_tu_cnt;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_x = ps_codec->s_parse.i4_ctb_tile_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_y = ps_codec->s_parse.i4_ctb_tile_y;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_x = ps_codec->s_parse.i4_ctb_slice_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_y = ps_codec->s_parse.i4_ctb_slice_y;
ps_codec->s_parse.s_bs_ctxt.ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx];
ps_codec->s_parse.s_bs_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx];
ps_codec->s_parse.s_bs_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map;
ps_codec->s_parse.s_bs_ctxt.i4_next_pu_ctb_cnt = ps_codec->s_parse.i4_next_pu_ctb_cnt;
ps_codec->s_parse.s_bs_ctxt.i4_next_tu_ctb_cnt = ps_codec->s_parse.i4_next_tu_ctb_cnt;
ps_codec->s_parse.s_bs_ctxt.pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx;
ps_codec->s_parse.s_bs_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ps_codec->s_parse.s_bs_ctxt.ps_tile = ps_codec->s_parse.ps_tile;
if(ISLICE == ps_slice_hdr->i1_slice_type)
{
ihevcd_ctb_boundary_strength_islice(&ps_codec->s_parse.s_bs_ctxt);
}
else
{
ihevcd_ctb_boundary_strength_pbslice(&ps_codec->s_parse.s_bs_ctxt);
}
}
/* Boundary strength is set to zero if deblocking is disabled for the current slice */
if(0 != ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
WORD32 bs_strd = (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16);
UWORD32 *pu4_vert_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_vert_bs +
ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) +
ps_codec->s_parse.i4_ctb_y * bs_strd);
UWORD32 *pu4_horz_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_horz_bs +
ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) +
ps_codec->s_parse.i4_ctb_y * bs_strd);
memset(pu4_vert_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2);
memset(pu4_horz_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2);
}
}
}
DATA_SYNC();
/* Update the parse status map */
{
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
UWORD8 *pu1_buf;
WORD32 idx;
idx = (ps_codec->s_parse.i4_ctb_x);
idx += ((ps_codec->s_parse.i4_ctb_y) * ps_sps->i2_pic_wd_in_ctb);
pu1_buf = (ps_codec->pu1_parse_map + idx);
*pu1_buf = 1;
}
/* Increment CTB x and y positions */
ps_codec->s_parse.i4_ctb_tile_x++;
ps_codec->s_parse.i4_ctb_x++;
ps_codec->s_parse.i4_ctb_slice_x++;
/*If tiles are enabled, handle the slice counters differently*/
if(ps_pps->i1_tiles_enabled_flag)
{
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if((slice_start_ctb_idx < tile_start_ctb_idx))
{
if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u1_pos_x + ps_tile->u2_wd))
{
/* Reached end of slice row within a tile /frame */
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; //todo:Check
}
}
else if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u2_wd))
{
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = 0;
}
}
else
{
if(ps_codec->s_parse.i4_ctb_slice_x == ps_tile->u2_wd)
{
/* Reached end of slice row within a tile /frame */
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = 0;
}
}
if(ps_codec->s_parse.i4_ctb_tile_x == (ps_tile->u2_wd))
{
/* Reached end of tile row */
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_tile_y++;
ps_codec->s_parse.i4_ctb_y++;
if(ps_codec->s_parse.i4_ctb_tile_y == (ps_tile->u2_ht))
{
/* Reached End of Tile */
ps_codec->s_parse.i4_ctb_tile_y = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.ps_tile++;
if((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb) && (ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb))
{
/* Reached end of frame */
end_of_pic = 1;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = ps_sps->i2_pic_ht_in_ctb;
}
else
{
/* Initialize ctb_x and ctb_y to start of next tile */
ps_tile = ps_codec->s_parse.ps_tile;
ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_y = ps_tile->u1_pos_y;
ps_codec->s_parse.i4_ctb_tile_y = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y;
}
}
}
ps_codec->s_parse.i4_next_ctb_indx = ps_codec->s_parse.i4_ctb_x +
ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb;
/* If the current slice is in error, check if the next slice's address
* is reached and mark the end_of_slice flag */
if(ps_codec->i4_slice_error)
{
slice_header_t *ps_slice_hdr_next = ps_slice_hdr + 1;
WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x +
ps_slice_hdr_next->i2_ctb_y * ps_sps->i2_pic_wd_in_ctb;
if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr)
end_of_slice_flag = 1;
}
/* If the codec is running in single core mode
* then call process function for current CTB
*/
if((1 == ps_codec->i4_num_cores) && (ps_codec->s_parse.i4_ctb_tile_x == 0))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[0];
ps_proc->i4_ctb_cnt = ps_proc->ps_tile->u2_wd;
ihevcd_process(ps_proc);
}
/* If the bytes for the current slice are exhausted
* set end_of_slice flag to 1
* This slice will be treated as incomplete */
if((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu1_buf_max + BITSTRM_OFF_THRS <
((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu4_buf + (ps_codec->s_parse.s_bitstrm.u4_bit_ofst / 8)))
{
if(0 == ps_codec->i4_slice_error)
end_of_slice_flag = 1;
}
if(end_of_pic)
break;
} while(!end_of_slice_flag);
/* Increment the slice index for parsing next slice */
if(0 == end_of_pic)
{
while(1)
{
WORD32 parse_slice_idx;
parse_slice_idx = ps_codec->s_parse.i4_cur_slice_idx;
parse_slice_idx++;
{
/* If the next slice header is not initialized, update cur_slice_idx and break */
if((1 == ps_codec->i4_num_cores) || (0 != (parse_slice_idx & (MAX_SLICE_HDR_CNT - 1))))
{
ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx;
break;
}
/* If the next slice header is initialised, wait for the parsed slices to be processed */
else
{
WORD32 ctb_indx = 0;
while(ctb_indx != ps_sps->i4_pic_size_in_ctb)
{
WORD32 parse_status = *(ps_codec->pu1_parse_map + ctb_indx);
volatile WORD32 proc_status = *(ps_codec->pu1_proc_map + ctb_indx) & 1;
if(parse_status == proc_status)
ctb_indx++;
}
ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx;
break;
}
}
}
}
else
{
#if FRAME_ILF_PAD
if(FRAME_ILF_PAD && 1 == ps_codec->i4_num_cores)
{
if(ps_slice_hdr->i4_abs_pic_order_cnt == 0)
{
DUMP_PRE_ILF(ps_codec->as_process[0].pu1_cur_pic_luma,
ps_codec->as_process[0].pu1_cur_pic_chroma,
ps_sps->i2_pic_width_in_luma_samples,
ps_sps->i2_pic_height_in_luma_samples,
ps_codec->i4_strd);
DUMP_BS(ps_codec->as_process[0].s_bs_ctxt.pu4_pic_vert_bs,
ps_codec->as_process[0].s_bs_ctxt.pu4_pic_horz_bs,
ps_sps->i2_pic_wd_in_ctb * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb,
(ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb);
DUMP_QP(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp,
(ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CU_SIZE * MIN_CU_SIZE));
DUMP_QP_CONST_IN_CTB(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp_const_in_ctb,
(ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CTB_SIZE * MIN_CTB_SIZE) / 8);
DUMP_NO_LOOP_FILTER(ps_codec->as_process[0].pu1_pic_no_loop_filter_flag,
(ps_sps->i2_pic_width_in_luma_samples / MIN_CU_SIZE) * (ps_sps->i2_pic_height_in_luma_samples / MIN_CU_SIZE) / 8);
DUMP_OFFSETS(ps_slice_hdr->i1_beta_offset_div2,
ps_slice_hdr->i1_tc_offset_div2,
ps_pps->i1_pic_cb_qp_offset,
ps_pps->i1_pic_cr_qp_offset);
}
ps_codec->s_parse.s_deblk_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_deblk_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_deblk_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_deblk_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ps_codec->s_parse.s_deblk_ctxt.is_chroma_yuv420sp_vu = (ps_codec->e_ref_chroma_fmt == IV_YUV_420SP_VU);
ps_codec->s_parse.s_sao_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_sao_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_sao_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_sao_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ihevcd_ilf_pad_frame(&ps_codec->s_parse.s_deblk_ctxt, &ps_codec->s_parse.s_sao_ctxt);
}
#endif
ps_codec->s_parse.i4_end_of_frame = 1;
}
return ret;
}
Commit Message: Return error from cabac init if offset is greater than range
When the offset was greater than range, the bitstream was read
more than the valid range in leaf-level cabac parsing modules.
Error check was added to cabac init to fix this issue. Additionally
end of slice and slice error were signalled to suppress further
parsing of current slice.
Bug: 34897036
Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2
(cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a)
(cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba)
CWE ID: CWE-119 | IHEVCD_ERROR_T ihevcd_parse_slice_data(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 end_of_slice_flag;
sps_t *ps_sps;
pps_t *ps_pps;
slice_header_t *ps_slice_hdr;
WORD32 end_of_pic;
tile_t *ps_tile, *ps_tile_prev;
WORD32 i;
WORD32 ctb_addr;
WORD32 tile_idx;
WORD32 cabac_init_idc;
WORD32 ctb_size;
WORD32 num_ctb_in_row;
WORD32 num_min4x4_in_ctb;
WORD32 slice_qp;
WORD32 slice_start_ctb_idx;
WORD32 tile_start_ctb_idx;
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base;
ps_pps = ps_codec->s_parse.ps_pps_base;
ps_sps = ps_codec->s_parse.ps_sps_base;
/* Get current slice header, pps and sps */
ps_slice_hdr += (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
ps_pps += ps_slice_hdr->i1_pps_id;
ps_sps += ps_pps->i1_sps_id;
if(0 != ps_codec->s_parse.i4_cur_slice_idx)
{
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_codec->s_parse.i4_cur_independent_slice_idx =
ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1);
}
}
ctb_size = 1 << ps_sps->i1_log2_ctb_size;
num_min4x4_in_ctb = (ctb_size / 4) * (ctb_size / 4);
num_ctb_in_row = ps_sps->i2_pic_wd_in_ctb;
/* Update the parse context */
if(0 == ps_codec->i4_slice_error)
{
ps_codec->s_parse.i4_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_codec->s_parse.i4_ctb_y = ps_slice_hdr->i2_ctb_y;
}
ps_codec->s_parse.ps_pps = ps_pps;
ps_codec->s_parse.ps_sps = ps_sps;
ps_codec->s_parse.ps_slice_hdr = ps_slice_hdr;
/* Derive Tile positions for the current CTB */
/* Change this to lookup if required */
ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x,
ps_codec->s_parse.i4_ctb_y,
&ps_codec->s_parse.i4_ctb_tile_x,
&ps_codec->s_parse.i4_ctb_tile_y,
&tile_idx);
ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx;
ps_codec->s_parse.i4_cur_tile_idx = tile_idx;
ps_tile = ps_codec->s_parse.ps_tile;
if(tile_idx)
ps_tile_prev = ps_tile - 1;
else
ps_tile_prev = ps_tile;
/* If the present slice is dependent, then store the previous
* independent slices' ctb x and y values for decoding process */
if(0 == ps_codec->i4_slice_error)
{
if(1 == ps_slice_hdr->i1_dependent_slice_flag)
{
/*If slice is present at the start of a new tile*/
if((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
ps_codec->s_parse.i4_ctb_slice_x = 0;
ps_codec->s_parse.i4_ctb_slice_y = 0;
}
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_codec->s_parse.i4_ctb_slice_x = 0;
ps_codec->s_parse.i4_ctb_slice_y = 0;
}
}
/* Frame level initializations */
if((0 == ps_codec->s_parse.i4_ctb_y) &&
(0 == ps_codec->s_parse.i4_ctb_x))
{
ret = ihevcd_parse_pic_init(ps_codec);
RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret);
ps_codec->s_parse.pu4_pic_tu_idx[0] = 0;
ps_codec->s_parse.pu4_pic_pu_idx[0] = 0;
ps_codec->s_parse.i4_cur_independent_slice_idx = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_tile_y = 0;
}
{
/* Updating the poc list of current slice to ps_mv_buf */
mv_buf_t *ps_mv_buf = ps_codec->s_parse.ps_cur_mv_buf;
if(ps_slice_hdr->i1_num_ref_idx_l1_active != 0)
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++)
{
ps_mv_buf->ai4_l1_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->i4_abs_poc;
ps_mv_buf->ai1_l1_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->u1_used_as_ref;
}
}
if(ps_slice_hdr->i1_num_ref_idx_l0_active != 0)
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++)
{
ps_mv_buf->ai4_l0_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->i4_abs_poc;
ps_mv_buf->ai1_l0_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->u1_used_as_ref;
}
}
}
/*Initialize the low delay flag at the beginning of every slice*/
if((0 == ps_codec->s_parse.i4_ctb_slice_x) || (0 == ps_codec->s_parse.i4_ctb_slice_y))
{
/* Lowdelay flag */
WORD32 cur_poc, ref_list_poc, flag = 1;
cur_poc = ps_slice_hdr->i4_abs_pic_order_cnt;
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++)
{
ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_mv_buf)->i4_abs_poc;
if(ref_list_poc > cur_poc)
{
flag = 0;
break;
}
}
if(flag && (ps_slice_hdr->i1_slice_type == BSLICE))
{
for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++)
{
ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_mv_buf)->i4_abs_poc;
if(ref_list_poc > cur_poc)
{
flag = 0;
break;
}
}
}
ps_slice_hdr->i1_low_delay_flag = flag;
}
/* initialize the cabac init idc based on slice type */
if(ps_slice_hdr->i1_slice_type == ISLICE)
{
cabac_init_idc = 0;
}
else if(ps_slice_hdr->i1_slice_type == PSLICE)
{
cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 2 : 1;
}
else
{
cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 1 : 2;
}
slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp;
slice_qp = CLIP3(slice_qp, 0, 51);
/*Update QP value for every indepndent slice or for every dependent slice that begins at the start of a new tile*/
if((0 == ps_slice_hdr->i1_dependent_slice_flag) ||
((1 == ps_slice_hdr->i1_dependent_slice_flag) && ((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))))
{
ps_codec->s_parse.u4_qp = slice_qp;
}
/*Cabac init at the beginning of a slice*/
if((1 == ps_slice_hdr->i1_dependent_slice_flag) && (!((ps_codec->s_parse.i4_ctb_tile_x == 0) && (ps_codec->s_parse.i4_ctb_tile_y == 0))))
{
if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x)))
{
ihevcd_cabac_reset(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm);
}
}
else if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x)))
{
ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
{
ps_codec->i4_slice_error = 1;
end_of_slice_flag = 1;
ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
}
do
{
{
WORD32 cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if(1 == ps_codec->i4_num_cores && 0 == cur_ctb_idx % RESET_TU_BUF_NCTB)
{
ps_codec->s_parse.ps_tu = ps_codec->s_parse.ps_pic_tu;
ps_codec->s_parse.i4_pic_tu_idx = 0;
}
}
end_of_pic = 0;
/* Section:7.3.7 Coding tree unit syntax */
/* coding_tree_unit() inlined here */
/* If number of cores is greater than 1, then add job to the queue */
/* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */
ps_codec->s_parse.i4_ctb_num_pcm_blks = 0;
/*At the beginning of each tile-which is not the beginning of a slice, cabac context must be initialized.
* Hence, check for the tile beginning here */
if(((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y))
&& (!((ps_tile->u1_pos_x == 0) && (ps_tile->u1_pos_y == 0)))
&& (!((0 == ps_codec->s_parse.i4_ctb_slice_x) && (0 == ps_codec->s_parse.i4_ctb_slice_y))))
{
slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp;
slice_qp = CLIP3(slice_qp, 0, 51);
ps_codec->s_parse.u4_qp = slice_qp;
ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x,
ps_codec->s_parse.i4_ctb_y,
&ps_codec->s_parse.i4_ctb_tile_x,
&ps_codec->s_parse.i4_ctb_tile_y,
&tile_idx);
ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx;
ps_codec->s_parse.i4_cur_tile_idx = tile_idx;
ps_tile_prev = ps_tile - 1;
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
/*For slices that span across multiple tiles*/
if(slice_start_ctb_idx < tile_start_ctb_idx)
{ /* 2 Cases
* 1 - slice spans across frame-width- but does not start from 1st column
* 2 - Slice spans across multiple tiles anywhere is a frame
*/
ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y;
if(!(((ps_slice_hdr->i2_ctb_x + ps_tile_prev->u2_wd) % ps_sps->i2_pic_wd_in_ctb) == ps_tile->u1_pos_x)) //Case 2
{
if(ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y)
{
if(ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x)
{
ps_codec->s_parse.i4_ctb_slice_y -= 1;
}
}
}
/*ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y;
if (ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y)
{
if (ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x )
{
ps_codec->s_parse.i4_ctb_slice_y -= 1 ;
}
}*/
}
/* Cabac init is done unconditionally at the start of the tile irrespective
* of whether it is a dependent or an independent slice */
{
ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
{
ps_codec->i4_slice_error = 1;
end_of_slice_flag = 1;
ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
}
}
/* If number of cores is greater than 1, then add job to the queue */
/* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */
if(0 == ps_codec->s_parse.i4_ctb_tile_x)
{
if(1 < ps_codec->i4_num_cores)
{
proc_job_t s_job;
IHEVCD_ERROR_T ret;
s_job.i4_cmd = CMD_PROCESS;
s_job.i2_ctb_cnt = (WORD16)ps_tile->u2_wd;
s_job.i2_ctb_x = (WORD16)ps_codec->s_parse.i4_ctb_x;
s_job.i2_ctb_y = (WORD16)ps_codec->s_parse.i4_ctb_y;
s_job.i2_slice_idx = (WORD16)ps_codec->s_parse.i4_cur_slice_idx;
s_job.i4_tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data -
(UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data;
ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
return ret;
}
else
{
process_ctxt_t *ps_proc = &ps_codec->as_process[0];
WORD32 tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data -
(UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data;
/* If the codec is running in single core mode,
* initialize zeroth process context
* TODO: Dual core mode might need a different implementation instead of jobq
*/
ps_proc->i4_ctb_cnt = ps_tile->u2_wd;
ps_proc->i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
ps_proc->i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
ps_proc->i4_cur_slice_idx = ps_codec->s_parse.i4_cur_slice_idx;
ihevcd_init_proc_ctxt(ps_proc, tu_coeff_data_ofst);
}
}
/* Restore cabac context model from top right CTB if entropy sync is enabled */
if(ps_pps->i1_entropy_coding_sync_enabled_flag)
{
/*TODO Handle single CTB and top-right belonging to a different slice */
if(0 == ps_codec->s_parse.i4_ctb_x)
{
WORD32 default_ctxt = 0;
if((0 == ps_codec->s_parse.i4_ctb_slice_y) && (!ps_slice_hdr->i1_dependent_slice_flag))
default_ctxt = 1;
if(1 == ps_sps->i2_pic_wd_in_ctb)
default_ctxt = 1;
ps_codec->s_parse.u4_qp = slice_qp;
if(default_ctxt)
{
ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
&gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
{
ps_codec->i4_slice_error = 1;
end_of_slice_flag = 1;
ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
}
else
{
ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm,
slice_qp,
cabac_init_idc,
(const UWORD8 *)&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync);
if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS)
{
ps_codec->i4_slice_error = 1;
end_of_slice_flag = 1;
ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
}
}
}
if(0 == ps_codec->i4_slice_error)
{
if(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag)
ihevcd_parse_sao(ps_codec);
}
else
{
sao_t *ps_sao = ps_codec->s_parse.ps_pic_sao +
ps_codec->s_parse.i4_ctb_x +
ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb;
/* Default values */
ps_sao->b3_y_type_idx = 0;
ps_sao->b3_cb_type_idx = 0;
ps_sao->b3_cr_type_idx = 0;
}
{
WORD32 ctb_indx;
ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y;
ps_codec->s_parse.s_bs_ctxt.pu1_pic_qp_const_in_ctb[ctb_indx >> 3] |= (1 << (ctb_indx & 7));
{
UWORD16 *pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx;
pu1_slice_idx[ctb_indx] = ps_codec->s_parse.i4_cur_independent_slice_idx;
}
}
if(0 == ps_codec->i4_slice_error)
{
ihevcd_parse_coding_quadtree(ps_codec,
(ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size),
(ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size),
ps_sps->i1_log2_ctb_size,
0);
}
else
{
tu_t *ps_tu = ps_codec->s_parse.ps_tu;
pu_t *ps_pu = ps_codec->s_parse.ps_pu;
ps_tu->b1_cb_cbf = 0;
ps_tu->b1_cr_cbf = 0;
ps_tu->b1_y_cbf = 0;
ps_tu->b4_pos_x = 0;
ps_tu->b4_pos_y = 0;
ps_tu->b1_transquant_bypass = 0;
ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2);
ps_tu->b7_qp = ps_codec->s_parse.u4_qp;
ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE;
ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE;
ps_tu->b1_first_tu_in_cu = 1;
ps_codec->s_parse.ps_tu++;
ps_codec->s_parse.s_cu.i4_tu_cnt++;
ps_codec->s_parse.i4_pic_tu_idx++;
ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP;
ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N;
ps_pu->b2_part_idx = 0;
ps_pu->b4_pos_x = 0;
ps_pu->b4_pos_y = 0;
ps_pu->b4_wd = (ctb_size >> 2) - 1;
ps_pu->b4_ht = (ctb_size >> 2) - 1;
ps_pu->b1_intra_flag = 0;
ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode;
ps_pu->b1_merge_flag = 1;
ps_pu->b3_merge_idx = 0;
ps_codec->s_parse.ps_pu++;
ps_codec->s_parse.i4_pic_pu_idx++;
}
if(0 == ps_codec->i4_slice_error)
end_of_slice_flag = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm);
else
end_of_slice_flag = 0;
AEV_TRACE("end_of_slice_flag", end_of_slice_flag, ps_codec->s_parse.s_cabac.u4_range);
/* In case of tiles or entropy sync, terminate cabac and copy cabac context backed up at the end of top-right CTB */
if(ps_pps->i1_tiles_enabled_flag || ps_pps->i1_entropy_coding_sync_enabled_flag)
{
WORD32 end_of_tile = 0;
WORD32 end_of_tile_row = 0;
/* Take a back up of cabac context models if entropy sync is enabled */
if(ps_pps->i1_entropy_coding_sync_enabled_flag || ps_pps->i1_tiles_enabled_flag)
{
if(1 == ps_codec->s_parse.i4_ctb_x)
{
WORD32 size = sizeof(ps_codec->s_parse.s_cabac.au1_ctxt_models);
memcpy(&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync, &ps_codec->s_parse.s_cabac.au1_ctxt_models, size);
}
}
/* Since tiles and entropy sync are not enabled simultaneously, the following will not result in any problems */
if((ps_codec->s_parse.i4_ctb_tile_x + 1) == (ps_tile->u2_wd))
{
end_of_tile_row = 1;
if((ps_codec->s_parse.i4_ctb_tile_y + 1) == ps_tile->u2_ht)
end_of_tile = 1;
}
if((0 == end_of_slice_flag) &&
((ps_pps->i1_tiles_enabled_flag && end_of_tile) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag && end_of_tile_row)))
{
WORD32 end_of_sub_stream_one_bit;
end_of_sub_stream_one_bit = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm);
AEV_TRACE("end_of_sub_stream_one_bit", end_of_sub_stream_one_bit, ps_codec->s_parse.s_cabac.u4_range);
/* TODO: Remove the check for offset when HM is updated to include a byte unconditionally even for aligned location */
/* For Ittiam streams this check should not be there, for HM9.1 streams this should be there */
if(ps_codec->s_parse.s_bitstrm.u4_bit_ofst % 8)
ihevcd_bits_flush_to_byte_boundary(&ps_codec->s_parse.s_bitstrm);
UNUSED(end_of_sub_stream_one_bit);
}
}
{
WORD32 ctb_indx;
ctb_addr = ps_codec->s_parse.i4_ctb_y * num_ctb_in_row + ps_codec->s_parse.i4_ctb_x;
ctb_indx = ++ctb_addr;
/* Store pu_idx for next CTB in frame level pu_idx array */
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = ctb_addr; //Next continuous ctb address
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.pu4_pic_pu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_pu_idx;
ps_codec->s_parse.i4_next_pu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu1_pu_map += num_min4x4_in_ctb;
/* Store tu_idx for next CTB in frame level tu_idx array */
if(1 == ps_codec->i4_num_cores)
{
ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ?
RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB;
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ?
RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB;
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx;
}
else
{
ctb_indx = ctb_addr;
if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb))
{
ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile.
if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1))
{
if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb)))
{
ctb_indx = ctb_addr;
}
else //Not last tile's end , but a tile end
{
tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1;
ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile.
}
}
}
ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx;
ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx;
}
ps_codec->s_parse.pu1_tu_map += num_min4x4_in_ctb;
}
/* QP array population has to be done if deblocking is enabled in the picture
* but some of the slices in the pic have it disabled */
if((0 != ps_codec->i4_disable_deblk_pic) &&
(1 == ps_slice_hdr->i1_slice_disable_deblocking_filter_flag))
{
bs_ctxt_t *ps_bs_ctxt = &ps_codec->s_parse.s_bs_ctxt;
WORD32 log2_ctb_size = ps_sps->i1_log2_ctb_size;
UWORD8 *pu1_qp;
WORD32 qp_strd;
WORD32 u4_qp_const_in_ctb;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 cur_tu_idx;
WORD32 i4_ctb_tu_cnt;
tu_t *ps_tu;
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y;
/* ctb_size/8 elements per CTB */
qp_strd = ps_sps->i2_pic_wd_in_ctb << (log2_ctb_size - 3);
pu1_qp = ps_bs_ctxt->pu1_pic_qp + ((ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * qp_strd) << (log2_ctb_size - 3));
u4_qp_const_in_ctb = ps_bs_ctxt->pu1_pic_qp_const_in_ctb[cur_ctb_idx >> 3] & (1 << (cur_ctb_idx & 7));
next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt;
if(1 == ps_codec->i4_num_cores)
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
}
else
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
}
ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx];
if(u4_qp_const_in_ctb)
{
pu1_qp[0] = ps_tu->b7_qp;
}
else
{
for(i = 0; i < i4_ctb_tu_cnt; i++, ps_tu++)
{
WORD32 start_pos_x;
WORD32 start_pos_y;
WORD32 tu_size;
/* start_pos_x and start_pos_y are in units of min TU size (4x4) */
start_pos_x = ps_tu->b4_pos_x;
start_pos_y = ps_tu->b4_pos_y;
tu_size = 1 << (ps_tu->b3_size + 2);
tu_size >>= 2; /* TU size divided by 4 */
if(0 == (start_pos_x & 1) && 0 == (start_pos_y & 1))
{
WORD32 row, col;
for(row = start_pos_y; row < start_pos_y + tu_size; row += 2)
{
for(col = start_pos_x; col < start_pos_x + tu_size; col += 2)
{
pu1_qp[(row >> 1) * qp_strd + (col >> 1)] = ps_tu->b7_qp;
}
}
}
}
}
}
if(ps_codec->i4_num_cores <= MV_PRED_NUM_CORES_THRESHOLD)
{
/*************************************************/
/**************** MV pred **********************/
/*************************************************/
WORD8 u1_top_ctb_avail = 1;
WORD8 u1_left_ctb_avail = 1;
WORD8 u1_top_lt_ctb_avail = 1;
WORD8 u1_top_rt_ctb_avail = 1;
WORD16 i2_wd_in_ctb;
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if((slice_start_ctb_idx < tile_start_ctb_idx))
{
i2_wd_in_ctb = ps_sps->i2_pic_wd_in_ctb;
}
else
{
i2_wd_in_ctb = ps_tile->u2_wd;
}
/* slice and tile boundaries */
if((0 == ps_codec->s_parse.i4_ctb_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
u1_top_rt_ctb_avail = 0;
}
if((0 == ps_codec->s_parse.i4_ctb_x) || (0 == ps_codec->s_parse.i4_ctb_tile_x))
{
u1_left_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) //TODO: For tile, not implemented
{
u1_top_rt_ctb_avail = 0;
}
}
}
/*For slices not beginning at start of a ctb row*/
else if(ps_codec->s_parse.i4_ctb_x > 0)
{
if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y))
{
u1_top_ctb_avail = 0;
u1_top_lt_ctb_avail = 0;
if(0 == ps_codec->s_parse.i4_ctb_slice_x)
{
u1_left_ctb_avail = 0;
}
if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x)
{
u1_top_rt_ctb_avail = 0;
}
}
else if((1 == ps_codec->s_parse.i4_ctb_slice_y) && (0 == ps_codec->s_parse.i4_ctb_slice_x))
{
u1_top_lt_ctb_avail = 0;
}
}
if(((ps_sps->i2_pic_wd_in_ctb - 1) == ps_codec->s_parse.i4_ctb_x) || ((ps_tile->u2_wd - 1) == ps_codec->s_parse.i4_ctb_tile_x))
{
u1_top_rt_ctb_avail = 0;
}
if(PSLICE == ps_slice_hdr->i1_slice_type
|| BSLICE == ps_slice_hdr->i1_slice_type)
{
mv_ctxt_t s_mv_ctxt;
process_ctxt_t *ps_proc;
UWORD32 *pu4_ctb_top_pu_idx;
UWORD32 *pu4_ctb_left_pu_idx;
UWORD32 *pu4_ctb_top_left_pu_idx;
WORD32 i4_ctb_pu_cnt;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 cur_pu_idx;
ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt;
i4_ctb_pu_cnt = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx]
- ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
pu4_ctb_top_pu_idx = ps_proc->pu4_pic_pu_idx_top
+ (ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE);
pu4_ctb_left_pu_idx = ps_proc->pu4_pic_pu_idx_left;
pu4_ctb_top_left_pu_idx = &ps_proc->u4_ctb_top_left_pu_idx;
/* Initializing s_mv_ctxt */
{
s_mv_ctxt.ps_pps = ps_pps;
s_mv_ctxt.ps_sps = ps_sps;
s_mv_ctxt.ps_slice_hdr = ps_slice_hdr;
s_mv_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
s_mv_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
s_mv_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx];
s_mv_ctxt.ps_pic_pu = ps_codec->s_parse.ps_pic_pu;
s_mv_ctxt.ps_tile = ps_tile;
s_mv_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map;
s_mv_ctxt.pu4_pic_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx;
s_mv_ctxt.pu1_pic_pu_map = ps_codec->s_parse.pu1_pic_pu_map;
s_mv_ctxt.i4_ctb_pu_cnt = i4_ctb_pu_cnt;
s_mv_ctxt.i4_ctb_start_pu_idx = cur_pu_idx;
s_mv_ctxt.u1_top_ctb_avail = u1_top_ctb_avail;
s_mv_ctxt.u1_top_rt_ctb_avail = u1_top_rt_ctb_avail;
s_mv_ctxt.u1_top_lt_ctb_avail = u1_top_lt_ctb_avail;
s_mv_ctxt.u1_left_ctb_avail = u1_left_ctb_avail;
}
ihevcd_get_mv_ctb(&s_mv_ctxt, pu4_ctb_top_pu_idx,
pu4_ctb_left_pu_idx, pu4_ctb_top_left_pu_idx);
}
else
{
WORD32 num_minpu_in_ctb = (ctb_size / MIN_PU_SIZE) * (ctb_size / MIN_PU_SIZE);
UWORD8 *pu1_pic_pu_map_ctb = ps_codec->s_parse.pu1_pic_pu_map +
(ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb) * num_minpu_in_ctb;
process_ctxt_t *ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
WORD32 row, col;
WORD32 pu_cnt;
WORD32 num_pu_per_ctb;
WORD32 cur_ctb_idx;
WORD32 next_ctb_idx;
WORD32 ctb_start_pu_idx;
UWORD32 *pu4_nbr_pu_idx = ps_proc->pu4_pic_pu_idx_map;
WORD32 nbr_pu_idx_strd = MAX_CTB_SIZE / MIN_PU_SIZE + 2;
pu_t *ps_pu;
for(row = 0; row < ctb_size / MIN_PU_SIZE; row++)
{
for(col = 0; col < ctb_size / MIN_PU_SIZE; col++)
{
pu1_pic_pu_map_ctb[row * ctb_size / MIN_PU_SIZE + col] = 0;
}
}
/* Neighbor PU idx update inside CTB */
/* 1byte per 4x4. Indicates the PU idx that 4x4 block belongs to */
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt;
num_pu_per_ctb = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx]
- ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
ctb_start_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
ps_pu = &ps_codec->s_parse.ps_pic_pu[ctb_start_pu_idx];
for(pu_cnt = 0; pu_cnt < num_pu_per_ctb; pu_cnt++, ps_pu++)
{
UWORD32 cur_pu_idx;
WORD32 pu_ht = (ps_pu->b4_ht + 1) << 2;
WORD32 pu_wd = (ps_pu->b4_wd + 1) << 2;
cur_pu_idx = ctb_start_pu_idx + pu_cnt;
for(row = 0; row < pu_ht / MIN_PU_SIZE; row++)
for(col = 0; col < pu_wd / MIN_PU_SIZE; col++)
pu4_nbr_pu_idx[(1 + ps_pu->b4_pos_x + col)
+ (1 + ps_pu->b4_pos_y + row)
* nbr_pu_idx_strd] =
cur_pu_idx;
}
/* Updating Top and Left pointers */
{
WORD32 rows_remaining = ps_sps->i2_pic_height_in_luma_samples
- (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size);
WORD32 ctb_size_left = MIN(ctb_size, rows_remaining);
/* Top Left */
/* saving top left before updating top ptr, as updating top ptr will overwrite the top left for the next ctb */
ps_proc->u4_ctb_top_left_pu_idx = ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + ctb_size / MIN_PU_SIZE - 1];
for(i = 0; i < ctb_size / MIN_PU_SIZE; i++)
{
/* Left */
/* Last column of au4_nbr_pu_idx */
ps_proc->pu4_pic_pu_idx_left[i] = pu4_nbr_pu_idx[(ctb_size / MIN_PU_SIZE)
+ (i + 1) * nbr_pu_idx_strd];
/* Top */
/* Last row of au4_nbr_pu_idx */
ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + i] =
pu4_nbr_pu_idx[(ctb_size_left / MIN_PU_SIZE) * nbr_pu_idx_strd + i + 1];
}
}
}
/*************************************************/
/****************** BS, QP *********************/
/*************************************************/
/* Check if deblock is disabled for the current slice or if it is disabled for the current picture
* because of disable deblock api
*/
if(0 == ps_codec->i4_disable_deblk_pic)
{
/* Boundary strength calculation is done irrespective of whether deblocking is disabled
* in the slice or not, to handle deblocking slice boundaries */
if((0 == ps_codec->i4_slice_error))
{
WORD32 i4_ctb_tu_cnt;
WORD32 cur_ctb_idx, next_ctb_idx;
WORD32 cur_pu_idx;
WORD32 cur_tu_idx;
process_ctxt_t *ps_proc;
ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)];
cur_ctb_idx = ps_codec->s_parse.i4_ctb_x
+ ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx];
next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt;
if(1 == ps_codec->i4_num_cores)
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB];
}
else
{
i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] -
ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx];
}
ps_codec->s_parse.s_bs_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_bs_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_bs_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tu_cnt = i4_ctb_tu_cnt;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_x = ps_codec->s_parse.i4_ctb_tile_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_y = ps_codec->s_parse.i4_ctb_tile_y;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_x = ps_codec->s_parse.i4_ctb_slice_x;
ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_y = ps_codec->s_parse.i4_ctb_slice_y;
ps_codec->s_parse.s_bs_ctxt.ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx];
ps_codec->s_parse.s_bs_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx];
ps_codec->s_parse.s_bs_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map;
ps_codec->s_parse.s_bs_ctxt.i4_next_pu_ctb_cnt = ps_codec->s_parse.i4_next_pu_ctb_cnt;
ps_codec->s_parse.s_bs_ctxt.i4_next_tu_ctb_cnt = ps_codec->s_parse.i4_next_tu_ctb_cnt;
ps_codec->s_parse.s_bs_ctxt.pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx;
ps_codec->s_parse.s_bs_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ps_codec->s_parse.s_bs_ctxt.ps_tile = ps_codec->s_parse.ps_tile;
if(ISLICE == ps_slice_hdr->i1_slice_type)
{
ihevcd_ctb_boundary_strength_islice(&ps_codec->s_parse.s_bs_ctxt);
}
else
{
ihevcd_ctb_boundary_strength_pbslice(&ps_codec->s_parse.s_bs_ctxt);
}
}
/* Boundary strength is set to zero if deblocking is disabled for the current slice */
if(0 != ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
WORD32 bs_strd = (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16);
UWORD32 *pu4_vert_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_vert_bs +
ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) +
ps_codec->s_parse.i4_ctb_y * bs_strd);
UWORD32 *pu4_horz_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_horz_bs +
ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) +
ps_codec->s_parse.i4_ctb_y * bs_strd);
memset(pu4_vert_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2);
memset(pu4_horz_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2);
}
}
}
DATA_SYNC();
/* Update the parse status map */
{
sps_t *ps_sps = ps_codec->s_parse.ps_sps;
UWORD8 *pu1_buf;
WORD32 idx;
idx = (ps_codec->s_parse.i4_ctb_x);
idx += ((ps_codec->s_parse.i4_ctb_y) * ps_sps->i2_pic_wd_in_ctb);
pu1_buf = (ps_codec->pu1_parse_map + idx);
*pu1_buf = 1;
}
/* Increment CTB x and y positions */
ps_codec->s_parse.i4_ctb_tile_x++;
ps_codec->s_parse.i4_ctb_x++;
ps_codec->s_parse.i4_ctb_slice_x++;
/*If tiles are enabled, handle the slice counters differently*/
if(ps_pps->i1_tiles_enabled_flag)
{
tile_start_ctb_idx = ps_tile->u1_pos_x
+ ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb);
slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x
+ ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb);
if((slice_start_ctb_idx < tile_start_ctb_idx))
{
if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u1_pos_x + ps_tile->u2_wd))
{
/* Reached end of slice row within a tile /frame */
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; //todo:Check
}
}
else if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u2_wd))
{
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = 0;
}
}
else
{
if(ps_codec->s_parse.i4_ctb_slice_x == ps_tile->u2_wd)
{
/* Reached end of slice row within a tile /frame */
ps_codec->s_parse.i4_ctb_slice_y++;
ps_codec->s_parse.i4_ctb_slice_x = 0;
}
}
if(ps_codec->s_parse.i4_ctb_tile_x == (ps_tile->u2_wd))
{
/* Reached end of tile row */
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_tile_y++;
ps_codec->s_parse.i4_ctb_y++;
if(ps_codec->s_parse.i4_ctb_tile_y == (ps_tile->u2_ht))
{
/* Reached End of Tile */
ps_codec->s_parse.i4_ctb_tile_y = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.ps_tile++;
if((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb) && (ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb))
{
/* Reached end of frame */
end_of_pic = 1;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = ps_sps->i2_pic_ht_in_ctb;
}
else
{
/* Initialize ctb_x and ctb_y to start of next tile */
ps_tile = ps_codec->s_parse.ps_tile;
ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_y = ps_tile->u1_pos_y;
ps_codec->s_parse.i4_ctb_tile_y = 0;
ps_codec->s_parse.i4_ctb_tile_x = 0;
ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x;
ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y;
}
}
}
ps_codec->s_parse.i4_next_ctb_indx = ps_codec->s_parse.i4_ctb_x +
ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb;
/* If the current slice is in error, check if the next slice's address
* is reached and mark the end_of_slice flag */
if(ps_codec->i4_slice_error)
{
slice_header_t *ps_slice_hdr_next = ps_slice_hdr + 1;
WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x +
ps_slice_hdr_next->i2_ctb_y * ps_sps->i2_pic_wd_in_ctb;
if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr)
end_of_slice_flag = 1;
}
/* If the codec is running in single core mode
* then call process function for current CTB
*/
if((1 == ps_codec->i4_num_cores) && (ps_codec->s_parse.i4_ctb_tile_x == 0))
{
process_ctxt_t *ps_proc = &ps_codec->as_process[0];
ps_proc->i4_ctb_cnt = ps_proc->ps_tile->u2_wd;
ihevcd_process(ps_proc);
}
/* If the bytes for the current slice are exhausted
* set end_of_slice flag to 1
* This slice will be treated as incomplete */
if((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu1_buf_max + BITSTRM_OFF_THRS <
((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu4_buf + (ps_codec->s_parse.s_bitstrm.u4_bit_ofst / 8)))
{
if(0 == ps_codec->i4_slice_error)
end_of_slice_flag = 1;
}
if(end_of_pic)
break;
} while(!end_of_slice_flag);
/* Reset slice error */
ps_codec->i4_slice_error = 0;
/* Increment the slice index for parsing next slice */
if(0 == end_of_pic)
{
while(1)
{
WORD32 parse_slice_idx;
parse_slice_idx = ps_codec->s_parse.i4_cur_slice_idx;
parse_slice_idx++;
{
/* If the next slice header is not initialized, update cur_slice_idx and break */
if((1 == ps_codec->i4_num_cores) || (0 != (parse_slice_idx & (MAX_SLICE_HDR_CNT - 1))))
{
ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx;
break;
}
/* If the next slice header is initialised, wait for the parsed slices to be processed */
else
{
WORD32 ctb_indx = 0;
while(ctb_indx != ps_sps->i4_pic_size_in_ctb)
{
WORD32 parse_status = *(ps_codec->pu1_parse_map + ctb_indx);
volatile WORD32 proc_status = *(ps_codec->pu1_proc_map + ctb_indx) & 1;
if(parse_status == proc_status)
ctb_indx++;
}
ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx;
break;
}
}
}
}
else
{
#if FRAME_ILF_PAD
if(FRAME_ILF_PAD && 1 == ps_codec->i4_num_cores)
{
if(ps_slice_hdr->i4_abs_pic_order_cnt == 0)
{
DUMP_PRE_ILF(ps_codec->as_process[0].pu1_cur_pic_luma,
ps_codec->as_process[0].pu1_cur_pic_chroma,
ps_sps->i2_pic_width_in_luma_samples,
ps_sps->i2_pic_height_in_luma_samples,
ps_codec->i4_strd);
DUMP_BS(ps_codec->as_process[0].s_bs_ctxt.pu4_pic_vert_bs,
ps_codec->as_process[0].s_bs_ctxt.pu4_pic_horz_bs,
ps_sps->i2_pic_wd_in_ctb * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb,
(ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb);
DUMP_QP(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp,
(ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CU_SIZE * MIN_CU_SIZE));
DUMP_QP_CONST_IN_CTB(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp_const_in_ctb,
(ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CTB_SIZE * MIN_CTB_SIZE) / 8);
DUMP_NO_LOOP_FILTER(ps_codec->as_process[0].pu1_pic_no_loop_filter_flag,
(ps_sps->i2_pic_width_in_luma_samples / MIN_CU_SIZE) * (ps_sps->i2_pic_height_in_luma_samples / MIN_CU_SIZE) / 8);
DUMP_OFFSETS(ps_slice_hdr->i1_beta_offset_div2,
ps_slice_hdr->i1_tc_offset_div2,
ps_pps->i1_pic_cb_qp_offset,
ps_pps->i1_pic_cr_qp_offset);
}
ps_codec->s_parse.s_deblk_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_deblk_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_deblk_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_deblk_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ps_codec->s_parse.s_deblk_ctxt.is_chroma_yuv420sp_vu = (ps_codec->e_ref_chroma_fmt == IV_YUV_420SP_VU);
ps_codec->s_parse.s_sao_ctxt.ps_pps = ps_codec->s_parse.ps_pps;
ps_codec->s_parse.s_sao_ctxt.ps_sps = ps_codec->s_parse.ps_sps;
ps_codec->s_parse.s_sao_ctxt.ps_codec = ps_codec;
ps_codec->s_parse.s_sao_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr;
ihevcd_ilf_pad_frame(&ps_codec->s_parse.s_deblk_ctxt, &ps_codec->s_parse.s_sao_ctxt);
}
#endif
ps_codec->s_parse.i4_end_of_frame = 1;
}
return ret;
}
| 174,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
Commit Message: bug #248, fix Out-Of-Bounds Read in read_image_tga
CWE ID: CWE-125 | int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
| 169,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: void ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
auto* plugin_rfh = RenderFrameHost::FromID(embedder_render_process_id,
plugin_frame_routing_id);
if (!plugin_rfh) {
plugin_rfh = RenderFrameHost::FromPlaceholderId(embedder_render_process_id,
plugin_frame_routing_id);
}
if (!plugin_rfh) {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_RetryCreatingMimeHandlerViewGuest(
element_instance_id));
guest_view->Destroy(true);
return;
}
if (guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh)) {
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
is_full_page_plugin);
} else {
frame_navigation_helpers_[element_instance_id] =
std::make_unique<FrameNavigationHelper>(
plugin_rfh, guest_view->guest_instance_id(), element_instance_id,
is_full_page_plugin, this);
}
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | void ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
| 173,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: int main()
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, "heap_overflow.tga");
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
return gdNumFailures();
}
Commit Message: Fix OOB reads of the TGA decompression buffer
It is possible to craft TGA files which will overflow the decompression
buffer, but not the image's bitmap. Therefore we also have to check for
potential decompression buffer overflows.
This issue had been reported by Ibrahim El-Sayed to [email protected];
a modified case exposing an off-by-one error of the first patch had been
provided by Konrad Beckmann.
This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906
as well.
CWE ID: CWE-125 | int main()
{
check_file("heap_overflow_1.tga");
check_file("heap_overflow_2.tga");
return gdNumFailures();
}
static void check_file(char *basename)
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, basename);
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
}
| 170,121 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_verify_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t msg_buffer,
const gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
OM_uint32 ret;
ret = gss_verify_mic(minor_status,
context_handle,
msg_buffer,
token_buffer,
qop_state);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_verify_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t msg_buffer,
const gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_verify_mic(minor_status,
sc->ctx_handle,
msg_buffer,
token_buffer,
qop_state);
return (ret);
}
| 166,669 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn,
PNG_CONST int interlace_typeIn,
PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn,
PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn,
PNG_CONST char *name,
PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In,
PNG_CONST int expand16In, PNG_CONST int do_backgroundIn,
PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
{
gamma_display d;
context(&pmIn->this, fault);
gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
palette_numberIn, interlace_typeIn, 0, 0, 0),
file_gammaIn, screen_gammaIn, sbitIn,
threshold_testIn, use_input_precisionIn, scale16In,
expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
Try
{
png_structp pp;
png_infop pi;
gama_modification gama_mod;
srgb_modification srgb_mod;
sbit_modification sbit_mod;
/* For the moment don't use the png_modifier support here. */
d.pm->encoding_counter = 0;
modifier_set_encoding(d.pm); /* Just resets everything */
d.pm->current_gamma = d.file_gamma;
/* Make an appropriate modifier to set the PNG file gamma to the
* given gamma value and the sBIT chunk to the given precision.
*/
d.pm->modifications = NULL;
gama_modification_init(&gama_mod, d.pm, d.file_gamma);
srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
if (d.sbit > 0)
sbit_modification_init(&sbit_mod, d.pm, d.sbit);
modification_reset(d.pm->modifications);
/* Get a png_struct for writing the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
standard_palette_init(&d.this);
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
gamma_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
gamma_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
gamma_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
if (d.pm->log && !d.threshold_test && !d.this.speed)
fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
d.this.bit_depth, colour_types[d.this.colour_type], name,
d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
/* Log the summary values too. */
if (d.this.colour_type == 0 || d.this.colour_type == 4)
{
switch (d.this.bit_depth)
{
case 1:
break;
case 2:
if (d.maxerrout > d.pm->error_gray_2)
d.pm->error_gray_2 = d.maxerrout;
break;
case 4:
if (d.maxerrout > d.pm->error_gray_4)
d.pm->error_gray_4 = d.maxerrout;
break;
case 8:
if (d.maxerrout > d.pm->error_gray_8)
d.pm->error_gray_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_gray_16)
d.pm->error_gray_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 1)");
}
}
else if (d.this.colour_type == 2 || d.this.colour_type == 6)
{
switch (d.this.bit_depth)
{
case 8:
if (d.maxerrout > d.pm->error_color_8)
d.pm->error_color_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_color_16)
d.pm->error_color_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 2)");
}
}
else if (d.this.colour_type == 3)
{
if (d.maxerrout > d.pm->error_indexed)
d.pm->error_indexed = d.maxerrout;
}
}
Catch(fault)
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn,
gamma_test(png_modifier *pmIn, const png_byte colour_typeIn,
const png_byte bit_depthIn, const int palette_numberIn,
const int interlace_typeIn,
const double file_gammaIn, const double screen_gammaIn,
const png_byte sbitIn, const int threshold_testIn,
const char *name,
const int use_input_precisionIn, const int scale16In,
const int expand16In, const int do_backgroundIn,
const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
{
gamma_display d;
context(&pmIn->this, fault);
gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
palette_numberIn, interlace_typeIn, 0, 0, 0),
file_gammaIn, screen_gammaIn, sbitIn,
threshold_testIn, use_input_precisionIn, scale16In,
expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
Try
{
png_structp pp;
png_infop pi;
gama_modification gama_mod;
srgb_modification srgb_mod;
sbit_modification sbit_mod;
/* For the moment don't use the png_modifier support here. */
d.pm->encoding_counter = 0;
modifier_set_encoding(d.pm); /* Just resets everything */
d.pm->current_gamma = d.file_gamma;
/* Make an appropriate modifier to set the PNG file gamma to the
* given gamma value and the sBIT chunk to the given precision.
*/
d.pm->modifications = NULL;
gama_modification_init(&gama_mod, d.pm, d.file_gamma);
srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
if (d.sbit > 0)
sbit_modification_init(&sbit_mod, d.pm, d.sbit);
modification_reset(d.pm->modifications);
/* Get a png_struct for reading the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
standard_palette_init(&d.this);
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
gamma_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
gamma_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
gamma_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
if (d.pm->log && !d.threshold_test && !d.this.speed)
fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
d.this.bit_depth, colour_types[d.this.colour_type], name,
d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
/* Log the summary values too. */
if (d.this.colour_type == 0 || d.this.colour_type == 4)
{
switch (d.this.bit_depth)
{
case 1:
break;
case 2:
if (d.maxerrout > d.pm->error_gray_2)
d.pm->error_gray_2 = d.maxerrout;
break;
case 4:
if (d.maxerrout > d.pm->error_gray_4)
d.pm->error_gray_4 = d.maxerrout;
break;
case 8:
if (d.maxerrout > d.pm->error_gray_8)
d.pm->error_gray_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_gray_16)
d.pm->error_gray_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 1)");
}
}
else if (d.this.colour_type == 2 || d.this.colour_type == 6)
{
switch (d.this.bit_depth)
{
case 8:
if (d.maxerrout > d.pm->error_color_8)
d.pm->error_color_8 = d.maxerrout;
break;
case 16:
if (d.maxerrout > d.pm->error_color_16)
d.pm->error_color_16 = d.maxerrout;
break;
default:
png_error(pp, "bad bit depth (internal: 2)");
}
}
else if (d.this.colour_type == 3)
{
if (d.maxerrout > d.pm->error_indexed)
d.pm->error_indexed = d.maxerrout;
}
}
Catch(fault)
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
| 173,614 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.