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: cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)
{
int sock;
cib_remote_opaque_t *private = cib->variant_opaque;
struct sockaddr_in addr;
int rc = 0;
char *server = private->server;
int ret_ga;
struct addrinfo *res;
struct addrinfo hints;
xmlNode *answer = NULL;
xmlNode *login = NULL;
static struct mainloop_fd_callbacks cib_fd_callbacks =
{
.dispatch = cib_remote_dispatch,
.destroy = cib_remote_connection_destroy,
};
connection->socket = 0;
connection->session = NULL;
/* create socket */
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
crm_perror(LOG_ERR, "Socket creation failed");
return -1;
}
/* getaddrinfo */
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_RAW;
if (hints.ai_family == AF_INET6) {
hints.ai_protocol = IPPROTO_ICMPV6;
} else {
hints.ai_protocol = IPPROTO_ICMP;
}
crm_debug("Looking up %s", server);
ret_ga = getaddrinfo(server, NULL, &hints, &res);
if (ret_ga) {
crm_err("getaddrinfo: %s", gai_strerror(ret_ga));
close(sock);
return -1;
}
if (res->ai_canonname) {
server = res->ai_canonname;
}
crm_debug("Got address %s for %s", server, private->server);
if (!res->ai_addr) {
fprintf(stderr, "getaddrinfo failed");
crm_exit(1);
}
#if 1
memcpy(&addr, res->ai_addr, res->ai_addrlen);
#else
/* connect to server */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(server);
#endif
addr.sin_port = htons(private->port);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
crm_perror(LOG_ERR, "Connection to %s:%d failed", server, private->port);
close(sock);
return -1;
}
if (connection->encrypted) {
/* initialize GnuTls lib */
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_global_init();
gnutls_anon_allocate_client_credentials(&anon_cred_c);
/* bind the socket to GnuTls lib */
connection->session = create_tls_session(sock, GNUTLS_CLIENT);
if (connection->session == NULL) {
crm_perror(LOG_ERR, "Session creation for %s:%d failed", server, private->port);
close(sock);
cib_tls_close(cib);
return -1;
}
#else
return -EPROTONOSUPPORT;
#endif
} else {
connection->session = GUINT_TO_POINTER(sock);
}
/* login to server */
login = create_xml_node(NULL, "cib_command");
crm_xml_add(login, "op", "authenticate");
crm_xml_add(login, "user", private->user);
crm_xml_add(login, "password", private->passwd);
crm_xml_add(login, "hidden", "password");
crm_send_remote_msg(connection->session, login, connection->encrypted);
free_xml(login);
answer = crm_recv_remote_msg(connection->session, connection->encrypted);
crm_log_xml_trace(answer, "Reply");
if (answer == NULL) {
rc = -EPROTO;
} else {
/* grab the token */
const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);
const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);
if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {
crm_err("Invalid registration message: %s", msg_type);
rc = -EPROTO;
} else if (tmp_ticket == NULL) {
rc = -EPROTO;
} else {
connection->token = strdup(tmp_ticket);
}
}
if (rc != 0) {
cib_tls_close(cib);
}
connection->socket = sock;
connection->source = mainloop_add_fd("cib-remote", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)
cib_tls_signon(cib_t * cib, struct remote_connection_s *connection, gboolean event_channel)
{
int sock;
cib_remote_opaque_t *private = cib->variant_opaque;
int rc = 0;
int disconnected = 0;
xmlNode *answer = NULL;
xmlNode *login = NULL;
static struct mainloop_fd_callbacks cib_fd_callbacks = { 0, };
cib_fd_callbacks.dispatch = event_channel ? cib_remote_callback_dispatch : cib_remote_command_dispatch;
cib_fd_callbacks.destroy = cib_remote_connection_destroy;
connection->socket = 0;
connection->session = NULL;
sock = crm_remote_tcp_connect(private->server, private->port);
if (sock <= 0) {
crm_perror(LOG_ERR, "remote tcp connection to %s:%d failed", private->server, private->port);
}
connection->socket = sock;
if (connection->encrypted) {
/* initialize GnuTls lib */
#ifdef HAVE_GNUTLS_GNUTLS_H
if (remote_gnutls_credentials_init == FALSE) {
gnutls_global_init();
gnutls_anon_allocate_client_credentials(&anon_cred_c);
remote_gnutls_credentials_init = TRUE;
}
/* bind the socket to GnuTls lib */
connection->session = crm_create_anon_tls_session(sock, GNUTLS_CLIENT, anon_cred_c);
if (crm_initiate_client_tls_handshake(connection->session, DEFAULT_CLIENT_HANDSHAKE_TIMEOUT) != 0) {
crm_err("Session creation for %s:%d failed", private->server, private->port);
gnutls_deinit(*connection->session);
gnutls_free(connection->session);
connection->session = NULL;
cib_tls_close(cib);
return -1;
}
#else
return -EPROTONOSUPPORT;
#endif
} else {
connection->session = GUINT_TO_POINTER(sock);
}
/* login to server */
login = create_xml_node(NULL, "cib_command");
crm_xml_add(login, "op", "authenticate");
crm_xml_add(login, "user", private->user);
crm_xml_add(login, "password", private->passwd);
crm_xml_add(login, "hidden", "password");
crm_send_remote_msg(connection->session, login, connection->encrypted);
free_xml(login);
crm_recv_remote_msg(connection->session, &connection->recv_buf, connection->encrypted, -1, &disconnected);
if (disconnected) {
rc = -ENOTCONN;
}
answer = crm_parse_remote_buffer(&connection->recv_buf);
crm_log_xml_trace(answer, "Reply");
if (answer == NULL) {
rc = -EPROTO;
} else {
/* grab the token */
const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);
const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);
if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {
crm_err("Invalid registration message: %s", msg_type);
rc = -EPROTO;
} else if (tmp_ticket == NULL) {
rc = -EPROTO;
} else {
connection->token = strdup(tmp_ticket);
}
}
free_xml(answer);
answer = NULL;
if (rc != 0) {
cib_tls_close(cib);
return rc;
}
crm_trace("remote client connection established");
connection->source = mainloop_add_fd("cib-remote", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);
return rc;
}
| 166,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids,
size_t glyph_count,
IntegerSet* glyph_id_processed) {
if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) {
return false;
}
GlyphTablePtr glyph_table =
down_cast<GlyphTable*>(font_->GetTable(Tag::glyf));
LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca));
if (glyph_table == NULL || loca_table == NULL) {
return false;
}
IntegerSet glyph_id_remaining;
glyph_id_remaining.insert(0); // Always include glyph id 0.
for (size_t i = 0; i < glyph_count; ++i) {
glyph_id_remaining.insert(glyph_ids[i]);
}
while (!glyph_id_remaining.empty()) {
IntegerSet comp_glyph_id;
for (IntegerSet::iterator i = glyph_id_remaining.begin(),
e = glyph_id_remaining.end(); i != e; ++i) {
if (*i < 0 || *i >= loca_table->NumGlyphs()) {
continue;
}
int32_t length = loca_table->GlyphLength(*i);
if (length == 0) {
continue;
}
int32_t offset = loca_table->GlyphOffset(*i);
GlyphPtr glyph;
glyph.Attach(glyph_table->GetGlyph(offset, length));
if (glyph == NULL) {
continue;
}
if (glyph->GlyphType() == GlyphType::kComposite) {
Ptr<GlyphTable::CompositeGlyph> comp_glyph =
down_cast<GlyphTable::CompositeGlyph*>(glyph.p_);
for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) {
int32_t glyph_id = comp_glyph->GlyphIndex(j);
if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() &&
glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) {
comp_glyph_id.insert(comp_glyph->GlyphIndex(j));
}
}
}
glyph_id_processed->insert(*i);
}
glyph_id_remaining.clear();
glyph_id_remaining = comp_glyph_id;
}
}
Commit Message: Fix compile warning.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/7572039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95563 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids,
size_t glyph_count,
IntegerSet* glyph_id_processed) {
if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) {
return false;
}
GlyphTablePtr glyph_table =
down_cast<GlyphTable*>(font_->GetTable(Tag::glyf));
LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca));
if (glyph_table == NULL || loca_table == NULL) {
return false;
}
IntegerSet glyph_id_remaining;
glyph_id_remaining.insert(0); // Always include glyph id 0.
for (size_t i = 0; i < glyph_count; ++i) {
glyph_id_remaining.insert(glyph_ids[i]);
}
while (!glyph_id_remaining.empty()) {
IntegerSet comp_glyph_id;
for (IntegerSet::iterator i = glyph_id_remaining.begin(),
e = glyph_id_remaining.end(); i != e; ++i) {
if (*i < 0 || *i >= loca_table->NumGlyphs()) {
continue;
}
int32_t length = loca_table->GlyphLength(*i);
if (length == 0) {
continue;
}
int32_t offset = loca_table->GlyphOffset(*i);
GlyphPtr glyph;
glyph.Attach(glyph_table->GetGlyph(offset, length));
if (glyph == NULL) {
continue;
}
if (glyph->GlyphType() == GlyphType::kComposite) {
Ptr<GlyphTable::CompositeGlyph> comp_glyph =
down_cast<GlyphTable::CompositeGlyph*>(glyph.p_);
for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) {
int32_t glyph_id = comp_glyph->GlyphIndex(j);
if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() &&
glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) {
comp_glyph_id.insert(comp_glyph->GlyphIndex(j));
}
}
}
glyph_id_processed->insert(*i);
}
glyph_id_remaining.clear();
glyph_id_remaining = comp_glyph_id;
}
return true;
}
| 170,329 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) (buffer[0] << 8);
value|=buffer[1];
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
| 169,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context,
const char* name,
const char** attrs) {
buzz::QName qname = context->ResolveQName(name, false);
const std::string &element = qname.LocalPart();
if (element.compare("autofillqueryresponse") == 0) {
*upload_required_ = USE_UPLOAD_RATES;
if (*attrs) {
buzz::QName attribute_qname = context->ResolveQName(attrs[0], true);
const std::string &attribute_name = attribute_qname.LocalPart();
if (attribute_name.compare("uploadrequired") == 0) {
if (strcmp(attrs[1], "true") == 0)
*upload_required_ = UPLOAD_REQUIRED;
else if (strcmp(attrs[1], "false") == 0)
*upload_required_ = UPLOAD_NOT_REQUIRED;
}
}
} else if (element.compare("field") == 0) {
if (!attrs[0]) {
context->RaiseError(XML_ERROR_ABORTED);
return;
}
AutoFillFieldType field_type = UNKNOWN_TYPE;
buzz::QName attribute_qname = context->ResolveQName(attrs[0], true);
const std::string &attribute_name = attribute_qname.LocalPart();
if (attribute_name.compare("autofilltype") == 0) {
int value = GetIntValue(context, attrs[1]);
field_type = static_cast<AutoFillFieldType>(value);
if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) {
field_type = NO_SERVER_DATA;
}
}
field_types_->push_back(field_type);
}
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context,
const char* name,
const char** attrs) {
buzz::QName qname = context->ResolveQName(name, false);
const std::string& element = qname.LocalPart();
if (element.compare("autofillqueryresponse") == 0) {
// We check for the upload required attribute below, but if it's not
// present, we use the default upload rates. Likewise, by default we assume
// an empty experiment id.
*upload_required_ = USE_UPLOAD_RATES;
*experiment_id_ = std::string();
// |attrs| is a NULL-terminated list of (attribute, value) pairs.
while (*attrs) {
buzz::QName attribute_qname = context->ResolveQName(attrs[0], true);
const std::string& attribute_name = attribute_qname.LocalPart();
if (attribute_name.compare("uploadrequired") == 0) {
if (strcmp(attrs[1], "true") == 0)
*upload_required_ = UPLOAD_REQUIRED;
else if (strcmp(attrs[1], "false") == 0)
*upload_required_ = UPLOAD_NOT_REQUIRED;
} else if (attribute_name.compare("experimentid") == 0) {
*experiment_id_ = attrs[1];
}
// Advance to the next (attribute, value) pair.
attrs += 2;
}
} else if (element.compare("field") == 0) {
if (!attrs[0]) {
context->RaiseError(XML_ERROR_ABORTED);
return;
}
AutoFillFieldType field_type = UNKNOWN_TYPE;
buzz::QName attribute_qname = context->ResolveQName(attrs[0], true);
const std::string& attribute_name = attribute_qname.LocalPart();
if (attribute_name.compare("autofilltype") == 0) {
int value = GetIntValue(context, attrs[1]);
field_type = static_cast<AutoFillFieldType>(value);
if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) {
field_type = NO_SERVER_DATA;
}
}
field_types_->push_back(field_type);
}
}
| 170,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: int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
if (cmd & 0x01) off = *delta++;
if (cmd & 0x02) off |= *delta++ << 8UL;
if (cmd & 0x04) off |= *delta++ << 16UL;
if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL);
if (cmd & 0x10) len = *delta++;
if (cmd & 0x20) len |= *delta++ << 8UL;
if (cmd & 0x40) len |= *delta++ << 16UL;
if (!len) len = 0x10000;
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
Commit Message: delta: fix out-of-bounds read of delta
When computing the offset and length of the delta base, we repeatedly
increment the `delta` pointer without checking whether we have advanced
past its end already, which can thus result in an out-of-bounds read.
Fix this by repeatedly checking whether we have reached the end. Add a
test which would cause Valgrind to produce an error.
Reported-by: Riccardo Schirone <[email protected]>
Test-provided-by: Riccardo Schirone <[email protected]>
CWE ID: CWE-125 | int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
| 169,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *target;
int ret, i;
ret = -EINVAL;
ch = ioctx->ch;
BUG_ON(!ch);
BUG_ON(!ch->sport);
sdev = ch->sport->sdev;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
for (i = 0; i < ch->rq_size; ++i) {
target = ch->ioctx_ring[i];
if (target->cmd.se_lun == ioctx->cmd.se_lun &&
target->cmd.tag == tag &&
srpt_get_cmd_state(target) != SRPT_STATE_DONE) {
ret = 0;
/* now let the target core abort &target->cmd; */
break;
}
}
spin_unlock_irq(&sdev->spinlock);
return ret;
}
Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt()
Let the target core check task existence instead of the SRP target
driver. Additionally, let the target core check the validity of the
task management request instead of the ib_srpt driver.
This patch fixes the following kernel crash:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000001
IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt]
Oops: 0002 [#1] SMP
Call Trace:
[<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt]
[<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt]
[<ffffffff8109726f>] kthread+0xcf/0xe0
[<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0
Signed-off-by: Bart Van Assche <[email protected]>
Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr")
Tested-by: Alex Estrin <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Cc: Nicholas Bellinger <[email protected]>
Cc: Sagi Grimberg <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-476 | static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
| 167,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_array(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an array is a possibly empty sequence of array elements, separated by
* commas and surrounded by square brackets.
*/
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
if (astart != NULL)
(*astart) (sem->semstate);
* array end.
*/
lex->lex_level++;
lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
{
parse_array_element(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_array_element(lex, sem);
}
lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
lex->lex_level--;
if (aend != NULL)
(*aend) (sem->semstate);
}
Commit Message:
CWE ID: CWE-119 | parse_array(JsonLexContext *lex, JsonSemAction *sem)
{
/*
* an array is a possibly empty sequence of array elements, separated by
* commas and surrounded by square brackets.
*/
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
json_struct_action astart = sem->array_start;
json_struct_action aend = sem->array_end;
check_stack_depth();
if (astart != NULL)
(*astart) (sem->semstate);
* array end.
*/
lex->lex_level++;
lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
{
parse_array_element(lex, sem);
while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
parse_array_element(lex, sem);
}
lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
lex->lex_level--;
if (aend != NULL)
(*aend) (sem->semstate);
}
| 164,679 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int ret = 0, size = 0;
const char *name = NULL;
char *value = NULL;
struct iattr newattrs;
umode_t new_mode = inode->i_mode, old_mode = inode->i_mode;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_equiv_mode(acl, &new_mode);
if (ret < 0)
goto out;
if (ret == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
ret = acl ? -EINVAL : 0;
goto out;
}
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
ret = -EINVAL;
goto out;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_NOFS);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out_free;
}
if (new_mode != old_mode) {
newattrs.ia_mode = new_mode;
newattrs.ia_valid = ATTR_MODE;
ret = __ceph_setattr(inode, &newattrs);
if (ret)
goto out_free;
}
ret = __ceph_setxattr(inode, name, value, size, 0);
if (ret) {
if (new_mode != old_mode) {
newattrs.ia_mode = old_mode;
newattrs.ia_valid = ATTR_MODE;
__ceph_setattr(inode, &newattrs);
}
goto out_free;
}
ceph_set_cached_acl(inode, type, acl);
out_free:
kfree(value);
out:
return ret;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285 | int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int ret = 0, size = 0;
const char *name = NULL;
char *value = NULL;
struct iattr newattrs;
umode_t new_mode = inode->i_mode, old_mode = inode->i_mode;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_update_mode(inode, &new_mode, &acl);
if (ret)
goto out;
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
ret = acl ? -EINVAL : 0;
goto out;
}
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
ret = -EINVAL;
goto out;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_NOFS);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out_free;
}
if (new_mode != old_mode) {
newattrs.ia_mode = new_mode;
newattrs.ia_valid = ATTR_MODE;
ret = __ceph_setattr(inode, &newattrs);
if (ret)
goto out_free;
}
ret = __ceph_setxattr(inode, name, value, size, 0);
if (ret) {
if (new_mode != old_mode) {
newattrs.ia_mode = old_mode;
newattrs.ia_valid = ATTR_MODE;
__ceph_setattr(inode, &newattrs);
}
goto out_free;
}
ceph_set_cached_acl(inode, type, acl);
out_free:
kfree(value);
out:
return ret;
}
| 166,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_wrap_iov_length (minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
int * conf_state;
gss_iov_buffer_desc * iov;
int iov_count;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_wrap_iov_args(minor_status, context_handle,
conf_req_flag, qop_req,
conf_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_wrap_iov_length) {
status = mech->gss_wrap_iov_length(
minor_status,
ctx->internal_ctx_id,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_wrap_iov_length (minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
int * conf_state;
gss_iov_buffer_desc * iov;
int iov_count;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_wrap_iov_args(minor_status, context_handle,
conf_req_flag, qop_req,
conf_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_wrap_iov_length) {
status = mech->gss_wrap_iov_length(
minor_status,
ctx->internal_ctx_id,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
| 168,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
Commit Message: Infobar Windows Media Player plug-in by default.
BUG=51464
Review URL: http://codereview.chromium.org/7080048
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87500 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
else if (name == webkit::npapi::PluginGroup::kWindowsMediaPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.WindowsMediaPlayer"));
}
| 170,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ConnectIBusSignals() {
if (!ibus_) {
return;
}
g_signal_connect_after(ibus_,
"connected",
G_CALLBACK(IBusBusConnectedCallback),
this);
g_signal_connect(ibus_,
"disconnected",
G_CALLBACK(IBusBusDisconnectedCallback),
this);
g_signal_connect(ibus_,
"global-engine-changed",
G_CALLBACK(IBusBusGlobalEngineChangedCallback),
this);
g_signal_connect(ibus_,
"name-owner-changed",
G_CALLBACK(IBusBusNameOwnerChangedCallback),
this);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ConnectIBusSignals() {
if (!ibus_) {
return;
}
g_signal_connect_after(ibus_,
"connected",
G_CALLBACK(IBusBusConnectedThunk),
this);
g_signal_connect(ibus_,
"disconnected",
G_CALLBACK(IBusBusDisconnectedThunk),
this);
g_signal_connect(ibus_,
"global-engine-changed",
G_CALLBACK(IBusBusGlobalEngineChangedThunk),
this);
g_signal_connect(ibus_,
"name-owner-changed",
G_CALLBACK(IBusBusNameOwnerChangedThunk),
this);
}
| 170,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */
unsigned char /* out */ **pixels, /* decoded pixels */
size_t /* out */ *pwidth, /* image width */
size_t /* out */ *pheight, /* image height */
unsigned char /* out */ **palette, /* ARGB palette */
size_t /* out */ *ncolors /* palette size (<= 256) */)
{
int n, i, r, g, b, sixel_vertical_mask, c;
int posision_x, posision_y;
int max_x, max_y;
int attributed_pan, attributed_pad;
int attributed_ph, attributed_pv;
int repeat_count, color_index, max_color_index = 2, background_color_index;
int param[10];
int sixel_palet[SIXEL_PALETTE_MAX];
unsigned char *imbuf, *dmbuf;
int imsx, imsy;
int dmsx, dmsy;
int y;
posision_x = posision_y = 0;
max_x = max_y = 0;
attributed_pan = 2;
attributed_pad = 1;
attributed_ph = attributed_pv = 0;
repeat_count = 1;
color_index = 0;
background_color_index = 0;
imsx = 2048;
imsy = 2048;
imbuf = (unsigned char *) AcquireQuantumMemory(imsx * imsy,1);
if (imbuf == NULL) {
return(MagickFalse);
}
for (n = 0; n < 16; n++) {
sixel_palet[n] = sixel_default_color_table[n];
}
/* colors 16-231 are a 6x6x6 color cube */
for (r = 0; r < 6; r++) {
for (g = 0; g < 6; g++) {
for (b = 0; b < 6; b++) {
sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51);
}
}
}
/* colors 232-255 are a grayscale ramp, intentionally leaving out */
for (i = 0; i < 24; i++) {
sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11);
}
for (; n < SIXEL_PALETTE_MAX; n++) {
sixel_palet[n] = SIXEL_RGB(255, 255, 255);
}
(void) ResetMagickMemory(imbuf, background_color_index, imsx * imsy);
while (*p != '\0') {
if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) {
if (*p == '\033') {
p++;
}
p = get_params(++p, param, &n);
if (*p == 'q') {
p++;
if (n > 0) { /* Pn1 */
switch(param[0]) {
case 0:
case 1:
attributed_pad = 2;
break;
case 2:
attributed_pad = 5;
break;
case 3:
attributed_pad = 4;
break;
case 4:
attributed_pad = 4;
break;
case 5:
attributed_pad = 3;
break;
case 6:
attributed_pad = 3;
break;
case 7:
attributed_pad = 2;
break;
case 8:
attributed_pad = 2;
break;
case 9:
attributed_pad = 1;
break;
}
}
if (n > 2) { /* Pn3 */
if (param[2] == 0) {
param[2] = 10;
}
attributed_pan = attributed_pan * param[2] / 10;
attributed_pad = attributed_pad * param[2] / 10;
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
}
}
} else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) {
break;
} else if (*p == '"') {
/* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
p = get_params(++p, param, &n);
if (n > 0) attributed_pad = param[0];
if (n > 1) attributed_pan = param[1];
if (n > 2 && param[2] > 0) attributed_ph = param[2];
if (n > 3 && param[3] > 0) attributed_pv = param[3];
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
if (imsx < attributed_ph || imsy < attributed_pv) {
dmsx = imsx > attributed_ph ? imsx : attributed_ph;
dmsy = imsy > attributed_pv ? imsy : attributed_pv;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
} else if (*p == '!') {
/* DECGRI Graphics Repeat Introducer ! Pn Ch */
p = get_params(++p, param, &n);
if (n > 0) {
repeat_count = param[0];
}
} else if (*p == '#') {
/* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
p = get_params(++p, param, &n);
if (n > 0) {
if ((color_index = param[0]) < 0) {
color_index = 0;
} else if (color_index >= SIXEL_PALETTE_MAX) {
color_index = SIXEL_PALETTE_MAX - 1;
}
}
if (n > 4) {
if (param[1] == 1) { /* HLS */
if (param[2] > 360) param[2] = 360;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]);
} else if (param[1] == 2) { /* RGB */
if (param[2] > 100) param[2] = 100;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]);
}
}
} else if (*p == '$') {
/* DECGCR Graphics Carriage Return */
p++;
posision_x = 0;
repeat_count = 1;
} else if (*p == '-') {
/* DECGNL Graphics Next Line */
p++;
posision_x = 0;
posision_y += 6;
repeat_count = 1;
} else if (*p >= '?' && *p <= '\177') {
if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) {
int nx = imsx * 2;
int ny = imsy * 2;
while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) {
nx *= 2;
ny *= 2;
}
dmsx = nx;
dmsy = ny;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
if (color_index > max_color_index) {
max_color_index = color_index;
}
if ((b = *(p++) - '?') == 0) {
posision_x += repeat_count;
} else {
sixel_vertical_mask = 0x01;
if (repeat_count <= 1) {
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
imbuf[imsx * (posision_y + i) + posision_x] = color_index;
if (max_x < posision_x) {
max_x = posision_x;
}
if (max_y < (posision_y + i)) {
max_y = posision_y + i;
}
}
sixel_vertical_mask <<= 1;
}
posision_x += 1;
} else { /* repeat_count > 1 */
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
c = sixel_vertical_mask << 1;
for (n = 1; (i + n) < 6; n++) {
if ((b & c) == 0) {
break;
}
c <<= 1;
}
for (y = posision_y + i; y < posision_y + i + n; ++y) {
(void) ResetMagickMemory(imbuf + imsx * y + posision_x, color_index, repeat_count);
}
if (max_x < (posision_x + repeat_count - 1)) {
max_x = posision_x + repeat_count - 1;
}
if (max_y < (posision_y + i + n - 1)) {
max_y = posision_y + i + n - 1;
}
i += (n - 1);
sixel_vertical_mask <<= (n - 1);
}
sixel_vertical_mask <<= 1;
}
posision_x += repeat_count;
}
}
repeat_count = 1;
} else {
p++;
}
}
if (++max_x < attributed_ph) {
max_x = attributed_ph;
}
if (++max_y < attributed_pv) {
max_y = attributed_pv;
}
if (imsx > max_x || imsy > max_y) {
dmsx = max_x;
dmsy = max_y;
if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1)) == NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
for (y = 0; y < dmsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
*pixels = imbuf;
*pwidth = imsx;
*pheight = imsy;
*ncolors = max_color_index + 1;
*palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4);
for (n = 0; n < (ssize_t) *ncolors; ++n) {
(*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff;
(*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff;
(*palette)[n * 4 + 2] = sixel_palet[n] & 0xff;
(*palette)[n * 4 + 3] = 0xff;
}
return(MagickTrue);
}
Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)
CWE ID: CWE-119 | MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */
unsigned char /* out */ **pixels, /* decoded pixels */
size_t /* out */ *pwidth, /* image width */
size_t /* out */ *pheight, /* image height */
unsigned char /* out */ **palette, /* ARGB palette */
size_t /* out */ *ncolors /* palette size (<= 256) */)
{
int n, i, r, g, b, sixel_vertical_mask, c;
int posision_x, posision_y;
int max_x, max_y;
int attributed_pan, attributed_pad;
int attributed_ph, attributed_pv;
int repeat_count, color_index, max_color_index = 2, background_color_index;
int param[10];
int sixel_palet[SIXEL_PALETTE_MAX];
unsigned char *imbuf, *dmbuf;
int imsx, imsy;
int dmsx, dmsy;
int y;
posision_x = posision_y = 0;
max_x = max_y = 0;
attributed_pan = 2;
attributed_pad = 1;
attributed_ph = attributed_pv = 0;
repeat_count = 1;
color_index = 0;
background_color_index = 0;
imsx = 2048;
imsy = 2048;
imbuf = (unsigned char *) AcquireQuantumMemory(imsx , imsy);
if (imbuf == NULL) {
return(MagickFalse);
}
for (n = 0; n < 16; n++) {
sixel_palet[n] = sixel_default_color_table[n];
}
/* colors 16-231 are a 6x6x6 color cube */
for (r = 0; r < 6; r++) {
for (g = 0; g < 6; g++) {
for (b = 0; b < 6; b++) {
sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51);
}
}
}
/* colors 232-255 are a grayscale ramp, intentionally leaving out */
for (i = 0; i < 24; i++) {
sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11);
}
for (; n < SIXEL_PALETTE_MAX; n++) {
sixel_palet[n] = SIXEL_RGB(255, 255, 255);
}
(void) ResetMagickMemory(imbuf, background_color_index, (size_t) imsx * imsy);
while (*p != '\0') {
if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) {
if (*p == '\033') {
p++;
}
p = get_params(++p, param, &n);
if (*p == 'q') {
p++;
if (n > 0) { /* Pn1 */
switch(param[0]) {
case 0:
case 1:
attributed_pad = 2;
break;
case 2:
attributed_pad = 5;
break;
case 3:
attributed_pad = 4;
break;
case 4:
attributed_pad = 4;
break;
case 5:
attributed_pad = 3;
break;
case 6:
attributed_pad = 3;
break;
case 7:
attributed_pad = 2;
break;
case 8:
attributed_pad = 2;
break;
case 9:
attributed_pad = 1;
break;
}
}
if (n > 2) { /* Pn3 */
if (param[2] == 0) {
param[2] = 10;
}
attributed_pan = attributed_pan * param[2] / 10;
attributed_pad = attributed_pad * param[2] / 10;
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
}
}
} else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) {
break;
} else if (*p == '"') {
/* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
p = get_params(++p, param, &n);
if (n > 0) attributed_pad = param[0];
if (n > 1) attributed_pan = param[1];
if (n > 2 && param[2] > 0) attributed_ph = param[2];
if (n > 3 && param[3] > 0) attributed_pv = param[3];
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
if (imsx < attributed_ph || imsy < attributed_pv) {
dmsx = imsx > attributed_ph ? imsx : attributed_ph;
dmsy = imsy > attributed_pv ? imsy : attributed_pv;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
} else if (*p == '!') {
/* DECGRI Graphics Repeat Introducer ! Pn Ch */
p = get_params(++p, param, &n);
if (n > 0) {
repeat_count = param[0];
}
} else if (*p == '#') {
/* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
p = get_params(++p, param, &n);
if (n > 0) {
if ((color_index = param[0]) < 0) {
color_index = 0;
} else if (color_index >= SIXEL_PALETTE_MAX) {
color_index = SIXEL_PALETTE_MAX - 1;
}
}
if (n > 4) {
if (param[1] == 1) { /* HLS */
if (param[2] > 360) param[2] = 360;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]);
} else if (param[1] == 2) { /* RGB */
if (param[2] > 100) param[2] = 100;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]);
}
}
} else if (*p == '$') {
/* DECGCR Graphics Carriage Return */
p++;
posision_x = 0;
repeat_count = 1;
} else if (*p == '-') {
/* DECGNL Graphics Next Line */
p++;
posision_x = 0;
posision_y += 6;
repeat_count = 1;
} else if (*p >= '?' && *p <= '\177') {
if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) {
int nx = imsx * 2;
int ny = imsy * 2;
while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) {
nx *= 2;
ny *= 2;
}
dmsx = nx;
dmsy = ny;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
if (color_index > max_color_index) {
max_color_index = color_index;
}
if ((b = *(p++) - '?') == 0) {
posision_x += repeat_count;
} else {
sixel_vertical_mask = 0x01;
if (repeat_count <= 1) {
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
imbuf[imsx * (posision_y + i) + posision_x] = color_index;
if (max_x < posision_x) {
max_x = posision_x;
}
if (max_y < (posision_y + i)) {
max_y = posision_y + i;
}
}
sixel_vertical_mask <<= 1;
}
posision_x += 1;
} else { /* repeat_count > 1 */
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
c = sixel_vertical_mask << 1;
for (n = 1; (i + n) < 6; n++) {
if ((b & c) == 0) {
break;
}
c <<= 1;
}
for (y = posision_y + i; y < posision_y + i + n; ++y) {
(void) ResetMagickMemory(imbuf + (size_t) imsx * y + posision_x, color_index, repeat_count);
}
if (max_x < (posision_x + repeat_count - 1)) {
max_x = posision_x + repeat_count - 1;
}
if (max_y < (posision_y + i + n - 1)) {
max_y = posision_y + i + n - 1;
}
i += (n - 1);
sixel_vertical_mask <<= (n - 1);
}
sixel_vertical_mask <<= 1;
}
posision_x += repeat_count;
}
}
repeat_count = 1;
} else {
p++;
}
}
if (++max_x < attributed_ph) {
max_x = attributed_ph;
}
if (++max_y < attributed_pv) {
max_y = attributed_pv;
}
if (imsx > max_x || imsy > max_y) {
dmsx = max_x;
dmsy = max_y;
if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy)) == NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
for (y = 0; y < dmsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
*pixels = imbuf;
*pwidth = imsx;
*pheight = imsy;
*ncolors = max_color_index + 1;
*palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4);
for (n = 0; n < (ssize_t) *ncolors; ++n) {
(*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff;
(*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff;
(*palette)[n * 4 + 2] = sixel_palet[n] & 0xff;
(*palette)[n * 4 + 3] = 0xff;
}
return(MagickTrue);
}
| 168,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Mapping several Indic characters to confusables.
A number of characters from several Indian scripts are confusable,
especially with numbers. This change maps these characters to their
ASCII lookalike to allow fallback to punycode when displaying probable
spoofing URLs.
Bug: 849421
Bug: 892646
Bug: 896722
Change-Id: I6d463642f3541454dc39bf4b32b8291417697c52
Reviewed-on: https://chromium-review.googlesource.com/c/1295179
Reviewed-by: Tommy Li <[email protected]>
Commit-Queue: Joe DeBlasio <[email protected]>
Cr-Commit-Position: refs/heads/master@{#602032}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0966 (०), U+09E6 (০), U+0A66 (੦), U+0AE6 (૦), U+0B30 (ଠ),
// U+0B66 (୦), U+0CE6 (೦)} => o,
// - {U+09ED (৭), U+0A67 (੧), U+0AE7 (૧)} => q,
// - {U+0E1A (บ), U+0E9A (ບ)} => u
// - {U+0968 (२), U+09E8 (২), U+0A68 (੨), U+0A68 (੨), U+0AE8 (૨),
// U+0ce9 (೩), U+0ced (೭)} => 2,
// U+0A69 (੩), U+0AE9 (૩), U+0C69 (౩),
// - {U+0A6B (੫)} => 4,
// - {U+09EA (৪), U+0A6A (੪), U+0b6b (୫)} => 8,
// - {U+0AED (૭), U+0b68 (୨), U+0C68 (౨)} => 9,
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[०০੦૦ଠ୦೦] > o;"
"[৭੧૧] > q;"
"[บບ] > u;"
"[२২੨੨૨೩೭] > 2;"
"[зҙӡउও੩૩౩ဒვპ] > 3;"
"[੫] > 4;"
"[৪੪୫] > 8;"
"[૭୨౨] > 9;"
),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,115 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
Commit Message: compose: fix infinite loop in parser on some inputs
The parser would enter an infinite loop if an unterminated keysym
literal occurs at EOF.
Found with the afl fuzzer.
Signed-off-by: Ran Benita <[email protected]>
CWE ID: CWE-835 | lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s) && !eof(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
| 169,094 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
/*
* This union makes it completely explicit to gcc-3.x
* that these two variables' stack usage should be
* combined, not added together.
*/
union {
struct kvm_pit_state ps;
struct kvm_pit_state2 ps2;
struct kvm_pit_config pit_config;
} u;
switch (ioctl) {
case KVM_SET_TSS_ADDR:
r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
if (r < 0)
goto out;
break;
case KVM_SET_IDENTITY_MAP_ADDR: {
u64 ident_addr;
r = -EFAULT;
if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
goto out;
r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
if (r < 0)
goto out;
break;
}
case KVM_SET_NR_MMU_PAGES:
r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
if (r)
goto out;
break;
case KVM_GET_NR_MMU_PAGES:
r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
break;
case KVM_CREATE_IRQCHIP: {
struct kvm_pic *vpic;
mutex_lock(&kvm->lock);
r = -EEXIST;
if (kvm->arch.vpic)
goto create_irqchip_unlock;
r = -ENOMEM;
vpic = kvm_create_pic(kvm);
if (vpic) {
r = kvm_ioapic_init(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_master);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_slave);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_eclr);
mutex_unlock(&kvm->slots_lock);
kfree(vpic);
goto create_irqchip_unlock;
}
} else
goto create_irqchip_unlock;
smp_wmb();
kvm->arch.vpic = vpic;
smp_wmb();
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
mutex_lock(&kvm->irq_lock);
kvm_ioapic_destroy(kvm);
kvm_destroy_pic(kvm);
mutex_unlock(&kvm->irq_lock);
mutex_unlock(&kvm->slots_lock);
}
create_irqchip_unlock:
mutex_unlock(&kvm->lock);
break;
}
case KVM_CREATE_PIT:
u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
goto create_pit;
case KVM_CREATE_PIT2:
r = -EFAULT;
if (copy_from_user(&u.pit_config, argp,
sizeof(struct kvm_pit_config)))
goto out;
create_pit:
mutex_lock(&kvm->slots_lock);
r = -EEXIST;
if (kvm->arch.vpit)
goto create_pit_unlock;
r = -ENOMEM;
kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
if (kvm->arch.vpit)
r = 0;
create_pit_unlock:
mutex_unlock(&kvm->slots_lock);
break;
case KVM_IRQ_LINE_STATUS:
case KVM_IRQ_LINE: {
struct kvm_irq_level irq_event;
r = -EFAULT;
if (copy_from_user(&irq_event, argp, sizeof irq_event))
goto out;
r = -ENXIO;
if (irqchip_in_kernel(kvm)) {
__s32 status;
status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event.irq, irq_event.level);
if (ioctl == KVM_IRQ_LINE_STATUS) {
r = -EFAULT;
irq_event.status = status;
if (copy_to_user(argp, &irq_event,
sizeof irq_event))
goto out;
}
r = 0;
}
break;
}
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto get_irqchip_out;
r = kvm_vm_ioctl_get_irqchip(kvm, chip);
if (r)
goto get_irqchip_out;
r = -EFAULT;
if (copy_to_user(argp, chip, sizeof *chip))
goto get_irqchip_out;
r = 0;
get_irqchip_out:
kfree(chip);
if (r)
goto out;
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto set_irqchip_out;
r = kvm_vm_ioctl_set_irqchip(kvm, chip);
if (r)
goto set_irqchip_out;
r = 0;
set_irqchip_out:
kfree(chip);
if (r)
goto out;
break;
}
case KVM_GET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof u.ps))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
if (r)
goto out;
r = 0;
break;
}
case KVM_GET_PIT2: {
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT2: {
r = -EFAULT;
if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
if (r)
goto out;
r = 0;
break;
}
case KVM_REINJECT_CONTROL: {
struct kvm_reinject_control control;
r = -EFAULT;
if (copy_from_user(&control, argp, sizeof(control)))
goto out;
r = kvm_vm_ioctl_reinject(kvm, &control);
if (r)
goto out;
r = 0;
break;
}
case KVM_XEN_HVM_CONFIG: {
r = -EFAULT;
if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
sizeof(struct kvm_xen_hvm_config)))
goto out;
r = -EINVAL;
if (kvm->arch.xen_hvm_config.flags)
goto out;
r = 0;
break;
}
case KVM_SET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
s64 delta;
r = -EFAULT;
if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
goto out;
r = -EINVAL;
if (user_ns.flags)
goto out;
r = 0;
local_irq_disable();
now_ns = get_kernel_ns();
delta = user_ns.clock - now_ns;
local_irq_enable();
kvm->arch.kvmclock_offset = delta;
break;
}
case KVM_GET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
local_irq_disable();
now_ns = get_kernel_ns();
user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
local_irq_enable();
user_ns.flags = 0;
memset(&user_ns.pad, 0, sizeof(user_ns.pad));
r = -EFAULT;
if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399 | long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
/*
* This union makes it completely explicit to gcc-3.x
* that these two variables' stack usage should be
* combined, not added together.
*/
union {
struct kvm_pit_state ps;
struct kvm_pit_state2 ps2;
struct kvm_pit_config pit_config;
} u;
switch (ioctl) {
case KVM_SET_TSS_ADDR:
r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
if (r < 0)
goto out;
break;
case KVM_SET_IDENTITY_MAP_ADDR: {
u64 ident_addr;
r = -EFAULT;
if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
goto out;
r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
if (r < 0)
goto out;
break;
}
case KVM_SET_NR_MMU_PAGES:
r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
if (r)
goto out;
break;
case KVM_GET_NR_MMU_PAGES:
r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
break;
case KVM_CREATE_IRQCHIP: {
struct kvm_pic *vpic;
mutex_lock(&kvm->lock);
r = -EEXIST;
if (kvm->arch.vpic)
goto create_irqchip_unlock;
r = -EINVAL;
if (atomic_read(&kvm->online_vcpus))
goto create_irqchip_unlock;
r = -ENOMEM;
vpic = kvm_create_pic(kvm);
if (vpic) {
r = kvm_ioapic_init(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_master);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_slave);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_eclr);
mutex_unlock(&kvm->slots_lock);
kfree(vpic);
goto create_irqchip_unlock;
}
} else
goto create_irqchip_unlock;
smp_wmb();
kvm->arch.vpic = vpic;
smp_wmb();
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
mutex_lock(&kvm->irq_lock);
kvm_ioapic_destroy(kvm);
kvm_destroy_pic(kvm);
mutex_unlock(&kvm->irq_lock);
mutex_unlock(&kvm->slots_lock);
}
create_irqchip_unlock:
mutex_unlock(&kvm->lock);
break;
}
case KVM_CREATE_PIT:
u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
goto create_pit;
case KVM_CREATE_PIT2:
r = -EFAULT;
if (copy_from_user(&u.pit_config, argp,
sizeof(struct kvm_pit_config)))
goto out;
create_pit:
mutex_lock(&kvm->slots_lock);
r = -EEXIST;
if (kvm->arch.vpit)
goto create_pit_unlock;
r = -ENOMEM;
kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
if (kvm->arch.vpit)
r = 0;
create_pit_unlock:
mutex_unlock(&kvm->slots_lock);
break;
case KVM_IRQ_LINE_STATUS:
case KVM_IRQ_LINE: {
struct kvm_irq_level irq_event;
r = -EFAULT;
if (copy_from_user(&irq_event, argp, sizeof irq_event))
goto out;
r = -ENXIO;
if (irqchip_in_kernel(kvm)) {
__s32 status;
status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event.irq, irq_event.level);
if (ioctl == KVM_IRQ_LINE_STATUS) {
r = -EFAULT;
irq_event.status = status;
if (copy_to_user(argp, &irq_event,
sizeof irq_event))
goto out;
}
r = 0;
}
break;
}
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto get_irqchip_out;
r = kvm_vm_ioctl_get_irqchip(kvm, chip);
if (r)
goto get_irqchip_out;
r = -EFAULT;
if (copy_to_user(argp, chip, sizeof *chip))
goto get_irqchip_out;
r = 0;
get_irqchip_out:
kfree(chip);
if (r)
goto out;
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto set_irqchip_out;
r = kvm_vm_ioctl_set_irqchip(kvm, chip);
if (r)
goto set_irqchip_out;
r = 0;
set_irqchip_out:
kfree(chip);
if (r)
goto out;
break;
}
case KVM_GET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof u.ps))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
if (r)
goto out;
r = 0;
break;
}
case KVM_GET_PIT2: {
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT2: {
r = -EFAULT;
if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
if (r)
goto out;
r = 0;
break;
}
case KVM_REINJECT_CONTROL: {
struct kvm_reinject_control control;
r = -EFAULT;
if (copy_from_user(&control, argp, sizeof(control)))
goto out;
r = kvm_vm_ioctl_reinject(kvm, &control);
if (r)
goto out;
r = 0;
break;
}
case KVM_XEN_HVM_CONFIG: {
r = -EFAULT;
if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
sizeof(struct kvm_xen_hvm_config)))
goto out;
r = -EINVAL;
if (kvm->arch.xen_hvm_config.flags)
goto out;
r = 0;
break;
}
case KVM_SET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
s64 delta;
r = -EFAULT;
if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
goto out;
r = -EINVAL;
if (user_ns.flags)
goto out;
r = 0;
local_irq_disable();
now_ns = get_kernel_ns();
delta = user_ns.clock - now_ns;
local_irq_enable();
kvm->arch.kvmclock_offset = delta;
break;
}
case KVM_GET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
local_irq_disable();
now_ns = get_kernel_ns();
user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
local_irq_enable();
user_ns.flags = 0;
memset(&user_ns.pad, 0, sizeof(user_ns.pad));
r = -EFAULT;
if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
| 165,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot)
{
gfn_t gfn, end_gfn;
pfn_t pfn;
int r = 0;
struct iommu_domain *domain = kvm->arch.iommu_domain;
int flags;
/* check if iommu exists and in use */
if (!domain)
return 0;
gfn = slot->base_gfn;
end_gfn = gfn + slot->npages;
flags = IOMMU_READ;
if (!(slot->flags & KVM_MEM_READONLY))
flags |= IOMMU_WRITE;
if (!kvm->arch.iommu_noncoherent)
flags |= IOMMU_CACHE;
while (gfn < end_gfn) {
unsigned long page_size;
/* Check if already mapped */
if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) {
gfn += 1;
continue;
}
/* Get the page size we could use to map */
page_size = kvm_host_page_size(kvm, gfn);
/* Make sure the page_size does not exceed the memslot */
while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn)
page_size >>= 1;
/* Make sure gfn is aligned to the page size we want to map */
while ((gfn << PAGE_SHIFT) & (page_size - 1))
page_size >>= 1;
/* Make sure hva is aligned to the page size we want to map */
while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1))
page_size >>= 1;
/*
* Pin all pages we are about to map in memory. This is
* important because we unmap and unpin in 4kb steps later.
*/
pfn = kvm_pin_pages(slot, gfn, page_size);
if (is_error_noslot_pfn(pfn)) {
gfn += 1;
continue;
}
/* Map into IO address space */
r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn),
page_size, flags);
if (r) {
printk(KERN_ERR "kvm_iommu_map_address:"
"iommu failed to map pfn=%llx\n", pfn);
kvm_unpin_pages(kvm, pfn, page_size);
goto unmap_pages;
}
gfn += page_size >> PAGE_SHIFT;
}
return 0;
unmap_pages:
kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn);
return r;
}
Commit Message: kvm: fix excessive pages un-pinning in kvm_iommu_map error path.
The third parameter of kvm_unpin_pages() when called from
kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin
and not the page size.
This error was facilitated with an inconsistent API: kvm_pin_pages() takes
a size, but kvn_unpin_pages() takes a number of pages, so fix the problem
by matching the two.
This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter
of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of
un-pinning for pages intended to be un-pinned (i.e. memory leak) but
unfortunately potentially aggravated the number of pages we un-pin that
should have stayed pinned. As far as I understand though, the same
practical mitigations apply.
This issue was found during review of Red Hat 6.6 patches to prepare
Ksplice rebootless updates.
Thanks to Vegard for his time on a late Friday evening to help me in
understanding this code.
Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)")
Cc: [email protected]
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Signed-off-by: Jamie Iles <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189 | int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot)
{
gfn_t gfn, end_gfn;
pfn_t pfn;
int r = 0;
struct iommu_domain *domain = kvm->arch.iommu_domain;
int flags;
/* check if iommu exists and in use */
if (!domain)
return 0;
gfn = slot->base_gfn;
end_gfn = gfn + slot->npages;
flags = IOMMU_READ;
if (!(slot->flags & KVM_MEM_READONLY))
flags |= IOMMU_WRITE;
if (!kvm->arch.iommu_noncoherent)
flags |= IOMMU_CACHE;
while (gfn < end_gfn) {
unsigned long page_size;
/* Check if already mapped */
if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) {
gfn += 1;
continue;
}
/* Get the page size we could use to map */
page_size = kvm_host_page_size(kvm, gfn);
/* Make sure the page_size does not exceed the memslot */
while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn)
page_size >>= 1;
/* Make sure gfn is aligned to the page size we want to map */
while ((gfn << PAGE_SHIFT) & (page_size - 1))
page_size >>= 1;
/* Make sure hva is aligned to the page size we want to map */
while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1))
page_size >>= 1;
/*
* Pin all pages we are about to map in memory. This is
* important because we unmap and unpin in 4kb steps later.
*/
pfn = kvm_pin_pages(slot, gfn, page_size >> PAGE_SHIFT);
if (is_error_noslot_pfn(pfn)) {
gfn += 1;
continue;
}
/* Map into IO address space */
r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn),
page_size, flags);
if (r) {
printk(KERN_ERR "kvm_iommu_map_address:"
"iommu failed to map pfn=%llx\n", pfn);
kvm_unpin_pages(kvm, pfn, page_size >> PAGE_SHIFT);
goto unmap_pages;
}
gfn += page_size >> PAGE_SHIFT;
}
return 0;
unmap_pages:
kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn);
return r;
}
| 166,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
}
Commit Message: tipc: fix info leaks via msg_name in recv_msg/recv_stream
The code in set_orig_addr() does not initialize all of the members of
struct sockaddr_tipc when filling the sockaddr info -- namely the union
is only partly filled. This will make recv_msg() and recv_stream() --
the only users of this function -- leak kernel stack memory as the
msg_name member is a local variable in net/socket.c.
Additionally to that both recv_msg() and recv_stream() fail to update
the msg_namelen member to 0 while otherwise returning with 0, i.e.
"success". This is the case for, e.g., non-blocking sockets. This will
lead to a 128 byte kernel stack leak in net/socket.c.
Fix the first issue by initializing the memory of the union with
memset(0). Fix the second one by setting msg_namelen to 0 early as it
will be updated later if we're going to fill the msg_name member.
Cc: Jon Maloy <[email protected]>
Cc: Allan Stephens <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int recv_msg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
u32 err;
int res;
/* Catch invalid receive requests */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely(sock->state == SS_UNCONNECTED)) {
res = -ENOTCONN;
goto exit;
}
/* will be updated in set_orig_addr() if needed */
m->msg_namelen = 0;
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Capture sender's address (optional) */
set_orig_addr(m, msg);
/* Capture ancillary data (optional) */
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
if (unlikely(buf_len < sz)) {
sz = buf_len;
m->msg_flags |= MSG_TRUNC;
}
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
m->msg_iov, sz);
if (res)
goto exit;
res = sz;
} else {
if ((sock->state == SS_READY) ||
((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if ((sock->state != SS_READY) &&
(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
exit:
release_sock(sk);
return res;
}
| 166,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: static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
{
path->incReserve(numPoints);
path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
WebCoreFloatToSkScalar(points[0].y()));
for (size_t i = 1; i < numPoints; ++i) {
path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
WebCoreFloatToSkScalar(points[i].y()));
}
path->setIsConvex(true);
}
Commit Message: [skia] not all convex paths are convex, so recompute convexity for the problematic ones
https://bugs.webkit.org/show_bug.cgi?id=75960
Reviewed by Stephen White.
No new tests.
See related chrome issue
http://code.google.com/p/chromium/issues/detail?id=108605
* platform/graphics/skia/GraphicsContextSkia.cpp:
(WebCore::setPathFromConvexPoints):
git-svn-id: svn://svn.chromium.org/blink/trunk@104609 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-19 | static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
{
path->incReserve(numPoints);
path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
WebCoreFloatToSkScalar(points[0].y()));
for (size_t i = 1; i < numPoints; ++i) {
path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
WebCoreFloatToSkScalar(points[i].y()));
}
/* The code used to just blindly call this
path->setIsConvex(true);
But webkit can sometimes send us non-convex 4-point values, so we mark the path's
convexity as unknown, so it will get computed by skia at draw time.
See crbug.com 108605
*/
SkPath::Convexity convexity = SkPath::kConvex_Convexity;
if (numPoints == 4)
convexity = SkPath::kUnknown_Convexity;
path->setConvexity(convexity);
}
| 170,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ptrace_triggered(struct perf_event *bp, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
int i;
struct thread_struct *thread = &(current->thread);
/*
* Store in the virtual DR6 register the fact that the breakpoint
* was hit so the thread's debugger will see it.
*/
for (i = 0; i < HBP_NUM; i++) {
if (thread->ptrace_bps[i] == bp)
break;
}
thread->debugreg6 |= (DR_TRAP0 << i);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void ptrace_triggered(struct perf_event *bp, int nmi,
static void ptrace_triggered(struct perf_event *bp,
struct perf_sample_data *data,
struct pt_regs *regs)
{
int i;
struct thread_struct *thread = &(current->thread);
/*
* Store in the virtual DR6 register the fact that the breakpoint
* was hit so the thread's debugger will see it.
*/
for (i = 0; i < HBP_NUM; i++) {
if (thread->ptrace_bps[i] == bp)
break;
}
thread->debugreg6 |= (DR_TRAP0 << i);
}
| 165,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: static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, as hardware has verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: [email protected]
Signed-off-by: Felix Wilhelm <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, nested_vmx_check_permission has verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
| 169,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
unsigned char
attributes,
tag[3];
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_per_pixel,
num_pad_bytes,
one,
packets;
ssize_t
count,
img_offset,
comment_offset = 0,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PDB image file.
*/
count=ReadBlob(image,32,(unsigned char *) pdb_info.name);
pdb_info.attributes=(short) ReadBlobMSBShort(image);
pdb_info.version=(short) ReadBlobMSBShort(image);
pdb_info.create_time=ReadBlobMSBLong(image);
pdb_info.modify_time=ReadBlobMSBLong(image);
pdb_info.archive_time=ReadBlobMSBLong(image);
pdb_info.modify_number=ReadBlobMSBLong(image);
pdb_info.application_info=ReadBlobMSBLong(image);
pdb_info.sort_info=ReadBlobMSBLong(image);
count=ReadBlob(image,4,(unsigned char *) pdb_info.type);
count=ReadBlob(image,4,(unsigned char *) pdb_info.id);
if ((count == 0) || (memcmp(pdb_info.type,"vIMG",4) != 0) ||
(memcmp(pdb_info.id,"View",4) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_info.seed=ReadBlobMSBLong(image);
pdb_info.next_record=ReadBlobMSBLong(image);
pdb_info.number_records=(short) ReadBlobMSBShort(image);
if (pdb_info.next_record != 0)
ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
/*
Read record header.
*/
img_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
(void) attributes;
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
if (pdb_info.number_records > 1)
{
comment_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read image header.
*/
count=ReadBlob(image,32,(unsigned char *) pdb_image.name);
pdb_image.version=ReadBlobByte(image);
pdb_image.type=(unsigned char) ReadBlobByte(image);
pdb_image.reserved_1=ReadBlobMSBLong(image);
pdb_image.note=ReadBlobMSBLong(image);
pdb_image.x_last=(short) ReadBlobMSBShort(image);
pdb_image.y_last=(short) ReadBlobMSBShort(image);
pdb_image.reserved_2=ReadBlobMSBLong(image);
pdb_image.x_anchor=ReadBlobMSBShort(image);
pdb_image.y_anchor=ReadBlobMSBShort(image);
pdb_image.width=(short) ReadBlobMSBShort(image);
pdb_image.height=(short) ReadBlobMSBShort(image);
/*
Initialize image structure.
*/
image->columns=(size_t) pdb_image.width;
image->rows=(size_t) pdb_image.height;
image->depth=8;
image->storage_class=PseudoClass;
bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
one=1;
if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
packets=(bits_per_pixel*image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
switch (pdb_image.version & 0x07)
{
case 0:
{
image->compression=NoCompression;
count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
break;
}
case 1:
{
image->compression=RLECompression;
if (!DecodeImage(image, pixels, packets * image -> rows))
ThrowReaderException( CorruptImageError, "RLEDecoderError" );
break;
}
default:
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompressionType" );
}
p=pixels;
switch (bits_per_pixel)
{
case 1:
{
int
bit;
/*
Read 1-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 2:
{
/*
Read 2-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x+=4)
{
index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
SetPixelIndex(indexes+x+1,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
SetPixelIndex(indexes+x+2,index);
index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
SetPixelIndex(indexes+x+3,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Read 4-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x+=2)
{
index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
SetPixelIndex(indexes+x+1,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (pdb_info.number_records > 1)
{
char
*comment;
int
c;
register char
*p;
size_t
length;
num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read comment.
*/
c=ReadBlobByte(image);
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; c != EOF; p++)
{
if ((size_t) (p-comment+MaxTextExtent) >= length)
{
*p='\0';
length<<=1;
length+=MaxTextExtent;
comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=c;
c=ReadBlobByte(image);
}
*p='\0';
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
unsigned char
attributes,
tag[3];
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_per_pixel,
num_pad_bytes,
one,
packets;
ssize_t
count,
img_offset,
comment_offset = 0,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PDB image file.
*/
count=ReadBlob(image,32,(unsigned char *) pdb_info.name);
pdb_info.attributes=(short) ReadBlobMSBShort(image);
pdb_info.version=(short) ReadBlobMSBShort(image);
pdb_info.create_time=ReadBlobMSBLong(image);
pdb_info.modify_time=ReadBlobMSBLong(image);
pdb_info.archive_time=ReadBlobMSBLong(image);
pdb_info.modify_number=ReadBlobMSBLong(image);
pdb_info.application_info=ReadBlobMSBLong(image);
pdb_info.sort_info=ReadBlobMSBLong(image);
count=ReadBlob(image,4,(unsigned char *) pdb_info.type);
count=ReadBlob(image,4,(unsigned char *) pdb_info.id);
if ((count == 0) || (memcmp(pdb_info.type,"vIMG",4) != 0) ||
(memcmp(pdb_info.id,"View",4) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_info.seed=ReadBlobMSBLong(image);
pdb_info.next_record=ReadBlobMSBLong(image);
pdb_info.number_records=(short) ReadBlobMSBShort(image);
if (pdb_info.next_record != 0)
ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
/*
Read record header.
*/
img_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
(void) attributes;
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
if (pdb_info.number_records > 1)
{
comment_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read image header.
*/
count=ReadBlob(image,32,(unsigned char *) pdb_image.name);
pdb_image.version=ReadBlobByte(image);
pdb_image.type=(unsigned char) ReadBlobByte(image);
pdb_image.reserved_1=ReadBlobMSBLong(image);
pdb_image.note=ReadBlobMSBLong(image);
pdb_image.x_last=(short) ReadBlobMSBShort(image);
pdb_image.y_last=(short) ReadBlobMSBShort(image);
pdb_image.reserved_2=ReadBlobMSBLong(image);
pdb_image.x_anchor=ReadBlobMSBShort(image);
pdb_image.y_anchor=ReadBlobMSBShort(image);
pdb_image.width=(short) ReadBlobMSBShort(image);
pdb_image.height=(short) ReadBlobMSBShort(image);
/*
Initialize image structure.
*/
image->columns=(size_t) pdb_image.width;
image->rows=(size_t) pdb_image.height;
image->depth=8;
image->storage_class=PseudoClass;
bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
one=1;
if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
packets=(bits_per_pixel*image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
switch (pdb_image.version & 0x07)
{
case 0:
{
image->compression=NoCompression;
count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
break;
}
case 1:
{
image->compression=RLECompression;
if (!DecodeImage(image, pixels, packets * image -> rows))
ThrowReaderException( CorruptImageError, "RLEDecoderError" );
break;
}
default:
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompressionType" );
}
p=pixels;
switch (bits_per_pixel)
{
case 1:
{
int
bit;
/*
Read 1-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 2:
{
/*
Read 2-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x+=4)
{
index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
SetPixelIndex(indexes+x+1,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
SetPixelIndex(indexes+x+2,index);
index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
SetPixelIndex(indexes+x+3,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Read 4-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x+=2)
{
index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
SetPixelIndex(indexes+x+1,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (pdb_info.number_records > 1)
{
char
*comment;
int
c;
register char
*p;
size_t
length;
num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read comment.
*/
c=ReadBlobByte(image);
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; c != EOF; p++)
{
if ((size_t) (p-comment+MaxTextExtent) >= length)
{
*p='\0';
length<<=1;
length+=MaxTextExtent;
comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=c;
c=ReadBlobByte(image);
}
*p='\0';
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_islice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ih264d_init_cabac_contexts(I_SLICE, ps_dec);
ps_dec->i1_prev_mb_qp_delta = 0;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD16 u2_mbx;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
{
UWORD8 u1_mb_type;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
u2_mbx = ps_dec->u2_mbx;
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(
ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type
| D_INTRA_MB;
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_intra_cabac(0, ps_dec);
if(u1_mb_type > 25)
return ERROR_MB_TYPE;
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/* Parse Macroblock Data */
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cabac(ps_dec, ps_cur_mb_info, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(
ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1),
4, 4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
}
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Decoder Update mb count after mb map is set.
Bug: 25928803
Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37
CWE ID: CWE-119 | WORD32 ih264d_parse_islice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ih264d_init_cabac_contexts(I_SLICE, ps_dec);
ps_dec->i1_prev_mb_qp_delta = 0;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD16 u2_mbx;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
{
UWORD8 u1_mb_type;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
u2_mbx = ps_dec->u2_mbx;
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(
ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type
| D_INTRA_MB;
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_intra_cabac(0, ps_dec);
if(u1_mb_type > 25)
return ERROR_MB_TYPE;
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/* Parse Macroblock Data */
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cabac(ps_dec, ps_cur_mb_info, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(
ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1),
4, 4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
}
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 173,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringCase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
| 171,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
X509_ALGOR *sigalg, ASN1_BIT_STRING *sig,
EVP_PKEY *pkey)
{
/* Sanity check: make sure it is PSS */
if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) {
RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
return -1;
}
if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey))
/* Carry on */
return 2;
return -1;
}
Commit Message:
CWE ID: | static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
X509_ALGOR *sigalg, ASN1_BIT_STRING *sig,
EVP_PKEY *pkey)
{
/* Sanity check: make sure it is PSS */
if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) {
RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
return -1;
}
if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) {
/* Carry on */
return 2;
}
return -1;
}
| 164,820 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ppp_unregister_channel(struct ppp_channel *chan)
{
struct channel *pch = chan->ppp;
struct ppp_net *pn;
if (!pch)
return; /* should never happen */
chan->ppp = NULL;
/*
* This ensures that we have returned from any calls into the
* the channel's start_xmit or ioctl routine before we proceed.
*/
down_write(&pch->chan_sem);
spin_lock_bh(&pch->downl);
pch->chan = NULL;
spin_unlock_bh(&pch->downl);
up_write(&pch->chan_sem);
ppp_disconnect_channel(pch);
pn = ppp_pernet(pch->chan_net);
spin_lock_bh(&pn->all_channels_lock);
list_del(&pch->list);
spin_unlock_bh(&pn->all_channels_lock);
pch->file.dead = 1;
wake_up_interruptible(&pch->file.rwait);
if (atomic_dec_and_test(&pch->file.refcnt))
ppp_destroy_channel(pch);
}
Commit Message: ppp: take reference on channels netns
Let channels hold a reference on their network namespace.
Some channel types, like ppp_async and ppp_synctty, can have their
userspace controller running in a different namespace. Therefore they
can't rely on them to preclude their netns from being removed from
under them.
==================================================================
BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at
addr ffff880064e217e0
Read of size 8 by task syz-executor/11581
=============================================================================
BUG net_namespace (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906
[< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440
[< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469
[< inline >] slab_alloc_node kernel/mm/slub.c:2532
[< inline >] slab_alloc kernel/mm/slub.c:2574
[< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579
[< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597
[< inline >] net_alloc kernel/net/core/net_namespace.c:325
[< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360
[< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95
[< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150
[< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451
[< inline >] copy_process kernel/kernel/fork.c:1274
[< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723
[< inline >] SYSC_clone kernel/kernel/fork.c:1832
[< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826
[< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185
INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631
[< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650
[< inline >] slab_free kernel/mm/slub.c:2805
[< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814
[< inline >] net_free kernel/net/core/net_namespace.c:341
[< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348
[< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448
[< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036
[< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170
[< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303
[< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468
INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000
flags=0x5fffc0000004080
INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200
CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014
00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300
ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054
ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000
Call Trace:
[< inline >] __dump_stack kernel/lib/dump_stack.c:15
[<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50
[<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654
[<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661
[< inline >] print_address_description kernel/mm/kasan/report.c:138
[<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236
[< inline >] kasan_report kernel/mm/kasan/report.c:259
[<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280
[< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ppp_pernet kernel/include/linux/compiler.h:218
[<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293
[<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392
[<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241
[<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000
[<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478
[<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744
[<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772
[<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901
[<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688
[<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208
[<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244
[<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115
[< inline >] exit_task_work kernel/include/linux/task_work.h:21
[<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750
[<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123
[<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357
[<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550
[<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145
[<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880
[<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307
[< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113
[<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158
[<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712
[<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655
[<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165
[<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692
[< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099
[<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678
[< inline >] ? context_switch kernel/kernel/sched/core.c:2807
[<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283
[<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247
[< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282
[<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344
[<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281
Memory state around the buggy address:
ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2")
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Guillaume Nault <[email protected]>
Reviewed-by: Cyrill Gorcunov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | ppp_unregister_channel(struct ppp_channel *chan)
{
struct channel *pch = chan->ppp;
struct ppp_net *pn;
if (!pch)
return; /* should never happen */
chan->ppp = NULL;
/*
* This ensures that we have returned from any calls into the
* the channel's start_xmit or ioctl routine before we proceed.
*/
down_write(&pch->chan_sem);
spin_lock_bh(&pch->downl);
pch->chan = NULL;
spin_unlock_bh(&pch->downl);
up_write(&pch->chan_sem);
ppp_disconnect_channel(pch);
pn = ppp_pernet(pch->chan_net);
spin_lock_bh(&pn->all_channels_lock);
list_del(&pch->list);
spin_unlock_bh(&pn->all_channels_lock);
put_net(pch->chan_net);
pch->chan_net = NULL;
pch->file.dead = 1;
wake_up_interruptible(&pch->file.rwait);
if (atomic_dec_and_test(&pch->file.refcnt))
ppp_destroy_channel(pch);
}
| 167,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FaviconWebUIHandler::OnFaviconDataAvailable(
FaviconService::Handle request_handle,
history::FaviconData favicon) {
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
int id = consumer_.GetClientData(favicon_service, request_handle);
if (favicon.is_valid()) {
FundamentalValue id_value(id);
color_utils::GridSampler sampler;
SkColor color =
color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665,
sampler);
std::string css_color = base::StringPrintf("rgb(%d, %d, %d)",
SkColorGetR(color),
SkColorGetG(color),
SkColorGetB(color));
StringValue color_value(css_color);
web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor",
id_value, color_value);
}
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FaviconWebUIHandler::OnFaviconDataAvailable(
FaviconService::Handle request_handle,
history::FaviconData favicon) {
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
int id = consumer_.GetClientData(favicon_service, request_handle);
FundamentalValue id_value(id);
scoped_ptr<StringValue> color_value;
if (favicon.is_valid()) {
color_utils::GridSampler sampler;
SkColor color =
color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665,
sampler);
std::string css_color = base::StringPrintf("rgb(%d, %d, %d)",
SkColorGetR(color),
SkColorGetG(color),
SkColorGetB(color));
color_value.reset(new StringValue(css_color));
} else {
color_value.reset(new StringValue("#919191"));
}
web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor",
id_value, *color_value);
}
| 170,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaStreamManager::CancelAllRequests(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto request_it = requests_.begin();
while (request_it != requests_.end()) {
if (request_it->second->requesting_process_id != render_process_id ||
request_it->second->requesting_frame_id != render_frame_id) {
++request_it;
continue;
}
const std::string label = request_it->first;
++request_it;
CancelRequest(label);
}
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamManager::CancelAllRequests(int render_process_id,
int render_frame_id,
int requester_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto request_it = requests_.begin();
while (request_it != requests_.end()) {
if (request_it->second->requesting_process_id != render_process_id ||
request_it->second->requesting_frame_id != render_frame_id ||
request_it->second->requester_id != requester_id) {
++request_it;
continue;
}
const std::string label = request_it->first;
++request_it;
CancelRequest(label);
}
}
| 173,100 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, private);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
CWE ID: CWE-476 | static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_tfm *tfm = private;
struct crypto_skcipher *skcipher = tfm->skcipher;
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(skcipher);
if (!tfm->has_key)
return -ENOKEY;
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(skcipher),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(skcipher));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, skcipher);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
| 167,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WebGLRenderingContextBase::ValidateHTMLImageElement(
const SecurityOrigin* security_origin,
const char* function_name,
HTMLImageElement* image,
ExceptionState& exception_state) {
if (!image || !image->CachedImage()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image");
return false;
}
const KURL& url = image->CachedImage()->GetResponse().Url();
if (url.IsNull() || url.IsEmpty() || !url.IsValid()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image");
return false;
}
if (WouldTaintOrigin(image, security_origin)) {
exception_state.ThrowSecurityError("The cross-origin image at " +
url.ElidedString() +
" may not be loaded.");
return false;
}
return true;
}
Commit Message: Simplify WebGL error message
The WebGL exception message text contains the full URL of a blocked
cross-origin resource. It should instead contain only a generic notice.
Bug: 799847
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: I3a7f00462a4643c41882f2ee7e7767e6d631557e
Reviewed-on: https://chromium-review.googlesource.com/854986
Reviewed-by: Brandon Jones <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528458}
CWE ID: CWE-20 | bool WebGLRenderingContextBase::ValidateHTMLImageElement(
const SecurityOrigin* security_origin,
const char* function_name,
HTMLImageElement* image,
ExceptionState& exception_state) {
if (!image || !image->CachedImage()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image");
return false;
}
const KURL& url = image->CachedImage()->GetResponse().Url();
if (url.IsNull() || url.IsEmpty() || !url.IsValid()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image");
return false;
}
if (WouldTaintOrigin(image, security_origin)) {
exception_state.ThrowSecurityError(
"The image element contains cross-origin data, and may not be loaded.");
return false;
}
return true;
}
| 172,690 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else 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 assume TLS 1.0 to avoid protocol version downgrade
* attacks. */
if (p[3] == 0 && p[4] < 6)
{
#if 0
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
#else
v[1] = TLS1_VERSION_MINOR;
#endif
}
/* 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....
*/
else if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
else 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 (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else 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;
}
}
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
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
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
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;
}
j=ssl23_read_bytes(s,n+2);
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
/* 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;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
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) */
if (!ssl_init_wbio_buffer(s,1)) goto err;
/* we are in this state */
s->state=SSL3_ST_SR_CLNT_HELLO_A;
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;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
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 (s->version == TLS1_2_VERSION)
s->method = TLSv1_2_server_method();
else if (s->version == TLS1_1_VERSION)
s->method = TLSv1_1_server_method();
else if (s->version == TLS1_VERSION)
s->method = TLSv1_server_method();
else
s->method = SSLv3_server_method();
#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 (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else 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 */
else 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 (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else 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;
}
}
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
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
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
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);
/* 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;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
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) */
if (!ssl_init_wbio_buffer(s,1)) goto err;
/* we are in this state */
s->state=SSL3_ST_SR_CLNT_HELLO_A;
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;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
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 (s->version == TLS1_2_VERSION)
s->method = TLSv1_2_server_method();
else if (s->version == TLS1_1_VERSION)
s->method = TLSv1_1_server_method();
else if (s->version == TLS1_VERSION)
s->method = TLSv1_server_method();
else
s->method = SSLv3_server_method();
#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,174 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks.
For configuration protocol options, use ND_TCHECK() and
ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument.
This fixes one case where the ND_TCHECK2() call they replace was not
checking enough bytes.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
| 167,860 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 sas_deform_port(struct asd_sas_phy *phy, int gone)
{
struct sas_ha_struct *sas_ha = phy->ha;
struct asd_sas_port *port = phy->port;
struct sas_internal *si =
to_sas_internal(sas_ha->core.shost->transportt);
struct domain_device *dev;
unsigned long flags;
if (!port)
return; /* done by a phy event */
dev = port->port_dev;
if (dev)
dev->pathways--;
if (port->num_phys == 1) {
sas_unregister_domain_devices(port, gone);
sas_port_delete(port->port);
port->port = NULL;
} else {
sas_port_delete_phy(port->port, phy->phy);
sas_device_set_phy(dev, port->port);
}
if (si->dft->lldd_port_deformed)
si->dft->lldd_port_deformed(phy);
spin_lock_irqsave(&sas_ha->phy_port_lock, flags);
spin_lock(&port->phy_list_lock);
list_del_init(&phy->port_phy_el);
sas_phy_set_target(phy, NULL);
phy->port = NULL;
port->num_phys--;
port->phy_mask &= ~(1U << phy->id);
if (port->num_phys == 0) {
INIT_LIST_HEAD(&port->phy_list);
memset(port->sas_addr, 0, SAS_ADDR_SIZE);
memset(port->attached_sas_addr, 0, SAS_ADDR_SIZE);
port->class = 0;
port->iproto = 0;
port->tproto = 0;
port->oob_mode = 0;
port->phy_mask = 0;
}
spin_unlock(&port->phy_list_lock);
spin_unlock_irqrestore(&sas_ha->phy_port_lock, flags);
return;
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: | void sas_deform_port(struct asd_sas_phy *phy, int gone)
{
struct sas_ha_struct *sas_ha = phy->ha;
struct asd_sas_port *port = phy->port;
struct sas_internal *si =
to_sas_internal(sas_ha->core.shost->transportt);
struct domain_device *dev;
unsigned long flags;
if (!port)
return; /* done by a phy event */
dev = port->port_dev;
if (dev)
dev->pathways--;
if (port->num_phys == 1) {
sas_unregister_domain_devices(port, gone);
sas_destruct_devices(port);
sas_port_delete(port->port);
port->port = NULL;
} else {
sas_port_delete_phy(port->port, phy->phy);
sas_device_set_phy(dev, port->port);
}
if (si->dft->lldd_port_deformed)
si->dft->lldd_port_deformed(phy);
spin_lock_irqsave(&sas_ha->phy_port_lock, flags);
spin_lock(&port->phy_list_lock);
list_del_init(&phy->port_phy_el);
sas_phy_set_target(phy, NULL);
phy->port = NULL;
port->num_phys--;
port->phy_mask &= ~(1U << phy->id);
if (port->num_phys == 0) {
INIT_LIST_HEAD(&port->phy_list);
memset(port->sas_addr, 0, SAS_ADDR_SIZE);
memset(port->attached_sas_addr, 0, SAS_ADDR_SIZE);
port->class = 0;
port->iproto = 0;
port->tproto = 0;
port->oob_mode = 0;
port->phy_mask = 0;
}
spin_unlock(&port->phy_list_lock);
spin_unlock_irqrestore(&sas_ha->phy_port_lock, flags);
return;
}
| 169,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
(void)remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
| 173,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: hb_buffer_ensure_separate (hb_buffer_t *buffer, unsigned int size)
{
hb_buffer_ensure (buffer, size);
if (buffer->out_info == buffer->info)
{
assert (buffer->have_output);
if (!buffer->pos)
buffer->pos = (hb_internal_glyph_position_t *) calloc (buffer->allocated, sizeof (buffer->pos[0]));
buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos;
memcpy (buffer->out_info, buffer->info, buffer->out_len * sizeof (buffer->out_info[0]));
}
}
Commit Message:
CWE ID: | hb_buffer_ensure_separate (hb_buffer_t *buffer, unsigned int size)
{
if (unlikely (!hb_buffer_ensure (buffer, size))) return FALSE;
if (buffer->out_info == buffer->info)
{
assert (buffer->have_output);
buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos;
memcpy (buffer->out_info, buffer->info, buffer->out_len * sizeof (buffer->out_info[0]));
}
return TRUE;
}
| 164,775 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
uint8_t pin_len, bt_pin_code_t *pin_code)
{
BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
if (pin_code == NULL)
return BT_STATUS_FAIL;
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
if (pairing_cb.is_le_only)
{
int i;
UINT32 passkey = 0;
int multi[] = {100000, 10000, 1000, 100, 10,1};
BD_ADDR remote_bd_addr;
bdcpy(remote_bd_addr, bd_addr->address);
for (i = 0; i < 6; i++)
{
passkey += (multi[i] * (pin_code->pin[i] - '0'));
}
BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
}
else
{
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
}
#else
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
#endif
return BT_STATUS_SUCCESS;
}
Commit Message: DO NOT MERGE Check size of pin before replying
If a malicious client set a pin that was too long it would overflow
the pin code memory.
Bug: 27411268
Change-Id: I9197ac6fdaa92a4799dacb6364e04671a39450cc
CWE ID: CWE-119 | bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
uint8_t pin_len, bt_pin_code_t *pin_code)
{
BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
if (pin_code == NULL || pin_len > PIN_CODE_LEN)
return BT_STATUS_FAIL;
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
if (pairing_cb.is_le_only)
{
int i;
UINT32 passkey = 0;
int multi[] = {100000, 10000, 1000, 100, 10,1};
BD_ADDR remote_bd_addr;
bdcpy(remote_bd_addr, bd_addr->address);
for (i = 0; i < 6; i++)
{
passkey += (multi[i] * (pin_code->pin[i] - '0'));
}
BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
}
else
{
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
}
#else
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
#endif
return BT_STATUS_SUCCESS;
}
| 173,886 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
Commit Message: crypto: ghash - Avoid null pointer dereference if no key is set
The ghash_update function passes a pointer to gf128mul_4k_lle which will
be NULL if ghash_setkey is not called or if the most recent call to
ghash_setkey failed to allocate memory. This causes an oops. Fix this
up by returning an error code in the null case.
This is trivially triggered from unprivileged userspace through the
AF_ALG interface by simply writing to the socket without setting a key.
The ghash_final function has a similar issue, but triggering it requires
a memory allocation failure in ghash_setkey _after_ at least one
successful call to ghash_update.
BUG: unable to handle kernel NULL pointer dereference at 00000670
IP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul]
*pde = 00000000
Oops: 0000 [#1] PREEMPT SMP
Modules linked in: ghash_generic gf128mul algif_hash af_alg nfs lockd nfs_acl sunrpc bridge ipv6 stp llc
Pid: 1502, comm: hashatron Tainted: G W 3.1.0-rc9-00085-ge9308cf #32 Bochs Bochs
EIP: 0060:[<d88c92d4>] EFLAGS: 00000202 CPU: 0
EIP is at gf128mul_4k_lle+0x23/0x60 [gf128mul]
EAX: d69db1f0 EBX: d6b8ddac ECX: 00000004 EDX: 00000000
ESI: 00000670 EDI: d6b8ddac EBP: d6b8ddc8 ESP: d6b8dda4
DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
Process hashatron (pid: 1502, ti=d6b8c000 task=d6810000 task.ti=d6b8c000)
Stack:
00000000 d69db1f0 00000163 00000000 d6b8ddc8 c101a520 d69db1f0 d52aa000
00000ff0 d6b8dde8 d88d310f d6b8a3f8 d52aa000 00001000 d88d502c d6b8ddfc
00001000 d6b8ddf4 c11676ed d69db1e8 d6b8de24 c11679ad d52aa000 00000000
Call Trace:
[<c101a520>] ? kmap_atomic_prot+0x37/0xa6
[<d88d310f>] ghash_update+0x85/0xbe [ghash_generic]
[<c11676ed>] crypto_shash_update+0x18/0x1b
[<c11679ad>] shash_ahash_update+0x22/0x36
[<c11679cc>] shash_async_update+0xb/0xd
[<d88ce0ba>] hash_sendpage+0xba/0xf2 [algif_hash]
[<c121b24c>] kernel_sendpage+0x39/0x4e
[<d88ce000>] ? 0xd88cdfff
[<c121b298>] sock_sendpage+0x37/0x3e
[<c121b261>] ? kernel_sendpage+0x4e/0x4e
[<c10b4dbc>] pipe_to_sendpage+0x56/0x61
[<c10b4e1f>] splice_from_pipe_feed+0x58/0xcd
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b51f5>] __splice_from_pipe+0x36/0x55
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b6383>] splice_from_pipe+0x51/0x64
[<c10b63c2>] ? default_file_splice_write+0x2c/0x2c
[<c10b63d5>] generic_splice_sendpage+0x13/0x15
[<c10b4d66>] ? splice_from_pipe_begin+0x10/0x10
[<c10b527f>] do_splice_from+0x5d/0x67
[<c10b6865>] sys_splice+0x2bf/0x363
[<c129373b>] ? sysenter_exit+0xf/0x16
[<c104dc1e>] ? trace_hardirqs_on_caller+0x10e/0x13f
[<c129370c>] sysenter_do_call+0x12/0x32
Code: 83 c4 0c 5b 5e 5f c9 c3 55 b9 04 00 00 00 89 e5 57 8d 7d e4 56 53 8d 5d e4 83 ec 18 89 45 e0 89 55 dc 0f b6 70 0f c1 e6 04 01 d6 <f3> a5 be 0f 00 00 00 4e 89 d8 e8 48 ff ff ff 8b 45 e0 89 da 0f
EIP: [<d88c92d4>] gf128mul_4k_lle+0x23/0x60 [gf128mul] SS:ESP 0068:d6b8dda4
CR2: 0000000000000670
---[ end trace 4eaa2a86a8e2da24 ]---
note: hashatron[1502] exited with preempt_count 1
BUG: scheduling while atomic: hashatron/1502/0x10000002
INFO: lockdep is turned off.
[...]
Signed-off-by: Nick Bowler <[email protected]>
Cc: [email protected] [2.6.37+]
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
if (!ctx->gf128)
return -ENOKEY;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
| 165,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
char *buf = NULL, *out = NULL, *realm = NULL, **ext_id;
char hostname[256];
int ret;
#ifdef HAVE_SSL
int i;
#endif
size_t buflen, outlen;
assert(ctx);
assert(ctx->cb);
if(mech != NULL) {
_sx_debug(ZONE, "auth request from client (mechanism=%s)", mech);
if(!gsasl_server_support_p(ctx->gsasl_ctx, mech)) {
_sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
return;
}
/* startup */
ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0);
return;
}
/* get the realm */
(ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg);
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_SERVICE, ctx->appname);
gsasl_property_set(sd, GSASL_REALM, realm);
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* get EXTERNAL data from the ssl plugin */
ext_id = NULL;
#ifdef HAVE_SSL
for(i = 0; i < s->env->nplugins; i++)
if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL)
ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id;
if (ext_id != NULL) {
/* if there is, store it for later */
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if (ext_id[i] != NULL) {
ctx->ext_id[i] = strdup(ext_id[i]);
} else {
ctx->ext_id[i] = NULL;
break;
}
}
#endif
_sx_debug(ZONE, "sasl context initialised for %d", s->tag);
s->plugin_data[p->index] = (void *) sd;
if(strcmp(mech, "ANONYMOUS") == 0) {
/*
* special case for SASL ANONYMOUS: ignore the initial
* response provided by the client and generate a random
* authid to use as the jid node for the user, as
* specified in XEP-0175
*/
(ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg);
buf = strdup(out);
buflen = strlen(buf);
} else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) {
/* XXX The above check is hackish, but `in` is just weird */
/* This is a special case for SASL External c2s. See XEP-0178 */
_sx_debug(ZONE, "gsasl auth string is empty");
buf = strdup("");
buflen = strlen(buf);
} else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
return;
}
}
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
return;
}
if(!sd) {
_sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0);
if(buf != NULL) free(buf);
return;
}
_sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf);
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
if(buf != NULL) free(buf);
/* auth completed */
if(ret == GSASL_OK) {
_sx_debug(ZONE, "sasl handshake completed");
/* encode the leftover response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
/* send success */
_sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0);
free(buf);
/* set a notify on the success nad buffer */
((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success;
((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p;
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
/* in progress */
if(ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0);
free(buf);
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
if(out != NULL) free(out);
/* its over */
_sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret));
switch (ret) {
case GSASL_AUTHENTICATION_ERROR:
case GSASL_NO_ANONYMOUS_TOKEN:
case GSASL_NO_AUTHID:
case GSASL_NO_AUTHZID:
case GSASL_NO_PASSWORD:
case GSASL_NO_PASSCODE:
case GSASL_NO_PIN:
case GSASL_NO_SERVICE:
case GSASL_NO_HOSTNAME:
out = _sasl_err_NOT_AUTHORIZED;
break;
case GSASL_UNKNOWN_MECHANISM:
case GSASL_MECHANISM_PARSE_ERROR:
out = _sasl_err_INVALID_MECHANISM;
break;
case GSASL_BASE64_ERROR:
out = _sasl_err_INCORRECT_ENCODING;
break;
default:
out = _sasl_err_MALFORMED_REQUEST;
}
_sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0);
}
Commit Message: Fixed offered SASL mechanism check
CWE ID: CWE-287 | static void _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
char *buf = NULL, *out = NULL, *realm = NULL, **ext_id;
char hostname[256];
int ret;
#ifdef HAVE_SSL
int i;
#endif
size_t buflen, outlen;
assert(ctx);
assert(ctx->cb);
if(mech != NULL) {
_sx_debug(ZONE, "auth request from client (mechanism=%s)", mech);
if(!gsasl_server_support_p(ctx->gsasl_ctx, mech) || (ctx->cb)(sx_sasl_cb_CHECK_MECH, (void*)mech, NULL, s, ctx->cbarg) != sx_sasl_ret_OK) {
_sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
return;
}
/* startup */
ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0);
return;
}
/* get the realm */
(ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg);
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_SERVICE, ctx->appname);
gsasl_property_set(sd, GSASL_REALM, realm);
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* get EXTERNAL data from the ssl plugin */
ext_id = NULL;
#ifdef HAVE_SSL
for(i = 0; i < s->env->nplugins; i++)
if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL)
ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id;
if (ext_id != NULL) {
/* if there is, store it for later */
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if (ext_id[i] != NULL) {
ctx->ext_id[i] = strdup(ext_id[i]);
} else {
ctx->ext_id[i] = NULL;
break;
}
}
#endif
_sx_debug(ZONE, "sasl context initialised for %d", s->tag);
s->plugin_data[p->index] = (void *) sd;
if(strcmp(mech, "ANONYMOUS") == 0) {
/*
* special case for SASL ANONYMOUS: ignore the initial
* response provided by the client and generate a random
* authid to use as the jid node for the user, as
* specified in XEP-0175
*/
(ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg);
buf = strdup(out);
buflen = strlen(buf);
} else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) {
/* XXX The above check is hackish, but `in` is just weird */
/* This is a special case for SASL External c2s. See XEP-0178 */
_sx_debug(ZONE, "gsasl auth string is empty");
buf = strdup("");
buflen = strlen(buf);
} else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
return;
}
}
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
return;
}
if(!sd) {
_sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0);
if(buf != NULL) free(buf);
return;
}
_sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf);
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
if(buf != NULL) free(buf);
/* auth completed */
if(ret == GSASL_OK) {
_sx_debug(ZONE, "sasl handshake completed");
/* encode the leftover response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
/* send success */
_sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0);
free(buf);
/* set a notify on the success nad buffer */
((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success;
((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p;
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
/* in progress */
if(ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0);
free(buf);
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
if(out != NULL) free(out);
/* its over */
_sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret));
switch (ret) {
case GSASL_AUTHENTICATION_ERROR:
case GSASL_NO_ANONYMOUS_TOKEN:
case GSASL_NO_AUTHID:
case GSASL_NO_AUTHZID:
case GSASL_NO_PASSWORD:
case GSASL_NO_PASSCODE:
case GSASL_NO_PIN:
case GSASL_NO_SERVICE:
case GSASL_NO_HOSTNAME:
out = _sasl_err_NOT_AUTHORIZED;
break;
case GSASL_UNKNOWN_MECHANISM:
case GSASL_MECHANISM_PARSE_ERROR:
out = _sasl_err_INVALID_MECHANISM;
break;
case GSASL_BASE64_ERROR:
out = _sasl_err_INCORRECT_ENCODING;
break;
default:
out = _sasl_err_MALFORMED_REQUEST;
}
_sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0);
}
| 168,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Downmix_Reset(downmix_object_t *pDownmixer, bool init) {
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | int Downmix_Reset(downmix_object_t *pDownmixer, bool init) {
int Downmix_Reset(downmix_object_t *pDownmixer __unused, bool init __unused) {
return 0;
}
| 173,345 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_field(netdissect_options *ndo, const char **pptr, int *len)
{
const char *s;
if (*len <= 0 || !pptr || !*pptr)
return NULL;
if (*pptr > (const char *) ndo->ndo_snapend)
return NULL;
s = *pptr;
while (*pptr <= (const char *) ndo->ndo_snapend && *len >= 0 && **pptr) {
(*pptr)++;
(*len)--;
}
(*pptr)++;
(*len)--;
if (*len < 0 || *pptr > (const char *) ndo->ndo_snapend)
return NULL;
return s;
}
Commit Message: CVE-2017-12902/Zephyr: Fix bounds checking.
Use ND_TTEST() rather than comparing against ndo->ndo_snapend ourselves;
it's easy to get the tests wrong.
Check for running out of packet data before checking for running out of
captured data, and distinguish between running out of packet data (which
might just mean "no more strings") and running out of captured data
(which means "truncated").
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | parse_field(netdissect_options *ndo, const char **pptr, int *len)
parse_field(netdissect_options *ndo, const char **pptr, int *len, int *truncated)
{
const char *s;
/* Start of string */
s = *pptr;
/* Scan for the NUL terminator */
for (;;) {
if (*len == 0) {
/* Ran out of packet data without finding it */
return NULL;
}
if (!ND_TTEST(**pptr)) {
/* Ran out of captured data without finding it */
*truncated = 1;
return NULL;
}
if (**pptr == '\0') {
/* Found it */
break;
}
/* Keep scanning */
(*pptr)++;
(*len)--;
}
/* Skip the NUL terminator */
(*pptr)++;
(*len)--;
return s;
}
| 167,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 base64decode_block(unsigned char *target, const char *data, size_t data_size)
{
int w1,w2,w3,w4;
int i;
size_t n;
if (!data || (data_size <= 0)) {
return 0;
}
n = 0;
i = 0;
while (n < data_size-3) {
w1 = base64_table[(int)data[n]];
w2 = base64_table[(int)data[n+1]];
w3 = base64_table[(int)data[n+2]];
w4 = base64_table[(int)data[n+3]];
if (w2 >= 0) {
target[i++] = (char)((w1*4 + (w2 >> 4)) & 255);
}
if (w3 >= 0) {
target[i++] = (char)((w2*16 + (w3 >> 2)) & 255);
}
if (w4 >= 0) {
target[i++] = (char)((w3*64 + w4) & 255);
}
n+=4;
}
return i;
}
Commit Message: base64: Rework base64decode to handle split encoded data correctly
CWE ID: CWE-125 | static int base64decode_block(unsigned char *target, const char *data, size_t data_size)
| 168,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostImpl::SendFrontSurfaceIsProtected(
bool is_protected,
uint32 protection_state_id,
int32 route_id,
int gpu_host_id) {
GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
if (ui_shim) {
ui_shim->Send(new AcceleratedSurfaceMsg_SetFrontSurfaceIsProtected(
route_id, is_protected, protection_state_id));
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostImpl::SendFrontSurfaceIsProtected(
| 171,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 && p[0] != 0x80 && p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 || p[0] != 0x80 || p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
| 169,047 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Browser::WindowFullscreenStateChanged() {
UpdateCommandsForFullscreenMode(window_->IsFullscreen());
UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
MessageLoop::current()->PostTask(
FROM_HERE, method_factory_.NewRunnableMethod(
&Browser::NotifyFullscreenChange));
if (!window_->IsFullscreen())
NotifyTabOfFullscreenExitIfNecessary();
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void Browser::WindowFullscreenStateChanged() {
UpdateCommandsForFullscreenMode(window_->IsFullscreen());
UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
MessageLoop::current()->PostTask(
FROM_HERE, method_factory_.NewRunnableMethod(
&Browser::NotifyFullscreenChange));
bool notify_tab_of_exit;
#if defined(OS_MACOSX)
notify_tab_of_exit = !window_->InPresentationMode();
#else
notify_tab_of_exit = !window_->IsFullscreen();
#endif
if (notify_tab_of_exit)
NotifyTabOfFullscreenExitIfNecessary();
}
| 170,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
Commit Message: xmlparse.c: Deny internal entities closing the doctype
CWE ID: CWE-611 | processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
| 169,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::Seek(
long long time_ns,
const BlockEntry*& pResult) const
{
const long status = GetFirst(pResult);
if (status < 0) //buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); //loaded only, not preloaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi)
{
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
while (lo > i)
{
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this);
if ((pResult != 0) && !pResult->EOS())
return 0;
}
pResult = GetEOS(); //weird
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Track::Seek(
long Track::Seek(long long time_ns, const BlockEntry*& pResult) const {
const long status = GetFirst(pResult);
if (status < 0) // buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); // loaded only, not preloaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi) {
// INVARIANT:
//[i, lo) <= time_ns
//[lo, hi) ?
//[hi, j) > time_ns
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
while (lo > i) {
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this);
if ((pResult != 0) && !pResult->EOS())
return 0;
// landed on empty cluster (no entries)
}
pResult = GetEOS(); // weird
return 0;
}
| 174,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 nfs4_close_done(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
struct nfs_server *server = NFS_SERVER(calldata->inode);
if (RPC_ASSASSINATED(task))
return;
/* hmm. we are done with the inode, and in the process of freeing
* the state_owner. we keep this around to process errors
*/
switch (task->tk_status) {
case 0:
nfs_set_open_stateid(state, &calldata->res.stateid, 0);
renew_lease(server, calldata->timestamp);
break;
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_OLD_STATEID:
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_EXPIRED:
if (calldata->arg.open_flags == 0)
break;
default:
if (nfs4_async_handle_error(task, server, state) == -EAGAIN) {
rpc_restart_call(task);
return;
}
}
nfs_refresh_inode(calldata->inode, calldata->res.fattr);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_close_done(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
struct nfs_server *server = NFS_SERVER(calldata->inode);
if (RPC_ASSASSINATED(task))
return;
/* hmm. we are done with the inode, and in the process of freeing
* the state_owner. we keep this around to process errors
*/
switch (task->tk_status) {
case 0:
nfs_set_open_stateid(state, &calldata->res.stateid, 0);
renew_lease(server, calldata->timestamp);
break;
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_OLD_STATEID:
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_EXPIRED:
if (calldata->arg.fmode == 0)
break;
default:
if (nfs4_async_handle_error(task, server, state) == -EAGAIN) {
rpc_restart_call(task);
return;
}
}
nfs_refresh_inode(calldata->inode, calldata->res.fattr);
}
| 165,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char* allocFromUTF32(const char32_t* in, size_t len)
{
if (len == 0) {
return getEmptyString();
}
const ssize_t bytes = utf32_to_utf8_length(in, len);
if (bytes < 0) {
return getEmptyString();
}
SharedBuffer* buf = SharedBuffer::alloc(bytes+1);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
char* str = (char*) buf->data();
utf32_to_utf8(in, len, str);
return str;
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119 | static char* allocFromUTF32(const char32_t* in, size_t len)
{
if (len == 0) {
return getEmptyString();
}
const ssize_t resultStrLen = utf32_to_utf8_length(in, len) + 1;
if (resultStrLen < 1) {
return getEmptyString();
}
SharedBuffer* buf = SharedBuffer::alloc(resultStrLen);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
char* resultStr = (char*) buf->data();
utf32_to_utf8(in, len, resultStr, resultStrLen);
return resultStr;
}
| 173,418 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
rules_.ParseFromString(server_whitelist);
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | void HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
// TODO(eroman): Is this necessary? The issue is that
// HttpAuthFilterWhitelist is trying to use ProxyBypassRules as a generic
// URL filter. However internally it has some implicit rules for localhost
// and linklocal addresses.
rules_.ParseFromString(ProxyBypassRules::GetRulesToSubtractImplicit() + ";" +
server_whitelist);
}
| 172,644 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: LosslessTestLarge()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
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 | LosslessTestLarge()
LosslessTest()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
| 174,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
struct ring_buffer *buf;
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
buf = tr->trace_buffer.buffer;
tr->trace_buffer.buffer = tr->max_buffer.buffer;
tr->max_buffer.buffer = buf;
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787 | update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
swap(tr->trace_buffer.buffer, tr->max_buffer.buffer);
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
| 169,185 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 perf_output_begin(struct perf_output_handle *handle,
struct perf_event *event, unsigned int size,
int nmi, int sample)
{
struct ring_buffer *rb;
unsigned long tail, offset, head;
int have_lost;
struct perf_sample_data sample_data;
struct {
struct perf_event_header header;
u64 id;
u64 lost;
} lost_event;
rcu_read_lock();
/*
* For inherited events we send all the output towards the parent.
*/
if (event->parent)
event = event->parent;
rb = rcu_dereference(event->rb);
if (!rb)
goto out;
handle->rb = rb;
handle->event = event;
handle->nmi = nmi;
handle->sample = sample;
if (!rb->nr_pages)
goto out;
have_lost = local_read(&rb->lost);
if (have_lost) {
lost_event.header.size = sizeof(lost_event);
perf_event_header__init_id(&lost_event.header, &sample_data,
event);
size += lost_event.header.size;
}
perf_output_get_handle(handle);
do {
/*
* Userspace could choose to issue a mb() before updating the
* tail pointer. So that all reads will be completed before the
* write is issued.
*/
tail = ACCESS_ONCE(rb->user_page->data_tail);
smp_rmb();
offset = head = local_read(&rb->head);
head += size;
if (unlikely(!perf_output_space(rb, tail, offset, head)))
goto fail;
} while (local_cmpxchg(&rb->head, offset, head) != offset);
if (head - local_read(&rb->wakeup) > rb->watermark)
local_add(rb->watermark, &rb->wakeup);
handle->page = offset >> (PAGE_SHIFT + page_order(rb));
handle->page &= rb->nr_pages - 1;
handle->size = offset & ((PAGE_SIZE << page_order(rb)) - 1);
handle->addr = rb->data_pages[handle->page];
handle->addr += handle->size;
handle->size = (PAGE_SIZE << page_order(rb)) - handle->size;
if (have_lost) {
lost_event.header.type = PERF_RECORD_LOST;
lost_event.header.misc = 0;
lost_event.id = event->id;
lost_event.lost = local_xchg(&rb->lost, 0);
perf_output_put(handle, lost_event);
perf_event__output_id_sample(event, handle, &sample_data);
}
return 0;
fail:
local_inc(&rb->lost);
perf_output_put_handle(handle);
out:
rcu_read_unlock();
return -ENOSPC;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | int perf_output_begin(struct perf_output_handle *handle,
struct perf_event *event, unsigned int size,
int sample)
{
struct ring_buffer *rb;
unsigned long tail, offset, head;
int have_lost;
struct perf_sample_data sample_data;
struct {
struct perf_event_header header;
u64 id;
u64 lost;
} lost_event;
rcu_read_lock();
/*
* For inherited events we send all the output towards the parent.
*/
if (event->parent)
event = event->parent;
rb = rcu_dereference(event->rb);
if (!rb)
goto out;
handle->rb = rb;
handle->event = event;
handle->sample = sample;
if (!rb->nr_pages)
goto out;
have_lost = local_read(&rb->lost);
if (have_lost) {
lost_event.header.size = sizeof(lost_event);
perf_event_header__init_id(&lost_event.header, &sample_data,
event);
size += lost_event.header.size;
}
perf_output_get_handle(handle);
do {
/*
* Userspace could choose to issue a mb() before updating the
* tail pointer. So that all reads will be completed before the
* write is issued.
*/
tail = ACCESS_ONCE(rb->user_page->data_tail);
smp_rmb();
offset = head = local_read(&rb->head);
head += size;
if (unlikely(!perf_output_space(rb, tail, offset, head)))
goto fail;
} while (local_cmpxchg(&rb->head, offset, head) != offset);
if (head - local_read(&rb->wakeup) > rb->watermark)
local_add(rb->watermark, &rb->wakeup);
handle->page = offset >> (PAGE_SHIFT + page_order(rb));
handle->page &= rb->nr_pages - 1;
handle->size = offset & ((PAGE_SIZE << page_order(rb)) - 1);
handle->addr = rb->data_pages[handle->page];
handle->addr += handle->size;
handle->size = (PAGE_SIZE << page_order(rb)) - handle->size;
if (have_lost) {
lost_event.header.type = PERF_RECORD_LOST;
lost_event.header.misc = 0;
lost_event.id = event->id;
lost_event.lost = local_xchg(&rb->lost, 0);
perf_output_put(handle, lost_event);
perf_event__output_id_sample(event, handle, &sample_data);
}
return 0;
fail:
local_inc(&rb->lost);
perf_output_put_handle(handle);
out:
rcu_read_unlock();
return -ENOSPC;
}
| 165,841 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
sp<Sample> sample;
SoundChannel* channel;
int channelID;
Mutex::Autolock lock(&mLock);
if (mQuit) {
return 0;
}
sample = findSample(sampleID);
if ((sample == 0) || (sample->state() != Sample::READY)) {
ALOGW(" sample %d not READY", sampleID);
return 0;
}
dump();
channel = allocateChannel_l(priority);
if (!channel) {
ALOGV("No channel allocated");
return 0;
}
channelID = ++mNextChannelID;
ALOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264 | int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
SoundChannel* channel;
int channelID;
Mutex::Autolock lock(&mLock);
if (mQuit) {
return 0;
}
sp<Sample> sample(findSample_l(sampleID));
if ((sample == 0) || (sample->state() != Sample::READY)) {
ALOGW(" sample %d not READY", sampleID);
return 0;
}
dump();
channel = allocateChannel_l(priority);
if (!channel) {
ALOGV("No channel allocated");
return 0;
}
channelID = ++mNextChannelID;
ALOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
| 173,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 VRDisplay::ProcessScheduledWindowAnimations(double timestamp) {
TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_);
auto doc = navigator_vr_->GetDocument();
if (!doc)
return;
auto page = doc->GetPage();
if (!page)
return;
page->Animator().ServiceScriptedAnimations(timestamp);
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::ProcessScheduledWindowAnimations(double timestamp) {
TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_);
auto doc = navigator_vr_->GetDocument();
if (!doc)
return;
auto page = doc->GetPage();
if (!page)
return;
bool had_pending_vrdisplay_raf = pending_vrdisplay_raf_;
page->Animator().ServiceScriptedAnimations(timestamp);
if (had_pending_vrdisplay_raf != pending_vrdisplay_raf_) {
DVLOG(1) << __FUNCTION__
<< ": window.rAF fallback successfully scheduled VRDisplay.rAF";
}
if (!pending_vrdisplay_raf_) {
// There wasn't any call to vrDisplay.rAF, so we will not be getting new
// frames from now on unless the application schedules one down the road in
// reaction to a separate event or timeout. TODO(klausw,crbug.com/716087):
// do something more useful here?
DVLOG(1) << __FUNCTION__
<< ": no scheduled VRDisplay.requestAnimationFrame, presentation "
"broken?";
}
}
| 171,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return ERROR_SUCCESS;
const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level);
if (!integrity_level_str) {
return ERROR_SUCCESS;
}
std::wstring ace_access = SDDL_NO_READ_UP;
ace_access += SDDL_NO_WRITE_UP;
DWORD error = SetObjectIntegrityLabel(::GetCurrentProcess(), SE_KERNEL_OBJECT,
ace_access.c_str(),
integrity_level_str);
if (ERROR_SUCCESS != error)
return error;
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return SetTokenIntegrityLevel(token.Get(), integrity_level);
}
Commit Message: Prevent sandboxed processes from opening each other
TBR=brettw
BUG=117627
BUG=119150
TEST=sbox_validation_tests
Review URL: https://chromiumcodereview.appspot.com/9716027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return ERROR_SUCCESS;
// We don't check for an invalid level here because we'll just let it
// fail on the SetTokenIntegrityLevel call later on.
if (integrity_level == INTEGRITY_LEVEL_LAST) {
return ERROR_SUCCESS;
}
HANDLE token_handle;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
&token_handle))
return ::GetLastError();
base::win::ScopedHandle token(token_handle);
return SetTokenIntegrityLevel(token.Get(), integrity_level);
}
| 170,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) {
base::AutoReset<bool> auto_reset(&ignore_changes_, true);
base::ListValue* list = new base::ListValue();
Profile* profile = Profile::FromWebUI(web_ui());
PrefService* prefs = profile->GetPrefs();
for (std::set<std::string>::iterator it = visible_apps_.begin();
it != visible_apps_.end(); ++it) {
const Extension* extension = extension_service_->GetInstalledExtension(*it);
if (extension && extensions::ui_util::ShouldDisplayInNewTabPage(
extension, profile)) {
base::DictionaryValue* app_info = GetAppInfo(extension);
list->Append(app_info);
}
}
dictionary->Set("apps", list);
#if defined(OS_MACOSX)
dictionary->SetBoolean("disableAppWindowLaunch", true);
dictionary->SetBoolean("disableCreateAppShortcut", true);
#endif
#if defined(OS_CHROMEOS)
dictionary->SetBoolean("disableCreateAppShortcut", true);
#endif
const base::ListValue* app_page_names =
prefs->GetList(prefs::kNtpAppPageNames);
if (!app_page_names || !app_page_names->GetSize()) {
ListPrefUpdate update(prefs, prefs::kNtpAppPageNames);
base::ListValue* list = update.Get();
list->Set(0, new base::StringValue(
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)));
dictionary->Set("appPageNames",
static_cast<base::ListValue*>(list->DeepCopy()));
} else {
dictionary->Set("appPageNames",
static_cast<base::ListValue*>(app_page_names->DeepCopy()));
}
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) {
base::AutoReset<bool> auto_reset(&ignore_changes_, true);
base::ListValue* list = new base::ListValue();
Profile* profile = Profile::FromWebUI(web_ui());
PrefService* prefs = profile->GetPrefs();
for (std::set<std::string>::iterator it = visible_apps_.begin();
it != visible_apps_.end(); ++it) {
const Extension* extension = extension_service_->GetInstalledExtension(*it);
if (extension && extensions::ui_util::ShouldDisplayInNewTabPage(
extension, profile)) {
base::DictionaryValue* app_info = GetAppInfo(extension);
list->Append(app_info);
}
}
dictionary->Set("apps", list);
const base::ListValue* app_page_names =
prefs->GetList(prefs::kNtpAppPageNames);
if (!app_page_names || !app_page_names->GetSize()) {
ListPrefUpdate update(prefs, prefs::kNtpAppPageNames);
base::ListValue* list = update.Get();
list->Set(0, new base::StringValue(
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)));
dictionary->Set("appPageNames",
static_cast<base::ListValue*>(list->DeepCopy()));
} else {
dictionary->Set("appPageNames",
static_cast<base::ListValue*>(app_page_names->DeepCopy()));
}
}
| 171,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: OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr)
{
unsigned int index = 0;
OMX_U8 *temp_buff ;
if (bufferHdr == NULL || m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]",
bufferHdr, m_inp_mem_ptr);
return OMX_ErrorBadParameter;
}
index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
#ifdef _ANDROID_ICS_
if (meta_mode_enable) {
if (index < m_sInPortDef.nBufferCountActual) {
memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index]));
memset(&meta_buffers[index], 0, sizeof(meta_buffers[index]));
}
if (!mUseProxyColorFormat)
return OMX_ErrorNone;
else {
c2d_conv.close();
opaque_buffer_hdr[index] = NULL;
}
}
#endif
if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat &&
dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) {
DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf");
}
if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) {
if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) {
DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case");
if(!secure_session) {
munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size);
} else {
free(m_pInput_pmem[index].buffer);
}
close (m_pInput_pmem[index].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[index]);
#endif
m_pInput_pmem[index].fd = -1;
} else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true &&
m_use_input_pmem == OMX_FALSE)) {
DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case");
if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf");
}
if(!secure_session) {
munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size);
}
close (m_pInput_pmem[index].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[index]);
#endif
m_pInput_pmem[index].fd = -1;
} else {
DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case");
}
}
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27903498
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVenc problem #3)
CRs-Fixed: 1010088
Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3
CWE ID: | OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr)
{
unsigned int index = 0;
OMX_U8 *temp_buff ;
if (bufferHdr == NULL || m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]",
bufferHdr, m_inp_mem_ptr);
return OMX_ErrorBadParameter;
}
index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
#ifdef _ANDROID_ICS_
if (meta_mode_enable) {
if (index < m_sInPortDef.nBufferCountActual) {
memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index]));
memset(&meta_buffers[index], 0, sizeof(meta_buffers[index]));
}
if (!mUseProxyColorFormat)
return OMX_ErrorNone;
else {
c2d_conv.close();
opaque_buffer_hdr[index] = NULL;
}
}
#endif
if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat &&
dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) {
DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf");
}
if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) {
auto_lock l(m_lock);
if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) {
DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case");
if(!secure_session) {
munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size);
} else {
free(m_pInput_pmem[index].buffer);
}
m_pInput_pmem[index].buffer = NULL;
close (m_pInput_pmem[index].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[index]);
#endif
m_pInput_pmem[index].fd = -1;
} else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true &&
m_use_input_pmem == OMX_FALSE)) {
DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case");
if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf");
}
if(!secure_session) {
munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size);
m_pInput_pmem[index].buffer = NULL;
}
close (m_pInput_pmem[index].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[index]);
#endif
m_pInput_pmem[index].fd = -1;
} else {
DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case");
}
}
return OMX_ErrorNone;
}
| 173,748 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent *ex;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)le32_to_cpu(ex->ee_block),
ext4_ext_get_actual_len(ex));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-362 | static int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path)
{
struct ext4_extent *ex;
ext4_lblk_t ee_block;
unsigned int ee_len;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)ee_block, ee_len);
/* If extent is larger than requested then split is required */
if (ee_block != map->m_lblk || ee_len > map->m_len) {
err = ext4_split_unwritten_extents(handle, inode, map, path,
EXT4_GET_BLOCKS_CONVERT);
if (err < 0)
goto out;
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk, path);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
depth = ext_depth(inode);
ex = path[depth].p_ext;
}
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
| 165,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 proc_sys_readdir(struct file *file, struct dir_context *ctx)
{
struct ctl_table_header *head = grab_header(file_inode(file));
struct ctl_table_header *h = NULL;
struct ctl_table *entry;
struct ctl_dir *ctl_dir;
unsigned long pos;
if (IS_ERR(head))
return PTR_ERR(head);
ctl_dir = container_of(head, struct ctl_dir, header);
if (!dir_emit_dots(file, ctx))
return 0;
pos = 2;
for (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {
if (!scan(h, entry, &pos, file, ctx)) {
sysctl_head_finish(h);
break;
}
}
sysctl_head_finish(head);
return 0;
}
Commit Message: sysctl: Drop reference added by grab_header in proc_sys_readdir
Fixes CVE-2016-9191, proc_sys_readdir doesn't drop reference
added by grab_header when return from !dir_emit_dots path.
It can cause any path called unregister_sysctl_table will
wait forever.
The calltrace of CVE-2016-9191:
[ 5535.960522] Call Trace:
[ 5535.963265] [<ffffffff817cdaaf>] schedule+0x3f/0xa0
[ 5535.968817] [<ffffffff817d33fb>] schedule_timeout+0x3db/0x6f0
[ 5535.975346] [<ffffffff817cf055>] ? wait_for_completion+0x45/0x130
[ 5535.982256] [<ffffffff817cf0d3>] wait_for_completion+0xc3/0x130
[ 5535.988972] [<ffffffff810d1fd0>] ? wake_up_q+0x80/0x80
[ 5535.994804] [<ffffffff8130de64>] drop_sysctl_table+0xc4/0xe0
[ 5536.001227] [<ffffffff8130de17>] drop_sysctl_table+0x77/0xe0
[ 5536.007648] [<ffffffff8130decd>] unregister_sysctl_table+0x4d/0xa0
[ 5536.014654] [<ffffffff8130deff>] unregister_sysctl_table+0x7f/0xa0
[ 5536.021657] [<ffffffff810f57f5>] unregister_sched_domain_sysctl+0x15/0x40
[ 5536.029344] [<ffffffff810d7704>] partition_sched_domains+0x44/0x450
[ 5536.036447] [<ffffffff817d0761>] ? __mutex_unlock_slowpath+0x111/0x1f0
[ 5536.043844] [<ffffffff81167684>] rebuild_sched_domains_locked+0x64/0xb0
[ 5536.051336] [<ffffffff8116789d>] update_flag+0x11d/0x210
[ 5536.057373] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450
[ 5536.064186] [<ffffffff81167acb>] ? cpuset_css_offline+0x1b/0x60
[ 5536.070899] [<ffffffff810fce3d>] ? trace_hardirqs_on+0xd/0x10
[ 5536.077420] [<ffffffff817cf61f>] ? mutex_lock_nested+0x2df/0x450
[ 5536.084234] [<ffffffff8115a9f5>] ? css_killed_work_fn+0x25/0x220
[ 5536.091049] [<ffffffff81167ae5>] cpuset_css_offline+0x35/0x60
[ 5536.097571] [<ffffffff8115aa2c>] css_killed_work_fn+0x5c/0x220
[ 5536.104207] [<ffffffff810bc83f>] process_one_work+0x1df/0x710
[ 5536.110736] [<ffffffff810bc7c0>] ? process_one_work+0x160/0x710
[ 5536.117461] [<ffffffff810bce9b>] worker_thread+0x12b/0x4a0
[ 5536.123697] [<ffffffff810bcd70>] ? process_one_work+0x710/0x710
[ 5536.130426] [<ffffffff810c3f7e>] kthread+0xfe/0x120
[ 5536.135991] [<ffffffff817d4baf>] ret_from_fork+0x1f/0x40
[ 5536.142041] [<ffffffff810c3e80>] ? kthread_create_on_node+0x230/0x230
One cgroup maintainer mentioned that "cgroup is trying to offline
a cpuset css, which takes place under cgroup_mutex. The offlining
ends up trying to drain active usages of a sysctl table which apprently
is not happening."
The real reason is that proc_sys_readdir doesn't drop reference added
by grab_header when return from !dir_emit_dots path. So this cpuset
offline path will wait here forever.
See here for details: http://www.openwall.com/lists/oss-security/2016/11/04/13
Fixes: f0c3b5093add ("[readdir] convert procfs")
Cc: [email protected]
Reported-by: CAI Qian <[email protected]>
Tested-by: Yang Shukui <[email protected]>
Signed-off-by: Zhou Chengming <[email protected]>
Acked-by: Al Viro <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
CWE ID: CWE-20 | static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
{
struct ctl_table_header *head = grab_header(file_inode(file));
struct ctl_table_header *h = NULL;
struct ctl_table *entry;
struct ctl_dir *ctl_dir;
unsigned long pos;
if (IS_ERR(head))
return PTR_ERR(head);
ctl_dir = container_of(head, struct ctl_dir, header);
if (!dir_emit_dots(file, ctx))
goto out;
pos = 2;
for (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {
if (!scan(h, entry, &pos, file, ctx)) {
sysctl_head_finish(h);
break;
}
}
out:
sysctl_head_finish(head);
return 0;
}
| 166,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> enabledAtRuntimeMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.enabledAtRuntimeMethod2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->enabledAtRuntimeMethod2(intArg);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> enabledAtRuntimeMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.enabledAtRuntimeMethod2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->enabledAtRuntimeMethod2(intArg);
return v8::Handle<v8::Value>();
}
| 171,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLXconfig *config;
__GLXscreen *pGlxScreen;
int err;
if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
return err;
if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err))
config, pGlxScreen, req->isDirect);
}
Commit Message:
CWE ID: CWE-20 | int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
ClientPtr client = cl->client;
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLXconfig *config;
__GLXscreen *pGlxScreen;
int err;
REQUEST_SIZE_MATCH(xGLXCreateContextReq);
if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
return err;
if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err))
config, pGlxScreen, req->isDirect);
}
| 165,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
Commit Message:
CWE ID: CWE-125 | static void Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) ||
BOUNDS( CUR.GS.rp0, CUR.zp0.n_points) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
| 164,780 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 can_open_cached(struct nfs4_state *state, int mode)
{
int ret = 0;
switch (mode & (FMODE_READ|FMODE_WRITE|O_EXCL)) {
case FMODE_READ:
ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0;
break;
case FMODE_WRITE:
ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0;
break;
case FMODE_READ|FMODE_WRITE:
ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0;
}
return ret;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static int can_open_cached(struct nfs4_state *state, int mode)
static int can_open_cached(struct nfs4_state *state, fmode_t mode, int open_mode)
{
int ret = 0;
if (open_mode & O_EXCL)
goto out;
switch (mode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0;
break;
case FMODE_WRITE:
ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0;
break;
case FMODE_READ|FMODE_WRITE:
ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0;
}
out:
return ret;
}
| 165,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_command (unsigned char c)
{
static int dtr_up = 0;
int newbaud, newflow, newparity, newbits;
const char *xfr_cmd;
char *fname;
int r;
switch (c) {
case KEY_EXIT:
return 1;
case KEY_QUIT:
term_set_hupcl(tty_fd, 0);
term_flush(tty_fd);
term_apply(tty_fd);
term_erase(tty_fd);
return 1;
case KEY_STATUS:
show_status(dtr_up);
break;
case KEY_PULSE:
fd_printf(STO, "\r\n*** pulse DTR ***\r\n");
if ( term_pulse_dtr(tty_fd) < 0 )
fd_printf(STO, "*** FAILED\r\n");
break;
case KEY_TOGGLE:
if ( dtr_up )
r = term_lower_dtr(tty_fd);
else
r = term_raise_dtr(tty_fd);
if ( r >= 0 ) dtr_up = ! dtr_up;
fd_printf(STO, "\r\n*** DTR: %s ***\r\n",
dtr_up ? "up" : "down");
break;
case KEY_BAUD_UP:
case KEY_BAUD_DN:
if (c == KEY_BAUD_UP)
opts.baud = baud_up(opts.baud);
else
opts.baud = baud_down(opts.baud);
term_set_baudrate(tty_fd, opts.baud);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbaud = term_get_baudrate(tty_fd, NULL);
if ( opts.baud != newbaud ) {
fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n",
opts.baud, newbaud);
} else {
fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud);
}
set_tty_write_sz(newbaud);
break;
case KEY_FLOW:
opts.flow = flow_next(opts.flow);
term_set_flowcntrl(tty_fd, opts.flow);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newflow = term_get_flowcntrl(tty_fd);
if ( opts.flow != newflow ) {
fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n",
flow_str[opts.flow], flow_str[newflow]);
} else {
fd_printf(STO, "\r\n*** flow: %s ***\r\n",
flow_str[opts.flow]);
}
break;
case KEY_PARITY:
opts.parity = parity_next(opts.parity);
term_set_parity(tty_fd, opts.parity);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newparity = term_get_parity(tty_fd);
if (opts.parity != newparity ) {
fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n",
parity_str[opts.parity],
parity_str[newparity]);
} else {
fd_printf(STO, "\r\n*** parity: %s ***\r\n",
parity_str[opts.parity]);
}
break;
case KEY_BITS:
opts.databits = bits_next(opts.databits);
term_set_databits(tty_fd, opts.databits);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbits = term_get_databits(tty_fd);
if (opts.databits != newbits ) {
fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n",
opts.databits, newbits);
} else {
fd_printf(STO, "\r\n*** databits: %d ***\r\n",
opts.databits);
}
break;
case KEY_LECHO:
opts.lecho = ! opts.lecho;
fd_printf(STO, "\r\n*** local echo: %s ***\r\n",
opts.lecho ? "yes" : "no");
break;
case KEY_SEND:
case KEY_RECEIVE:
xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd;
if ( xfr_cmd[0] == '\0' ) {
fd_printf(STO, "\r\n*** command disabled ***\r\n");
break;
}
fname = read_filename();
if (fname == NULL) {
fd_printf(STO, "*** cannot read filename ***\r\n");
break;
}
run_cmd(tty_fd, xfr_cmd, fname, NULL);
free(fname);
break;
case KEY_BREAK:
term_break(tty_fd);
fd_printf(STO, "\r\n*** break sent ***\r\n");
break;
default:
break;
}
return 0;
}
Commit Message: Do not use "/bin/sh" to run external commands.
Picocom no longer uses /bin/sh to run external commands for
file-transfer operations. Parsing the command line and spliting it into
arguments is now performed internally by picocom, using quoting rules
very similar to those of the Unix shell. Hopefully, this makes it
impossible to inject shell-commands when supplying filenames or
extra arguments to the send- and receive-file commands.
CWE ID: CWE-77 | do_command (unsigned char c)
{
static int dtr_up = 0;
int newbaud, newflow, newparity, newbits;
const char *xfr_cmd;
char *fname;
int r;
switch (c) {
case KEY_EXIT:
return 1;
case KEY_QUIT:
term_set_hupcl(tty_fd, 0);
term_flush(tty_fd);
term_apply(tty_fd);
term_erase(tty_fd);
return 1;
case KEY_STATUS:
show_status(dtr_up);
break;
case KEY_PULSE:
fd_printf(STO, "\r\n*** pulse DTR ***\r\n");
if ( term_pulse_dtr(tty_fd) < 0 )
fd_printf(STO, "*** FAILED\r\n");
break;
case KEY_TOGGLE:
if ( dtr_up )
r = term_lower_dtr(tty_fd);
else
r = term_raise_dtr(tty_fd);
if ( r >= 0 ) dtr_up = ! dtr_up;
fd_printf(STO, "\r\n*** DTR: %s ***\r\n",
dtr_up ? "up" : "down");
break;
case KEY_BAUD_UP:
case KEY_BAUD_DN:
if (c == KEY_BAUD_UP)
opts.baud = baud_up(opts.baud);
else
opts.baud = baud_down(opts.baud);
term_set_baudrate(tty_fd, opts.baud);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbaud = term_get_baudrate(tty_fd, NULL);
if ( opts.baud != newbaud ) {
fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n",
opts.baud, newbaud);
} else {
fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud);
}
set_tty_write_sz(newbaud);
break;
case KEY_FLOW:
opts.flow = flow_next(opts.flow);
term_set_flowcntrl(tty_fd, opts.flow);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newflow = term_get_flowcntrl(tty_fd);
if ( opts.flow != newflow ) {
fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n",
flow_str[opts.flow], flow_str[newflow]);
} else {
fd_printf(STO, "\r\n*** flow: %s ***\r\n",
flow_str[opts.flow]);
}
break;
case KEY_PARITY:
opts.parity = parity_next(opts.parity);
term_set_parity(tty_fd, opts.parity);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newparity = term_get_parity(tty_fd);
if (opts.parity != newparity ) {
fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n",
parity_str[opts.parity],
parity_str[newparity]);
} else {
fd_printf(STO, "\r\n*** parity: %s ***\r\n",
parity_str[opts.parity]);
}
break;
case KEY_BITS:
opts.databits = bits_next(opts.databits);
term_set_databits(tty_fd, opts.databits);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbits = term_get_databits(tty_fd);
if (opts.databits != newbits ) {
fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n",
opts.databits, newbits);
} else {
fd_printf(STO, "\r\n*** databits: %d ***\r\n",
opts.databits);
}
break;
case KEY_LECHO:
opts.lecho = ! opts.lecho;
fd_printf(STO, "\r\n*** local echo: %s ***\r\n",
opts.lecho ? "yes" : "no");
break;
case KEY_SEND:
case KEY_RECEIVE:
xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd;
if ( xfr_cmd[0] == '\0' ) {
fd_printf(STO, "\r\n*** command disabled ***\r\n");
break;
}
fname = read_filename();
if (fname == NULL) {
fd_printf(STO, "*** cannot read filename ***\r\n");
break;
}
run_cmd(tty_fd, xfr_cmd, fname);
free(fname);
break;
case KEY_BREAK:
term_break(tty_fd);
fd_printf(STO, "\r\n*** break sent ***\r\n");
break;
default:
break;
}
return 0;
}
| 168,849 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Handle<v8::Value> V8TestInterface::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
ScriptExecutionContext* context = getScriptExecutionContext();
if (!context)
return V8Proxy::throwError(V8Proxy::ReferenceError, "TestInterface constructor's associated context is not available", args.GetIsolate());
RefPtr<TestInterface> impl = TestInterface::create(context, str1, str2, ec);
v8::Handle<v8::Object> wrapper = args.Holder();
if (ec)
goto fail;
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate());
return args.Holder();
fail:
return throwError(ec, args.GetIsolate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | v8::Handle<v8::Value> V8TestInterface::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
ExceptionCode ec = 0;
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
ScriptExecutionContext* context = getScriptExecutionContext();
if (!context)
return V8Proxy::throwError(V8Proxy::ReferenceError, "TestInterface constructor's associated context is not available", args.GetIsolate());
RefPtr<TestInterface> impl = TestInterface::create(context, str1, str2, ec);
v8::Handle<v8::Object> wrapper = args.Holder();
if (ec)
goto fail;
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate());
return args.Holder();
fail:
return throwError(ec, args.GetIsolate());
}
| 171,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (!mTimeToSample.empty() || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug
28076789.
Detail: Before the original fix
(Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the
code allowed a time-to-sample table size to be 0. The change
made in that fix disallowed such situation, which in fact should
be allowed. This current patch allows it again while maintaining
the security of the previous fix.
Bug: 28288202
Bug: 28076789
Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295
CWE ID: CWE-20 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mHasTimeToSample || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
mHasTimeToSample = true;
return OK;
}
| 173,773 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = ext4_inode_aio(inode);
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical "
"block %llu, max_blocks %u, flags %x, allocated %u\n",
inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
flags, allocated);
ext4_ext_show_leaf(inode, path);
trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
newblock);
/* get_block() before submit the IO, split the extent */
if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
ret = ext4_split_unwritten_extents(handle, inode, map,
path, flags);
if (ret <= 0)
goto out;
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to conversion to written when IO is
* completed
*/
if (io)
ext4_set_io_unwritten_flag(inode, io);
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
if (ext4_should_dioread_nolock(inode))
map->m_flags |= EXT4_MAP_UNINIT;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
ret = ext4_convert_unwritten_extents_endio(handle, inode,
path);
if (ret >= 0) {
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, map->m_len);
} else
err = ret;
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > map->m_len) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + map->m_len,
allocated - map->m_len);
allocated = map->m_len;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
unsigned int reserved_clusters;
reserved_clusters = get_reserved_cluster_alloc(inode,
map->m_lblk, map->m_len);
if (reserved_clusters)
ext4_da_update_reserve_space(inode,
reserved_clusters,
0);
}
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
map->m_len);
if (err < 0)
goto out2;
}
out1:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_pblk = newblock;
map->m_len = allocated;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-362 | ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path, int flags,
unsigned int allocated, ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = ext4_inode_aio(inode);
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical "
"block %llu, max_blocks %u, flags %x, allocated %u\n",
inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
flags, allocated);
ext4_ext_show_leaf(inode, path);
trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
newblock);
/* get_block() before submit the IO, split the extent */
if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
ret = ext4_split_unwritten_extents(handle, inode, map,
path, flags);
if (ret <= 0)
goto out;
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to conversion to written when IO is
* completed
*/
if (io)
ext4_set_io_unwritten_flag(inode, io);
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
if (ext4_should_dioread_nolock(inode))
map->m_flags |= EXT4_MAP_UNINIT;
goto out;
}
/* IO end_io complete, convert the filled extent to written */
if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
path);
if (ret >= 0) {
ext4_update_inode_fsync_trans(handle, inode, 1);
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, map->m_len);
} else
err = ret;
goto out2;
}
/* buffered IO case */
/*
* repeat fallocate creation request
* we already have an unwritten extent
*/
if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
goto map_out;
/* buffered READ or buffered write_begin() lookup */
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
/*
* We have blocks reserved already. We
* return allocated blocks so that delalloc
* won't do block reservation for us. But
* the buffer head will be unmapped so that
* a read from the block returns 0s.
*/
map->m_flags |= EXT4_MAP_UNWRITTEN;
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
map->m_flags |= EXT4_MAP_NEW;
/*
* if we allocated more blocks than requested
* we need to make sure we unmap the extra block
* allocated. The actual needed block will get
* unmapped later when we find the buffer_head marked
* new.
*/
if (allocated > map->m_len) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + map->m_len,
allocated - map->m_len);
allocated = map->m_len;
}
/*
* If we have done fallocate with the offset that is already
* delayed allocated, we would have block reservation
* and quota reservation done in the delayed write path.
* But fallocate would have already updated quota and block
* count for this offset. So cancel these reservation
*/
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
unsigned int reserved_clusters;
reserved_clusters = get_reserved_cluster_alloc(inode,
map->m_lblk, map->m_len);
if (reserved_clusters)
ext4_da_update_reserve_space(inode,
reserved_clusters,
0);
}
map_out:
map->m_flags |= EXT4_MAP_MAPPED;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
map->m_len);
if (err < 0)
goto out2;
}
out1:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_pblk = newblock;
map->m_len = allocated;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
| 165,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (data >= (limit - 2))
return;
data += 2;
if (data > (limit - 4))
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (data + size > limit)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (data + len1 + len2 != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (data + len != limit)
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
Commit Message:
CWE ID: CWE-190 | static void ssl_check_for_safari(SSL *s, const unsigned char *data,
const unsigned char *limit)
{
unsigned short type, size;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
};
/* The following is only present in TLS 1.2 */
static const unsigned char kSafariTLS12ExtensionsBlock[] = {
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
if (limit - data <= 2)
return;
data += 2;
if (limit - data < 4)
return;
n2s(data, type);
n2s(data, size);
if (type != TLSEXT_TYPE_server_name)
return;
if (limit - data < size)
return;
data += size;
if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
const size_t len1 = sizeof(kSafariExtensionsBlock);
const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
if (limit - data != (int)(len1 + len2))
return;
if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
return;
if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
return;
} else {
const size_t len = sizeof(kSafariExtensionsBlock);
if (limit - data != (int)(len))
return;
if (memcmp(data, kSafariExtensionsBlock, len) != 0)
return;
}
s->s3->is_probably_safari = 1;
}
| 165,202 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 BlockEntry::GetIndex() const
{
return m_index;
}
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 BlockEntry::GetIndex() const
| 174,329 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
Commit Message: Fix integer overflows in recovery procedure.
Bug: 26960931
Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf
(cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b)
CWE ID: CWE-189 | static int sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
if (pMap->ranges == NULL) {
LOGE("malloc failed: %s\n", strerror(errno));
munmap(memPtr, length);
return -1;
}
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
| 173,904 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AudioOutputAuthorizationHandler::AudioOutputAuthorizationHandler(
media::AudioManager* audio_manager,
MediaStreamManager* media_stream_manager,
int render_process_id,
const std::string& salt)
: audio_manager_(audio_manager),
media_stream_manager_(media_stream_manager),
permission_checker_(base::MakeUnique<MediaDevicesPermissionChecker>()),
render_process_id_(render_process_id),
salt_(salt),
weak_factory_(this) {
DCHECK(media_stream_manager_);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioOutputAuthorizationHandler::AudioOutputAuthorizationHandler(
media::AudioSystem* audio_system,
MediaStreamManager* media_stream_manager,
int render_process_id,
const std::string& salt)
: audio_system_(audio_system),
media_stream_manager_(media_stream_manager),
permission_checker_(base::MakeUnique<MediaDevicesPermissionChecker>()),
render_process_id_(render_process_id),
salt_(salt),
weak_factory_(this) {
DCHECK(media_stream_manager_);
}
| 171,980 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: kg_seal_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count,
int toktype)
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
if (qop_req != 0) {
*minor_status = (OM_uint32)G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *)context_handle;
if (!ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) {
/* may be more sensible to return an error here */
conf_req_flag = FALSE;
}
context = ctx->k5_context;
switch (ctx->proto) {
case 0:
code = make_seal_token_v1_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
case 1:
code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
default:
code = G_UNKNOWN_QOP;
break;
}
if (code != 0) {
*minor_status = code;
save_error_info(*minor_status, context);
return GSS_S_FAILURE;
}
*minor_status = 0;
return GSS_S_COMPLETE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | kg_seal_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count,
int toktype)
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
if (qop_req != 0) {
*minor_status = (OM_uint32)G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *)context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) {
/* may be more sensible to return an error here */
conf_req_flag = FALSE;
}
context = ctx->k5_context;
switch (ctx->proto) {
case 0:
code = make_seal_token_v1_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
case 1:
code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
default:
code = G_UNKNOWN_QOP;
break;
}
if (code != 0) {
*minor_status = code;
save_error_info(*minor_status, context);
return GSS_S_FAILURE;
}
*minor_status = 0;
return GSS_S_COMPLETE;
}
| 166,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 InitPrefMembers() {
settings_->InitPrefMembers();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void InitPrefMembers() {
| 172,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper,
NaClSubprocess* subprocess,
const Manifest* manifest,
bool should_report_uma,
ErrorInfo* error_info,
pp::CompletionCallback init_done_cb,
pp::CompletionCallback crash_cb) {
ServiceRuntime* new_service_runtime =
new ServiceRuntime(this, manifest, should_report_uma, init_done_cb,
crash_cb);
subprocess->set_service_runtime(new_service_runtime);
PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n",
static_cast<void*>(new_service_runtime)));
if (NULL == new_service_runtime) {
error_info->SetReport(ERROR_SEL_LDR_INIT,
"sel_ldr init failure " + subprocess->description());
return false;
}
bool service_runtime_started =
new_service_runtime->Start(wrapper,
error_info,
manifest_base_url());
PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n",
service_runtime_started));
if (!service_runtime_started) {
return false;
}
const PPB_NaCl_Private* ppb_nacl = GetNaclInterface();
if (ppb_nacl->StartPpapiProxy(pp_instance())) {
using_ipc_proxy_ = true;
CHECK(init_done_cb.pp_completion_callback().func != NULL);
PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n"));
pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK);
}
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper,
NaClSubprocess* subprocess,
const Manifest* manifest,
bool should_report_uma,
ErrorInfo* error_info,
pp::CompletionCallback init_done_cb,
pp::CompletionCallback crash_cb) {
ServiceRuntime* new_service_runtime =
new ServiceRuntime(this, manifest, should_report_uma, init_done_cb,
crash_cb);
subprocess->set_service_runtime(new_service_runtime);
PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n",
static_cast<void*>(new_service_runtime)));
if (NULL == new_service_runtime) {
error_info->SetReport(ERROR_SEL_LDR_INIT,
"sel_ldr init failure " + subprocess->description());
return false;
}
bool service_runtime_started =
new_service_runtime->Start(wrapper, error_info, manifest_base_url());
PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n",
service_runtime_started));
if (!service_runtime_started) {
return false;
}
return true;
}
| 170,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns,
struct user_namespace *user_ns, struct fs_struct *fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old = mnt_ns->root;
struct mount *new;
int copy_flags;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
down_write(&namespace_sem);
/* First pass: copy the tree topology */
copy_flags = CL_COPY_ALL | CL_EXPIRE;
if (user_ns != mnt_ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
up_write(&namespace_sem);
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
br_write_lock(&vfsmount_lock);
list_add_tail(&new_ns->list, &new->mnt_list);
br_write_unlock(&vfsmount_lock);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (fs) {
if (&p->mnt == fs->root.mnt) {
fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == fs->pwd.mnt) {
fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
}
up_write(&namespace_sem);
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
Commit Message: vfs: Carefully propogate mounts across user namespaces
As a matter of policy MNT_READONLY should not be changable if the
original mounter had more privileges than creator of the mount
namespace.
Add the flag CL_UNPRIVILEGED to note when we are copying a mount from
a mount namespace that requires more privileges to a mount namespace
that requires fewer privileges.
When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT
if any of the mnt flags that should never be changed are set.
This protects both mount propagation and the initial creation of a less
privileged mount namespace.
Cc: [email protected]
Acked-by: Serge Hallyn <[email protected]>
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns,
struct user_namespace *user_ns, struct fs_struct *fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old = mnt_ns->root;
struct mount *new;
int copy_flags;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
down_write(&namespace_sem);
/* First pass: copy the tree topology */
copy_flags = CL_COPY_ALL | CL_EXPIRE;
if (user_ns != mnt_ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
up_write(&namespace_sem);
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
br_write_lock(&vfsmount_lock);
list_add_tail(&new_ns->list, &new->mnt_list);
br_write_unlock(&vfsmount_lock);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (fs) {
if (&p->mnt == fs->root.mnt) {
fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == fs->pwd.mnt) {
fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
}
up_write(&namespace_sem);
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
| 166,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 av_reallocp_array(void *ptr, size_t nmemb, size_t size)
{
void **ptrptr = ptr;
*ptrptr = av_realloc_f(*ptrptr, nmemb, size);
if (!*ptrptr && !(nmemb && size))
return AVERROR(ENOMEM);
return 0;
}
Commit Message: avutil/mem: Fix flipped condition
Fixes return code and later null pointer dereference
Found-by: Laurent Butti <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: | int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
{
void **ptrptr = ptr;
*ptrptr = av_realloc_f(*ptrptr, nmemb, size);
if (!*ptrptr && nmemb && size)
return AVERROR(ENOMEM);
return 0;
}
| 165,995 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh,
char **target)
{
uint32_t data[1024];
uint32_t *p;
uint32_t len;
struct packet *nfs_packet;
/*
* struct READLINK3args {
* nfs_fh3 symlink;
* };
*
* struct READLINK3resok {
* post_op_attr symlink_attributes;
* nfspath3 data;
* };
*
* struct READLINK3resfail {
* post_op_attr symlink_attributes;
* }
*
* union READLINK3res switch (nfsstat3 status) {
* case NFS3_OK:
* READLINK3resok resok;
* default:
* READLINK3resfail resfail;
* };
*/
p = &(data[0]);
p = rpc_add_credentials(p);
p = nfs_add_fh3(p, fh);
len = p - &(data[0]);
nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len);
if (IS_ERR(nfs_packet))
return PTR_ERR(nfs_packet);
p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4;
p = nfs_read_post_op_attr(p, NULL);
len = ntoh32(net_read_uint32(p)); /* new path length */
p++;
*target = xzalloc(len + 1);
return 0;
}
Commit Message:
CWE ID: CWE-119 | static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh,
char **target)
{
uint32_t data[1024];
uint32_t *p;
uint32_t len;
struct packet *nfs_packet;
/*
* struct READLINK3args {
* nfs_fh3 symlink;
* };
*
* struct READLINK3resok {
* post_op_attr symlink_attributes;
* nfspath3 data;
* };
*
* struct READLINK3resfail {
* post_op_attr symlink_attributes;
* }
*
* union READLINK3res switch (nfsstat3 status) {
* case NFS3_OK:
* READLINK3resok resok;
* default:
* READLINK3resfail resfail;
* };
*/
p = &(data[0]);
p = rpc_add_credentials(p);
p = nfs_add_fh3(p, fh);
len = p - &(data[0]);
nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len);
if (IS_ERR(nfs_packet))
return PTR_ERR(nfs_packet);
p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4;
p = nfs_read_post_op_attr(p, NULL);
len = ntoh32(net_read_uint32(p)); /* new path length */
len = max_t(unsigned int, len,
nfs_packet->len - sizeof(struct rpc_reply) - sizeof(uint32_t));
p++;
*target = xzalloc(len + 1);
return 0;
}
| 164,624 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
xsltStyleItemApplyTemplatesPtr comp =
(xsltStyleItemApplyTemplatesPtr) castedComp;
#else
xsltStylePreCompPtr comp = castedComp;
#endif
int i;
xmlNodePtr cur, delNode = NULL, oldContextNode;
xmlNodeSetPtr list = NULL, oldList;
xsltStackElemPtr withParams = NULL;
int oldXPProximityPosition, oldXPContextSize, oldXPNsNr;
const xmlChar *oldMode, *oldModeURI;
xmlDocPtr oldXPDoc;
xsltDocumentPtr oldDocInfo;
xmlXPathContextPtr xpctxt;
xmlNsPtr *oldXPNamespaces;
if (comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:apply-templates : compilation failed\n");
return;
}
if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL))
return;
#ifdef WITH_XSLT_DEBUG_PROCESS
if ((node != NULL) && (node->name != NULL))
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: node: '%s'\n", node->name));
#endif
xpctxt = ctxt->xpathCtxt;
/*
* Save context states.
*/
oldContextNode = ctxt->node;
oldMode = ctxt->mode;
oldModeURI = ctxt->modeURI;
oldDocInfo = ctxt->document;
oldList = ctxt->nodeList;
/*
* The xpath context size and proximity position, as
* well as the xpath and context documents, may be changed
* so we save their initial state and will restore on exit
*/
oldXPContextSize = xpctxt->contextSize;
oldXPProximityPosition = xpctxt->proximityPosition;
oldXPDoc = xpctxt->doc;
oldXPNsNr = xpctxt->nsNr;
oldXPNamespaces = xpctxt->namespaces;
/*
* Set up contexts.
*/
ctxt->mode = comp->mode;
ctxt->modeURI = comp->modeURI;
if (comp->select != NULL) {
xmlXPathObjectPtr res = NULL;
if (comp->comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:apply-templates : compilation failed\n");
goto error;
}
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: select %s\n", comp->select));
#endif
/*
* Set up XPath.
*/
xpctxt->node = node; /* Set the "context node" */
#ifdef XSLT_REFACTORED
if (comp->inScopeNs != NULL) {
xpctxt->namespaces = comp->inScopeNs->list;
xpctxt->nsNr = comp->inScopeNs->xpathNumber;
} else {
xpctxt->namespaces = NULL;
xpctxt->nsNr = 0;
}
#else
xpctxt->namespaces = comp->nsList;
xpctxt->nsNr = comp->nsNr;
#endif
res = xmlXPathCompiledEval(comp->comp, xpctxt);
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
if (res != NULL) {
if (res->type == XPATH_NODESET) {
list = res->nodesetval; /* consume the node set */
res->nodesetval = NULL;
} else {
xsltTransformError(ctxt, NULL, inst,
"The 'select' expression did not evaluate to a "
"node set.\n");
ctxt->state = XSLT_STATE_STOPPED;
xmlXPathFreeObject(res);
goto error;
}
xmlXPathFreeObject(res);
/*
* Note: An xsl:apply-templates with a 'select' attribute,
* can change the current source doc.
*/
} else {
xsltTransformError(ctxt, NULL, inst,
"Failed to evaluate the 'select' expression.\n");
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
if (list == NULL) {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: select didn't evaluate to a node list\n"));
#endif
goto exit;
}
/*
*
* NOTE: Previously a document info (xsltDocument) was
* created and attached to the Result Tree Fragment.
* But such a document info is created on demand in
* xsltKeyFunction() (functions.c), so we need to create
* it here beforehand.
* In order to take care of potential keys we need to
* do some extra work for the case when a Result Tree Fragment
* is converted into a nodeset (e.g. exslt:node-set()) :
* We attach a "pseudo-doc" (xsltDocument) to _private.
* This xsltDocument, together with the keyset, will be freed
* when the Result Tree Fragment is freed.
*
*/
#if 0
if ((ctxt->nbKeys > 0) &&
(list->nodeNr != 0) &&
(list->nodeTab[0]->doc != NULL) &&
XSLT_IS_RES_TREE_FRAG(list->nodeTab[0]->doc))
{
/*
* NOTE that it's also OK if @effectiveDocInfo will be
* set to NULL.
*/
isRTF = 1;
effectiveDocInfo = list->nodeTab[0]->doc->_private;
}
#endif
} else {
/*
* Build an XPath node set with the children
*/
list = xmlXPathNodeSetCreate(NULL);
if (list == NULL)
goto error;
if (node->type != XML_NAMESPACE_DECL)
cur = node->children;
else
cur = NULL;
while (cur != NULL) {
switch (cur->type) {
case XML_TEXT_NODE:
if ((IS_BLANK_NODE(cur)) &&
(cur->parent != NULL) &&
(cur->parent->type == XML_ELEMENT_NODE) &&
(ctxt->style->stripSpaces != NULL)) {
const xmlChar *val;
if (cur->parent->ns != NULL) {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
cur->parent->name,
cur->parent->ns->href);
if (val == NULL) {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
BAD_CAST "*",
cur->parent->ns->href);
}
} else {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
cur->parent->name, NULL);
}
if ((val != NULL) &&
(xmlStrEqual(val, (xmlChar *) "strip"))) {
delNode = cur;
break;
}
}
/* no break on purpose */
case XML_ELEMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
xmlXPathNodeSetAddUnique(list, cur);
break;
case XML_DTD_NODE:
/* Unlink the DTD, it's still reachable
* using doc->intSubset */
if (cur->next != NULL)
cur->next->prev = cur->prev;
if (cur->prev != NULL)
cur->prev->next = cur->next;
break;
case XML_NAMESPACE_DECL:
break;
default:
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: skipping cur type %d\n",
cur->type));
#endif
delNode = cur;
}
cur = cur->next;
if (delNode != NULL) {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: removing ignorable blank cur\n"));
#endif
xmlUnlinkNode(delNode);
xmlFreeNode(delNode);
delNode = NULL;
}
}
}
#ifdef WITH_XSLT_DEBUG_PROCESS
if (list != NULL)
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: list of %d nodes\n", list->nodeNr));
#endif
if ((list == NULL) || (list->nodeNr == 0))
goto exit;
/*
* Set the context's node set and size; this is also needed for
* for xsltDoSortFunction().
*/
ctxt->nodeList = list;
/*
* Process xsl:with-param and xsl:sort instructions.
* (The code became so verbose just to avoid the
* xmlNodePtr sorts[XSLT_MAX_SORT] if there's no xsl:sort)
* BUG TODO: We are not using namespaced potentially defined on the
* xsl:sort or xsl:with-param elements; XPath expression might fail.
*/
if (inst->children) {
xsltStackElemPtr param;
cur = inst->children;
while (cur) {
#ifdef WITH_DEBUGGER
if (ctxt->debugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, node, NULL, ctxt);
#endif
if (ctxt->state == XSLT_STATE_STOPPED)
break;
if (cur->type == XML_TEXT_NODE) {
cur = cur->next;
continue;
}
if (! IS_XSLT_ELEM(cur))
break;
if (IS_XSLT_NAME(cur, "with-param")) {
param = xsltParseStylesheetCallerParam(ctxt, cur);
if (param != NULL) {
param->next = withParams;
withParams = param;
}
}
if (IS_XSLT_NAME(cur, "sort")) {
xsltTemplatePtr oldCurTempRule =
ctxt->currentTemplateRule;
int nbsorts = 0;
xmlNodePtr sorts[XSLT_MAX_SORT];
sorts[nbsorts++] = cur;
while (cur) {
#ifdef WITH_DEBUGGER
if (ctxt->debugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, node, NULL, ctxt);
#endif
if (ctxt->state == XSLT_STATE_STOPPED)
break;
if (cur->type == XML_TEXT_NODE) {
cur = cur->next;
continue;
}
if (! IS_XSLT_ELEM(cur))
break;
if (IS_XSLT_NAME(cur, "with-param")) {
param = xsltParseStylesheetCallerParam(ctxt, cur);
if (param != NULL) {
param->next = withParams;
withParams = param;
}
}
if (IS_XSLT_NAME(cur, "sort")) {
if (nbsorts >= XSLT_MAX_SORT) {
xsltTransformError(ctxt, NULL, cur,
"The number (%d) of xsl:sort instructions exceeds the "
"maximum allowed by this processor's settings.\n",
nbsorts);
ctxt->state = XSLT_STATE_STOPPED;
break;
} else {
sorts[nbsorts++] = cur;
}
}
cur = cur->next;
}
/*
* The "current template rule" is cleared for xsl:sort.
*/
ctxt->currentTemplateRule = NULL;
/*
* Sort.
*/
xsltDoSortFunction(ctxt, sorts, nbsorts);
ctxt->currentTemplateRule = oldCurTempRule;
break;
}
cur = cur->next;
}
}
xpctxt->contextSize = list->nodeNr;
/*
* Apply templates for all selected source nodes.
*/
for (i = 0; i < list->nodeNr; i++) {
cur = list->nodeTab[i];
/*
* The node becomes the "current node".
*/
ctxt->node = cur;
/*
* An xsl:apply-templates can change the current context doc.
* OPTIMIZE TODO: Get rid of the need to set the context doc.
*/
if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL))
xpctxt->doc = cur->doc;
xpctxt->proximityPosition = i + 1;
/*
* Find and apply a template for this node.
*/
xsltProcessOneNode(ctxt, cur, withParams);
}
exit:
error:
/*
* Free the parameter list.
*/
if (withParams != NULL)
xsltFreeStackElemList(withParams);
if (list != NULL)
xmlXPathFreeNodeSet(list);
/*
* Restore context states.
*/
xpctxt->nsNr = oldXPNsNr;
xpctxt->namespaces = oldXPNamespaces;
xpctxt->doc = oldXPDoc;
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
ctxt->document = oldDocInfo;
ctxt->nodeList = oldList;
ctxt->node = oldContextNode;
ctxt->mode = oldMode;
ctxt->modeURI = oldModeURI;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
xsltStyleItemApplyTemplatesPtr comp =
(xsltStyleItemApplyTemplatesPtr) castedComp;
#else
xsltStylePreCompPtr comp = castedComp;
#endif
int i;
xmlNodePtr cur, delNode = NULL, oldContextNode;
xmlNodeSetPtr list = NULL, oldList;
xsltStackElemPtr withParams = NULL;
int oldXPProximityPosition, oldXPContextSize;
const xmlChar *oldMode, *oldModeURI;
xmlDocPtr oldXPDoc;
xsltDocumentPtr oldDocInfo;
xmlXPathContextPtr xpctxt;
if (comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:apply-templates : compilation failed\n");
return;
}
if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL))
return;
#ifdef WITH_XSLT_DEBUG_PROCESS
if ((node != NULL) && (node->name != NULL))
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: node: '%s'\n", node->name));
#endif
xpctxt = ctxt->xpathCtxt;
/*
* Save context states.
*/
oldContextNode = ctxt->node;
oldMode = ctxt->mode;
oldModeURI = ctxt->modeURI;
oldDocInfo = ctxt->document;
oldList = ctxt->nodeList;
/*
* The xpath context size and proximity position, as
* well as the xpath and context documents, may be changed
* so we save their initial state and will restore on exit
*/
oldXPContextSize = xpctxt->contextSize;
oldXPProximityPosition = xpctxt->proximityPosition;
oldXPDoc = xpctxt->doc;
/*
* Set up contexts.
*/
ctxt->mode = comp->mode;
ctxt->modeURI = comp->modeURI;
if (comp->select != NULL) {
xmlXPathObjectPtr res = NULL;
if (comp->comp == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:apply-templates : compilation failed\n");
goto error;
}
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: select %s\n", comp->select));
#endif
res = xsltPreCompEval(ctxt, node, comp);
if (res != NULL) {
if (res->type == XPATH_NODESET) {
list = res->nodesetval; /* consume the node set */
res->nodesetval = NULL;
} else {
xsltTransformError(ctxt, NULL, inst,
"The 'select' expression did not evaluate to a "
"node set.\n");
ctxt->state = XSLT_STATE_STOPPED;
xmlXPathFreeObject(res);
goto error;
}
xmlXPathFreeObject(res);
/*
* Note: An xsl:apply-templates with a 'select' attribute,
* can change the current source doc.
*/
} else {
xsltTransformError(ctxt, NULL, inst,
"Failed to evaluate the 'select' expression.\n");
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
if (list == NULL) {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: select didn't evaluate to a node list\n"));
#endif
goto exit;
}
/*
*
* NOTE: Previously a document info (xsltDocument) was
* created and attached to the Result Tree Fragment.
* But such a document info is created on demand in
* xsltKeyFunction() (functions.c), so we need to create
* it here beforehand.
* In order to take care of potential keys we need to
* do some extra work for the case when a Result Tree Fragment
* is converted into a nodeset (e.g. exslt:node-set()) :
* We attach a "pseudo-doc" (xsltDocument) to _private.
* This xsltDocument, together with the keyset, will be freed
* when the Result Tree Fragment is freed.
*
*/
#if 0
if ((ctxt->nbKeys > 0) &&
(list->nodeNr != 0) &&
(list->nodeTab[0]->doc != NULL) &&
XSLT_IS_RES_TREE_FRAG(list->nodeTab[0]->doc))
{
/*
* NOTE that it's also OK if @effectiveDocInfo will be
* set to NULL.
*/
isRTF = 1;
effectiveDocInfo = list->nodeTab[0]->doc->_private;
}
#endif
} else {
/*
* Build an XPath node set with the children
*/
list = xmlXPathNodeSetCreate(NULL);
if (list == NULL)
goto error;
if (node->type != XML_NAMESPACE_DECL)
cur = node->children;
else
cur = NULL;
while (cur != NULL) {
switch (cur->type) {
case XML_TEXT_NODE:
if ((IS_BLANK_NODE(cur)) &&
(cur->parent != NULL) &&
(cur->parent->type == XML_ELEMENT_NODE) &&
(ctxt->style->stripSpaces != NULL)) {
const xmlChar *val;
if (cur->parent->ns != NULL) {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
cur->parent->name,
cur->parent->ns->href);
if (val == NULL) {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
BAD_CAST "*",
cur->parent->ns->href);
}
} else {
val = (const xmlChar *)
xmlHashLookup2(ctxt->style->stripSpaces,
cur->parent->name, NULL);
}
if ((val != NULL) &&
(xmlStrEqual(val, (xmlChar *) "strip"))) {
delNode = cur;
break;
}
}
/* no break on purpose */
case XML_ELEMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
xmlXPathNodeSetAddUnique(list, cur);
break;
case XML_DTD_NODE:
/* Unlink the DTD, it's still reachable
* using doc->intSubset */
if (cur->next != NULL)
cur->next->prev = cur->prev;
if (cur->prev != NULL)
cur->prev->next = cur->next;
break;
case XML_NAMESPACE_DECL:
break;
default:
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: skipping cur type %d\n",
cur->type));
#endif
delNode = cur;
}
cur = cur->next;
if (delNode != NULL) {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: removing ignorable blank cur\n"));
#endif
xmlUnlinkNode(delNode);
xmlFreeNode(delNode);
delNode = NULL;
}
}
}
#ifdef WITH_XSLT_DEBUG_PROCESS
if (list != NULL)
XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext,
"xsltApplyTemplates: list of %d nodes\n", list->nodeNr));
#endif
if ((list == NULL) || (list->nodeNr == 0))
goto exit;
/*
* Set the context's node set and size; this is also needed for
* for xsltDoSortFunction().
*/
ctxt->nodeList = list;
/*
* Process xsl:with-param and xsl:sort instructions.
* (The code became so verbose just to avoid the
* xmlNodePtr sorts[XSLT_MAX_SORT] if there's no xsl:sort)
* BUG TODO: We are not using namespaced potentially defined on the
* xsl:sort or xsl:with-param elements; XPath expression might fail.
*/
if (inst->children) {
xsltStackElemPtr param;
cur = inst->children;
while (cur) {
#ifdef WITH_DEBUGGER
if (ctxt->debugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, node, NULL, ctxt);
#endif
if (ctxt->state == XSLT_STATE_STOPPED)
break;
if (cur->type == XML_TEXT_NODE) {
cur = cur->next;
continue;
}
if (! IS_XSLT_ELEM(cur))
break;
if (IS_XSLT_NAME(cur, "with-param")) {
param = xsltParseStylesheetCallerParam(ctxt, cur);
if (param != NULL) {
param->next = withParams;
withParams = param;
}
}
if (IS_XSLT_NAME(cur, "sort")) {
xsltTemplatePtr oldCurTempRule =
ctxt->currentTemplateRule;
int nbsorts = 0;
xmlNodePtr sorts[XSLT_MAX_SORT];
sorts[nbsorts++] = cur;
while (cur) {
#ifdef WITH_DEBUGGER
if (ctxt->debugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, node, NULL, ctxt);
#endif
if (ctxt->state == XSLT_STATE_STOPPED)
break;
if (cur->type == XML_TEXT_NODE) {
cur = cur->next;
continue;
}
if (! IS_XSLT_ELEM(cur))
break;
if (IS_XSLT_NAME(cur, "with-param")) {
param = xsltParseStylesheetCallerParam(ctxt, cur);
if (param != NULL) {
param->next = withParams;
withParams = param;
}
}
if (IS_XSLT_NAME(cur, "sort")) {
if (nbsorts >= XSLT_MAX_SORT) {
xsltTransformError(ctxt, NULL, cur,
"The number (%d) of xsl:sort instructions exceeds the "
"maximum allowed by this processor's settings.\n",
nbsorts);
ctxt->state = XSLT_STATE_STOPPED;
break;
} else {
sorts[nbsorts++] = cur;
}
}
cur = cur->next;
}
/*
* The "current template rule" is cleared for xsl:sort.
*/
ctxt->currentTemplateRule = NULL;
/*
* Sort.
*/
xsltDoSortFunction(ctxt, sorts, nbsorts);
ctxt->currentTemplateRule = oldCurTempRule;
break;
}
cur = cur->next;
}
}
xpctxt->contextSize = list->nodeNr;
/*
* Apply templates for all selected source nodes.
*/
for (i = 0; i < list->nodeNr; i++) {
cur = list->nodeTab[i];
/*
* The node becomes the "current node".
*/
ctxt->node = cur;
/*
* An xsl:apply-templates can change the current context doc.
* OPTIMIZE TODO: Get rid of the need to set the context doc.
*/
if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL))
xpctxt->doc = cur->doc;
xpctxt->proximityPosition = i + 1;
/*
* Find and apply a template for this node.
*/
xsltProcessOneNode(ctxt, cur, withParams);
}
exit:
error:
/*
* Free the parameter list.
*/
if (withParams != NULL)
xsltFreeStackElemList(withParams);
if (list != NULL)
xmlXPathFreeNodeSet(list);
/*
* Restore context states.
*/
xpctxt->doc = oldXPDoc;
xpctxt->contextSize = oldXPContextSize;
xpctxt->proximityPosition = oldXPProximityPosition;
ctxt->document = oldDocInfo;
ctxt->nodeList = oldList;
ctxt->node = oldContextNode;
ctxt->mode = oldMode;
ctxt->modeURI = oldModeURI;
}
| 173,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
Commit Message:
CWE ID: CWE-119 | tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( p + 4 > p_limit ||
num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
| 164,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ExtensionTtsSpeakCompletedFunction::RunImpl() {
int request_id;
std::string error_message;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id));
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &error_message));
ExtensionTtsController::GetInstance()->OnSpeechFinished(
request_id, error_message);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ExtensionTtsSpeakCompletedFunction::RunImpl() {
bool ExtensionTtsGetVoicesFunction::RunImpl() {
result_.reset(ExtensionTtsController::GetInstance()->GetVoices(profile()));
return true;
}
| 170,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
int nmi, struct perf_sample_data *data,
struct pt_regs *regs)
{
struct hw_perf_event *hwc = &event->hw;
int throttle = 0;
data->period = event->hw.last_period;
if (!overflow)
overflow = perf_swevent_set_period(event);
if (hwc->interrupts == MAX_INTERRUPTS)
return;
for (; overflow; overflow--) {
if (__perf_event_overflow(event, nmi, throttle,
data, regs)) {
/*
* We inhibit the overflow from happening when
* hwc->interrupts == MAX_INTERRUPTS.
*/
break;
}
throttle = 1;
}
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct hw_perf_event *hwc = &event->hw;
int throttle = 0;
data->period = event->hw.last_period;
if (!overflow)
overflow = perf_swevent_set_period(event);
if (hwc->interrupts == MAX_INTERRUPTS)
return;
for (; overflow; overflow--) {
if (__perf_event_overflow(event, throttle,
data, regs)) {
/*
* We inhibit the overflow from happening when
* hwc->interrupts == MAX_INTERRUPTS.
*/
break;
}
throttle = 1;
}
}
| 165,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
const char* format;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
Fatal( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%s %s (file `%s')",
face->family_name, face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%s': error 0x%04x",
basename, (FT_UShort)error_code );
break;
}
status.header = (const char *)status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0, status.header,
display->fore_color );
format = "at %g points, first glyph index = %d";
snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num );
if ( FT_HAS_GLYPH_NAMES( face ) )
{
char* p;
int format_len, gindex, size;
size = strlen( status.header_buffer );
p = status.header_buffer + size;
size = 256 - size;
format = ", name = ";
format_len = strlen( format );
if ( size >= format_len + 2 )
{
gindex = status.Num;
strcpy( p, format );
if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) )
*p = '\0';
}
}
status.header = (const char *)status.header_buffer;
grWriteCellString( display->bitmap, 0, HEADER_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
Commit Message:
CWE ID: CWE-119 | write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
const char* format;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
Fatal( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')",
face->family_name, face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%.100s': error 0x%04x",
basename, (FT_UShort)error_code );
break;
}
status.header = (const char *)status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0, status.header,
display->fore_color );
format = "at %g points, first glyph index = %d";
snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num );
if ( FT_HAS_GLYPH_NAMES( face ) )
{
char* p;
int format_len, gindex, size;
size = strlen( status.header_buffer );
p = status.header_buffer + size;
size = 256 - size;
format = ", name = ";
format_len = strlen( format );
if ( size >= format_len + 2 )
{
gindex = status.Num;
strcpy( p, format );
if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) )
*p = '\0';
}
}
status.header = (const char *)status.header_buffer;
grWriteCellString( display->bitmap, 0, HEADER_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
| 164,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Segment::AppendCluster(Cluster* pCluster) {
assert(pCluster);
assert(pCluster->m_index >= 0);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
const long idx = pCluster->m_index;
assert(idx == m_clusterCount);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
if (m_clusterPreloadCount > 0) {
assert(m_clusters);
Cluster** const p = m_clusters + m_clusterCount;
assert(*p);
assert((*p)->m_index < 0);
Cluster** q = p + m_clusterPreloadCount;
assert(q < (m_clusters + size));
for (;;) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | void Segment::AppendCluster(Cluster* pCluster) {
bool Segment::AppendCluster(Cluster* pCluster) {
if (pCluster == NULL || pCluster->m_index < 0)
return false;
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
const long idx = pCluster->m_index;
if (size < count || idx != m_clusterCount)
return false;
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new (std::nothrow) Cluster*[n];
if (qq == NULL)
return false;
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
if (m_clusterPreloadCount > 0) {
Cluster** const p = m_clusters + m_clusterCount;
if (*p == NULL || (*p)->m_index >= 0)
return false;
Cluster** q = p + m_clusterPreloadCount;
if (q >= (m_clusters + size))
return false;
for (;;) {
Cluster** const qq = q - 1;
if ((*qq)->m_index >= 0)
return false;
*q = *qq;
q = qq;
if (q == p)
break;
}
}
m_clusters[idx] = pCluster;
++m_clusterCount;
return true;
}
| 173,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, webPhar)
{
zval *mimeoverride = NULL, *rewrite = NULL;
char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
char *fname, *path_info, *mime_type = NULL, *entry, *pt;
const char *basename;
int fname_len, entry_len, code, index_php_len = 0, not_cgi;
phar_archive_data *phar = NULL;
phar_entry_info *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
return;
}
/* retrieve requested file within phar */
if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
return;
}
#ifdef PHP_WIN32
fname = estrndup(fname, fname_len);
phar_unixify_path_separators(fname, fname_len);
#endif
basename = zend_memrchr(fname, '/', fname_len);
if (!basename) {
basename = fname;
} else {
++basename;
}
if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
if (PG(http_globals)[TRACK_VARS_SERVER]) {
HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
zval **z_script_name, **z_path_info;
if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
IS_STRING != Z_TYPE_PP(z_script_name) ||
!strstr(Z_STRVAL_PP(z_script_name), basename)) {
return;
}
if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
IS_STRING == Z_TYPE_PP(z_path_info)) {
entry_len = Z_STRLEN_PP(z_path_info);
entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
free_pathinfo = 1;
} else {
entry_len = 0;
entry = estrndup("", 0);
path_info = Z_STRVAL_PP(z_script_name);
}
pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
} else {
char *testit;
testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
if (!(pt = strstr(testit, basename))) {
efree(testit);
return;
}
path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
if (path_info) {
entry = path_info;
entry_len = strlen(entry);
spprintf(&path_info, 0, "%s%s", testit, path_info);
free_pathinfo = 1;
} else {
path_info = testit;
free_pathinfo = 1;
entry = estrndup("", 0);
entry_len = 0;
}
pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
}
not_cgi = 0;
} else {
path_info = SG(request_info).request_uri;
if (!(pt = strstr(path_info, basename))) {
/* this can happen with rewrite rules - and we have no idea what to do then, so return */
return;
}
entry_len = strlen(path_info);
entry_len -= (pt - path_info) + (fname_len - (basename - fname));
entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
not_cgi = 1;
}
if (rewrite) {
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *params, *retval_ptr, **zp[1];
MAKE_STD_ZVAL(params);
ZVAL_STRINGL(params, entry, entry_len, 1);
zp[0] = ¶ms;
#if PHP_VERSION_ID < 50300
if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
#else
if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
#endif
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
if (free_pathinfo) {
efree(path_info);
}
return;
}
fci.param_count = 1;
fci.params = zp;
#if PHP_VERSION_ID < 50300
++(params->refcount);
#else
Z_ADDREF_P(params);
#endif
fci.retval_ptr_ptr = &retval_ptr;
if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
if (!EG(exception)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
}
if (free_pathinfo) {
efree(path_info);
}
return;
}
if (!fci.retval_ptr_ptr || !retval_ptr) {
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
switch (Z_TYPE_P(retval_ptr)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(retval_ptr TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
efree(entry);
if (fci.retval_ptr_ptr != &retval_ptr) {
entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
} else {
entry = Z_STRVAL_P(retval_ptr);
entry_len = Z_STRLEN_P(retval_ptr);
}
break;
case IS_BOOL:
phar_do_403(entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
return;
default:
efree(retval_ptr);
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
}
if (entry_len) {
phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
}
if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
efree(entry);
/* direct request */
if (index_php_len) {
entry = index_php;
entry_len = index_php_len;
if (entry[0] != '/') {
spprintf(&entry, 0, "/%s", index_php);
++entry_len;
}
} else {
/* assume "index.php" is starting point */
entry = estrndup("/index.php", sizeof("/index.php"));
entry_len = sizeof("/index.php")-1;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
} else {
char *tmp = NULL, sa = '\0';
sapi_header_line ctr = {0};
ctr.response_code = 301;
ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
ctr.line = "HTTP/1.1 301 Moved Permanently";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
if (not_cgi) {
tmp = strstr(path_info, basename) + fname_len;
sa = *tmp;
*tmp = '\0';
}
ctr.response_code = 0;
if (path_info[strlen(path_info)-1] == '/') {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
} else {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
}
if (not_cgi) {
*tmp = sa;
}
if (free_pathinfo) {
efree(path_info);
}
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
efree(ctr.line);
zend_bailout();
}
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
#ifdef PHP_WIN32
efree(fname);
#endif
zend_bailout();
}
if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
const char *ext = zend_memrchr(entry, '.', entry_len);
zval **val;
if (ext) {
++ext;
if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
switch (Z_TYPE_PP(val)) {
case IS_LONG:
if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
mime_type = "";
code = Z_LVAL_PP(val);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
break;
case IS_STRING:
mime_type = Z_STRVAL_PP(val);
code = PHAR_MIME_OTHER;
break;
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
}
}
}
if (!mime_type) {
code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
}
ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto void Phar::mungServer(array munglist)
* Defines a list of up to 4 $_SERVER variables that should be modified for execution
* to mask the presence of the phar archive. This should be used in conjunction with
* Phar::webPhar(), and has no effect otherwise
* SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
*/
PHP_METHOD(Phar, mungServer)
{
zval *mungvalues;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
phar_request_initialize(TSRMLS_C);
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
zval **data = NULL;
if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
return;
}
if (Z_TYPE_PP(data) != IS_STRING) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
}
if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
}
if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
}
}
if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
}
}
}
/* }}} */
/* {{{ proto void Phar::interceptFileFuncs()
* instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
* and return stat on files within the phar for relative paths
*
* Once called, this cannot be reversed, and continue until the end of the request.
*
* This allows legacy scripts to be pharred unmodified
*/
PHP_METHOD(Phar, interceptFileFuncs)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phar_intercept_functions(TSRMLS_C);
}
/* }}} */
/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
* Return a stub that can be used to run a phar-based archive without the phar extension
* indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
* is the web startup filename, and also defaults to "index.php"
*/
PHP_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *stub, *error;
int index_len = 0, webindex_len = 0;
size_t stub_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
return;
}
RETURN_STRINGL(stub, stub_len, 0);
}
/* }}} */
/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
* Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar, mapPhar)
{
char *alias = NULL, *error;
int alias_len = 0;
long dataoffset = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
* Loads any phar archive with an alias */
PHP_METHOD(Phar, loadPhar)
{
char *fname, *alias = NULL, *error;
int fname_len, alias_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto string Phar::apiVersion()
* Returns the api version */
PHP_METHOD(Phar, apiVersion)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
}
/* }}}*/
/* {{{ proto bool Phar::canCompress([int method])
* Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar, canCompress)
{
long method = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
switch (method) {
case PHAR_ENT_COMPRESSED_GZ:
if (PHAR_G(has_zlib)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
case PHAR_ENT_COMPRESSED_BZ2:
if (PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
default:
if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto bool Phar::canWrite()
* Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar, canWrite)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!PHAR_G(readonly));
}
/* }}} */
/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
* Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar, isValidPharFilename)
{
char *fname;
const char *ext_str;
int fname_len, ext_len, is_executable;
zend_bool executable = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
return;
}
is_executable = executable;
RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
}
/* }}} */
#if HAVE_SPL
/**
* from spl_directory
*/
static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar = (phar_archive_data *) object->oth;
if (!phar->is_persistent) {
phar_archive_delref(phar TSRMLS_CC);
}
object->oth = NULL;
}
/* }}} */
/**
* from spl_directory
*/
static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
}
/* }}} */
static spl_other_handler phar_spl_foreign_handler = {
phar_spl_foreign_dtor,
phar_spl_foreign_clone
};
#endif /* HAVE_SPL */
/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
* Construct a Phar archive object
*
* proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
* Construct a PharData archive object
*
* This function is used as the constructor for both the Phar and PharData
* classes, hence the two prototypes above.
*/
PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
/* }}} */
/* {{{ proto array Phar::getSupportedSignatures()
* Return array of supported signature types
*/
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
/* }}} */
/* {{{ proto array Phar::getSupportedCompression()
* Return array of supported comparession algorithms
*/
PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
/* }}} */
/* {{{ proto array Phar::unlinkArchive(string archive)
* Completely remove a phar archive from memory and disk
*/
PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
int fname_len, zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename(TSRMLS_C);
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar TSRMLS_CC);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
/* }}} */
#if HAVE_SPL
#define PHAR_ARCHIVE_OBJECT() \
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!phar_obj->arc.archive) { \
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
"Cannot call method on an uninitialized Phar object"); \
return; \
}
/* {{{ proto void Phar::__destruct()
* if persistent, remove from the cache
*/
PHP_METHOD(Phar, __destruct)
{
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
}
}
/* }}} */
struct _phar_t {
phar_archive_object *p;
zend_class_entry *c;
char *b;
uint l;
zval *ret;
int count;
php_stream *fp;
};
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
{
zval **value;
zend_uchar key_type;
zend_bool close_fp = 1;
ulong int_key;
struct _phar_t *p_obj = (struct _phar_t*) puser;
uint str_key_len, base_len = p_obj->l, fname_len;
phar_entry_data *data;
php_stream *fp;
size_t contents_len;
char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
phar_zstr key;
char *str_key;
zend_class_entry *ce = p_obj->c;
phar_archive_object *phar_obj = p_obj->p;
char *str = "[stream]";
iter->funcs->get_current_data(iter, &value TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (!value) {
/* failure in get_current_data */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (Z_TYPE_PP(value)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(*(value) TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
break;
case IS_RESOURCE:
php_stream_from_zval_no_verify(fp, value);
if (!fp) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') {
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
close_fp = 0;
opened = (char *) estrndup(str, sizeof("[stream]") - 1);
goto after_open_fp;
case IS_OBJECT:
if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
char *test = NULL;
zval dummy;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
if (!base_len) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (intern->type) {
case SPL_FS_DIR:
#if PHP_VERSION_ID >= 60000
test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
#elif PHP_VERSION_ID >= 50300
test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
#else
test = intern->path;
#endif
fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
if (Z_BVAL(dummy)) {
/* ignore directories */
efree(fname);
return ZEND_HASH_APPLY_KEEP;
}
test = expand_filepath(fname, NULL TSRMLS_CC);
efree(fname);
if (test) {
fname = test;
fname_len = strlen(fname);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
save = fname;
goto phar_spl_fileinfo;
case SPL_FS_INFO:
case SPL_FS_FILE:
#if PHP_VERSION_ID >= 60000
if (intern->file_name_type == IS_UNICODE) {
zval zv;
INIT_ZVAL(zv);
Z_UNIVAL(zv) = intern->file_name;
Z_UNILEN(zv) = intern->file_name_len;
Z_TYPE(zv) = IS_UNICODE;
zval_copy_ctor(&zv);
zval_unicode_to_string(&zv TSRMLS_CC);
fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
ezfree(Z_UNIVAL(zv));
} else {
fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
}
#else
fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
#endif
if (!fname) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
fname_len = strlen(fname);
save = fname;
goto phar_spl_fileinfo;
}
}
/* fall-through */
default:
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
fname = Z_STRVAL_PP(value);
fname_len = Z_STRLEN_PP(value);
phar_spl_fileinfo:
if (base_len) {
temp = expand_filepath(base, NULL TSRMLS_CC);
if (!temp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
if (save) {
efree(save);
}
return ZEND_HASH_APPLY_STOP;
}
base = temp;
base_len = strlen(base);
if (strstr(fname, base)) {
str_key_len = fname_len - base_len;
if (str_key_len <= 0) {
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_KEEP;
}
str_key = fname + base_len;
if (*str_key == '/' || *str_key == '\\') {
str_key++;
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
} else {
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') str_key_len--;
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
/* try to open source file, then create internal phar file and copy contents */
fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
if (!fp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
after_open_fp:
if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
/* silently skip any files that would be added to the magic .phar directory */
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
if (opened) {
efree(opened);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_KEEP;
}
if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
efree(error);
if (save) {
efree(save);
}
if (opened) {
efree(opened);
}
if (temp) {
efree(temp);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_STOP;
} else {
if (error) {
efree(error);
}
/* convert to PHAR_UFP */
if (data->internal_file->fp_type == PHAR_MOD) {
php_stream_close(data->internal_file->fp);
}
data->internal_file->fp = NULL;
data->internal_file->fp_type = PHAR_UFP;
data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
data->fp = NULL;
phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
php_stream_tell(p_obj->fp) - data->internal_file->offset;
}
if (close_fp) {
php_stream_close(fp);
}
add_assoc_string(p_obj->ret, str_key, opened, 0);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
phar_entry_delref(data TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
* Construct a phar archive from an existing directory, recursively.
* Optional second parameter is a regular expression for filtering directory contents.
*
* Return value is an array mapping phar index to actual files added.
*/
PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
* Construct a phar archive from an iterator. The iterator must return a series of strings
* that are full paths to files that should be added to the phar. The iterator key should
* be the path that the file will have within the phar archive.
*
* If base directory is specified, then the key will be ignored, and instead the portion of
* the current value minus the base directory will be used
*
* Returned is an array mapping phar index to actual file added
*/
PHP_METHOD(Phar, buildFromIterator)
{
zval *obj;
char *error;
uint base_len = 0;
char *base = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
array_init(return_value);
pass.c = Z_OBJCE_P(obj);
pass.p = phar_obj;
pass.b = base;
pass.l = base_len;
pass.ret = return_value;
pass.count = 0;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto int Phar::count()
* Returns the number of entries in the Phar archive
*/
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
/* }}} */
/* {{{ proto bool Phar::isFileFormat(int format)
* Returns true if the phar archive is based on the tar/zip/phar file format depending
* on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
*/
PHP_METHOD(Phar, isFileFormat)
{
long type;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
RETURN_FALSE;
}
switch (type) {
case PHAR_FORMAT_TAR:
RETURN_BOOL(phar_obj->arc.archive->is_tar);
case PHAR_FORMAT_ZIP:
RETURN_BOOL(phar_obj->arc.archive->is_zip);
case PHAR_FORMAT_PHAR:
RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
}
}
/* }}} */
static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *error;
off_t offset;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
}
return FAILURE;
}
/* copy old contents in entirety */
phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
offset = php_stream_tell(fp);
link = phar_get_link_source(entry TSRMLS_CC);
if (!link) {
link = entry;
}
if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
/* save for potential restore on error */
entry->cfp = entry->fp;
entry->fp = NULL;
}
/* set new location of file contents */
entry->fp_type = PHAR_FP;
entry->offset = offset;
return SUCCESS;
}
/* }}} */
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, newentry;
zval *ret;
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
/* set whole-archive compression and type from parameter */
phar->flags = flags;
phar->is_data = source->is_data;
switch (convert) {
case PHAR_FORMAT_TAR:
phar->is_tar = 1;
break;
case PHAR_FORMAT_ZIP:
phar->is_zip = 1;
break;
default:
phar->is_data = 0;
break;
}
zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
phar->fp = php_stream_fopen_tmpfile();
if (phar->fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
return NULL;
}
phar->fname = source->fname;
phar->fname_len = source->fname_len;
phar->is_temporary_alias = source->is_temporary_alias;
phar->alias = source->alias;
if (source->metadata) {
zval *t;
t = source->metadata;
ALLOC_ZVAL(phar->metadata);
*phar->metadata = *t;
zval_copy_ctor(phar->metadata);
#if PHP_VERSION_ID < 50300
phar->metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(phar->metadata, 1);
#endif
phar->metadata_len = 0;
}
/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\"", source->fname);
return NULL;
}
newentry = *entry;
if (newentry.link) {
newentry.link = estrdup(newentry.link);
goto no_copy;
}
if (newentry.tmp) {
newentry.tmp = estrdup(newentry.tmp);
goto no_copy;
}
newentry.metadata_str.c = 0;
if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
/* exception already thrown */
return NULL;
}
no_copy:
newentry.filename = estrndup(newentry.filename, newentry.filename_len);
if (newentry.metadata) {
zval *t;
t = newentry.metadata;
ALLOC_ZVAL(newentry.metadata);
*newentry.metadata = *t;
zval_copy_ctor(newentry.metadata);
#if PHP_VERSION_ID < 50300
newentry.metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(newentry.metadata, 1);
#endif
newentry.metadata_str.c = NULL;
newentry.metadata_str.len = 0;
}
newentry.is_zip = phar->is_zip;
newentry.is_tar = phar->is_tar;
if (newentry.is_tar) {
newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
}
newentry.is_modified = 1;
newentry.phar = phar;
newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
phar_set_inode(&newentry TSRMLS_CC);
zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
}
if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) {
return ret;
} else {
zend_hash_destroy(&(phar->manifest));
zend_hash_destroy(&(phar->mounted_dirs));
zend_hash_destroy(&(phar->virtual_dirs));
php_stream_close(phar->fp);
efree(phar->fname);
efree(phar);
return NULL;
/* }}} */
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, webPhar)
{
zval *mimeoverride = NULL, *rewrite = NULL;
char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
char *fname, *path_info, *mime_type = NULL, *entry, *pt;
const char *basename;
int fname_len, entry_len, code, index_php_len = 0, not_cgi;
phar_archive_data *phar = NULL;
phar_entry_info *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
return;
}
/* retrieve requested file within phar */
if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
return;
}
#ifdef PHP_WIN32
fname = estrndup(fname, fname_len);
phar_unixify_path_separators(fname, fname_len);
#endif
basename = zend_memrchr(fname, '/', fname_len);
if (!basename) {
basename = fname;
} else {
++basename;
}
if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
if (PG(http_globals)[TRACK_VARS_SERVER]) {
HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
zval **z_script_name, **z_path_info;
if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
IS_STRING != Z_TYPE_PP(z_script_name) ||
!strstr(Z_STRVAL_PP(z_script_name), basename)) {
return;
}
if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
IS_STRING == Z_TYPE_PP(z_path_info)) {
entry_len = Z_STRLEN_PP(z_path_info);
entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
free_pathinfo = 1;
} else {
entry_len = 0;
entry = estrndup("", 0);
path_info = Z_STRVAL_PP(z_script_name);
}
pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
} else {
char *testit;
testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
if (!(pt = strstr(testit, basename))) {
efree(testit);
return;
}
path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
if (path_info) {
entry = path_info;
entry_len = strlen(entry);
spprintf(&path_info, 0, "%s%s", testit, path_info);
free_pathinfo = 1;
} else {
path_info = testit;
free_pathinfo = 1;
entry = estrndup("", 0);
entry_len = 0;
}
pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
}
not_cgi = 0;
} else {
path_info = SG(request_info).request_uri;
if (!(pt = strstr(path_info, basename))) {
/* this can happen with rewrite rules - and we have no idea what to do then, so return */
return;
}
entry_len = strlen(path_info);
entry_len -= (pt - path_info) + (fname_len - (basename - fname));
entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
not_cgi = 1;
}
if (rewrite) {
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *params, *retval_ptr, **zp[1];
MAKE_STD_ZVAL(params);
ZVAL_STRINGL(params, entry, entry_len, 1);
zp[0] = ¶ms;
#if PHP_VERSION_ID < 50300
if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
#else
if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
#endif
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
if (free_pathinfo) {
efree(path_info);
}
return;
}
fci.param_count = 1;
fci.params = zp;
#if PHP_VERSION_ID < 50300
++(params->refcount);
#else
Z_ADDREF_P(params);
#endif
fci.retval_ptr_ptr = &retval_ptr;
if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
if (!EG(exception)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
}
if (free_pathinfo) {
efree(path_info);
}
return;
}
if (!fci.retval_ptr_ptr || !retval_ptr) {
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
switch (Z_TYPE_P(retval_ptr)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(retval_ptr TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
efree(entry);
if (fci.retval_ptr_ptr != &retval_ptr) {
entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
} else {
entry = Z_STRVAL_P(retval_ptr);
entry_len = Z_STRLEN_P(retval_ptr);
}
break;
case IS_BOOL:
phar_do_403(entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
return;
default:
efree(retval_ptr);
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
}
if (entry_len) {
phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
}
if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
efree(entry);
/* direct request */
if (index_php_len) {
entry = index_php;
entry_len = index_php_len;
if (entry[0] != '/') {
spprintf(&entry, 0, "/%s", index_php);
++entry_len;
}
} else {
/* assume "index.php" is starting point */
entry = estrndup("/index.php", sizeof("/index.php"));
entry_len = sizeof("/index.php")-1;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
} else {
char *tmp = NULL, sa = '\0';
sapi_header_line ctr = {0};
ctr.response_code = 301;
ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
ctr.line = "HTTP/1.1 301 Moved Permanently";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
if (not_cgi) {
tmp = strstr(path_info, basename) + fname_len;
sa = *tmp;
*tmp = '\0';
}
ctr.response_code = 0;
if (path_info[strlen(path_info)-1] == '/') {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
} else {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
}
if (not_cgi) {
*tmp = sa;
}
if (free_pathinfo) {
efree(path_info);
}
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
efree(ctr.line);
zend_bailout();
}
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
#ifdef PHP_WIN32
efree(fname);
#endif
zend_bailout();
}
if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
const char *ext = zend_memrchr(entry, '.', entry_len);
zval **val;
if (ext) {
++ext;
if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
switch (Z_TYPE_PP(val)) {
case IS_LONG:
if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
mime_type = "";
code = Z_LVAL_PP(val);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
break;
case IS_STRING:
mime_type = Z_STRVAL_PP(val);
code = PHAR_MIME_OTHER;
break;
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
}
}
}
if (!mime_type) {
code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
}
ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto void Phar::mungServer(array munglist)
* Defines a list of up to 4 $_SERVER variables that should be modified for execution
* to mask the presence of the phar archive. This should be used in conjunction with
* Phar::webPhar(), and has no effect otherwise
* SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
*/
PHP_METHOD(Phar, mungServer)
{
zval *mungvalues;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
phar_request_initialize(TSRMLS_C);
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
zval **data = NULL;
if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
return;
}
if (Z_TYPE_PP(data) != IS_STRING) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
}
if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
}
if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
}
}
if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
}
}
}
/* }}} */
/* {{{ proto void Phar::interceptFileFuncs()
* instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
* and return stat on files within the phar for relative paths
*
* Once called, this cannot be reversed, and continue until the end of the request.
*
* This allows legacy scripts to be pharred unmodified
*/
PHP_METHOD(Phar, interceptFileFuncs)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phar_intercept_functions(TSRMLS_C);
}
/* }}} */
/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
* Return a stub that can be used to run a phar-based archive without the phar extension
* indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
* is the web startup filename, and also defaults to "index.php"
*/
PHP_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *stub, *error;
int index_len = 0, webindex_len = 0;
size_t stub_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
return;
}
RETURN_STRINGL(stub, stub_len, 0);
}
/* }}} */
/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
* Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar, mapPhar)
{
char *alias = NULL, *error;
int alias_len = 0;
long dataoffset = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
* Loads any phar archive with an alias */
PHP_METHOD(Phar, loadPhar)
{
char *fname, *alias = NULL, *error;
int fname_len, alias_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto string Phar::apiVersion()
* Returns the api version */
PHP_METHOD(Phar, apiVersion)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
}
/* }}}*/
/* {{{ proto bool Phar::canCompress([int method])
* Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar, canCompress)
{
long method = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
switch (method) {
case PHAR_ENT_COMPRESSED_GZ:
if (PHAR_G(has_zlib)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
case PHAR_ENT_COMPRESSED_BZ2:
if (PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
default:
if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto bool Phar::canWrite()
* Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar, canWrite)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!PHAR_G(readonly));
}
/* }}} */
/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
* Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar, isValidPharFilename)
{
char *fname;
const char *ext_str;
int fname_len, ext_len, is_executable;
zend_bool executable = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
return;
}
is_executable = executable;
RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
}
/* }}} */
#if HAVE_SPL
/**
* from spl_directory
*/
static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar = (phar_archive_data *) object->oth;
if (!phar->is_persistent) {
phar_archive_delref(phar TSRMLS_CC);
}
object->oth = NULL;
}
/* }}} */
/**
* from spl_directory
*/
static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
}
/* }}} */
static spl_other_handler phar_spl_foreign_handler = {
phar_spl_foreign_dtor,
phar_spl_foreign_clone
};
#endif /* HAVE_SPL */
/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
* Construct a Phar archive object
*
* proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
* Construct a PharData archive object
*
* This function is used as the constructor for both the Phar and PharData
* classes, hence the two prototypes above.
*/
PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
/* }}} */
/* {{{ proto array Phar::getSupportedSignatures()
* Return array of supported signature types
*/
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
/* }}} */
/* {{{ proto array Phar::getSupportedCompression()
* Return array of supported comparession algorithms
*/
PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
/* }}} */
/* {{{ proto array Phar::unlinkArchive(string archive)
* Completely remove a phar archive from memory and disk
*/
PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
int fname_len, zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename(TSRMLS_C);
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar TSRMLS_CC);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
/* }}} */
#if HAVE_SPL
#define PHAR_ARCHIVE_OBJECT() \
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!phar_obj->arc.archive) { \
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
"Cannot call method on an uninitialized Phar object"); \
return; \
}
/* {{{ proto void Phar::__destruct()
* if persistent, remove from the cache
*/
PHP_METHOD(Phar, __destruct)
{
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
}
}
/* }}} */
struct _phar_t {
phar_archive_object *p;
zend_class_entry *c;
char *b;
uint l;
zval *ret;
int count;
php_stream *fp;
};
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
{
zval **value;
zend_uchar key_type;
zend_bool close_fp = 1;
ulong int_key;
struct _phar_t *p_obj = (struct _phar_t*) puser;
uint str_key_len, base_len = p_obj->l, fname_len;
phar_entry_data *data;
php_stream *fp;
size_t contents_len;
char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
phar_zstr key;
char *str_key;
zend_class_entry *ce = p_obj->c;
phar_archive_object *phar_obj = p_obj->p;
char *str = "[stream]";
iter->funcs->get_current_data(iter, &value TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (!value) {
/* failure in get_current_data */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (Z_TYPE_PP(value)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(*(value) TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
break;
case IS_RESOURCE:
php_stream_from_zval_no_verify(fp, value);
if (!fp) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') {
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
close_fp = 0;
opened = (char *) estrndup(str, sizeof("[stream]") - 1);
goto after_open_fp;
case IS_OBJECT:
if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
char *test = NULL;
zval dummy;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
if (!base_len) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (intern->type) {
case SPL_FS_DIR:
#if PHP_VERSION_ID >= 60000
test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
#elif PHP_VERSION_ID >= 50300
test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
#else
test = intern->path;
#endif
fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
if (Z_BVAL(dummy)) {
/* ignore directories */
efree(fname);
return ZEND_HASH_APPLY_KEEP;
}
test = expand_filepath(fname, NULL TSRMLS_CC);
efree(fname);
if (test) {
fname = test;
fname_len = strlen(fname);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
save = fname;
goto phar_spl_fileinfo;
case SPL_FS_INFO:
case SPL_FS_FILE:
#if PHP_VERSION_ID >= 60000
if (intern->file_name_type == IS_UNICODE) {
zval zv;
INIT_ZVAL(zv);
Z_UNIVAL(zv) = intern->file_name;
Z_UNILEN(zv) = intern->file_name_len;
Z_TYPE(zv) = IS_UNICODE;
zval_copy_ctor(&zv);
zval_unicode_to_string(&zv TSRMLS_CC);
fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
ezfree(Z_UNIVAL(zv));
} else {
fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
}
#else
fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
#endif
if (!fname) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
fname_len = strlen(fname);
save = fname;
goto phar_spl_fileinfo;
}
}
/* fall-through */
default:
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
fname = Z_STRVAL_PP(value);
fname_len = Z_STRLEN_PP(value);
phar_spl_fileinfo:
if (base_len) {
temp = expand_filepath(base, NULL TSRMLS_CC);
if (!temp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
if (save) {
efree(save);
}
return ZEND_HASH_APPLY_STOP;
}
base = temp;
base_len = strlen(base);
if (strstr(fname, base)) {
str_key_len = fname_len - base_len;
if (str_key_len <= 0) {
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_KEEP;
}
str_key = fname + base_len;
if (*str_key == '/' || *str_key == '\\') {
str_key++;
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
} else {
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') str_key_len--;
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
/* try to open source file, then create internal phar file and copy contents */
fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
if (!fp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
after_open_fp:
if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
/* silently skip any files that would be added to the magic .phar directory */
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
if (opened) {
efree(opened);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_KEEP;
}
if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
efree(error);
if (save) {
efree(save);
}
if (opened) {
efree(opened);
}
if (temp) {
efree(temp);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_STOP;
} else {
if (error) {
efree(error);
}
/* convert to PHAR_UFP */
if (data->internal_file->fp_type == PHAR_MOD) {
php_stream_close(data->internal_file->fp);
}
data->internal_file->fp = NULL;
data->internal_file->fp_type = PHAR_UFP;
data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
data->fp = NULL;
phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
php_stream_tell(p_obj->fp) - data->internal_file->offset;
}
if (close_fp) {
php_stream_close(fp);
}
add_assoc_string(p_obj->ret, str_key, opened, 0);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
phar_entry_delref(data TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
* Construct a phar archive from an existing directory, recursively.
* Optional second parameter is a regular expression for filtering directory contents.
*
* Return value is an array mapping phar index to actual files added.
*/
PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
* Construct a phar archive from an iterator. The iterator must return a series of strings
* that are full paths to files that should be added to the phar. The iterator key should
* be the path that the file will have within the phar archive.
*
* If base directory is specified, then the key will be ignored, and instead the portion of
* the current value minus the base directory will be used
*
* Returned is an array mapping phar index to actual file added
*/
PHP_METHOD(Phar, buildFromIterator)
{
zval *obj;
char *error;
uint base_len = 0;
char *base = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
array_init(return_value);
pass.c = Z_OBJCE_P(obj);
pass.p = phar_obj;
pass.b = base;
pass.l = base_len;
pass.ret = return_value;
pass.count = 0;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto int Phar::count()
* Returns the number of entries in the Phar archive
*/
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
/* }}} */
/* {{{ proto bool Phar::isFileFormat(int format)
* Returns true if the phar archive is based on the tar/zip/phar file format depending
* on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
*/
PHP_METHOD(Phar, isFileFormat)
{
long type;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
RETURN_FALSE;
}
switch (type) {
case PHAR_FORMAT_TAR:
RETURN_BOOL(phar_obj->arc.archive->is_tar);
case PHAR_FORMAT_ZIP:
RETURN_BOOL(phar_obj->arc.archive->is_zip);
case PHAR_FORMAT_PHAR:
RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
}
}
/* }}} */
static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *error;
off_t offset;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
}
return FAILURE;
}
/* copy old contents in entirety */
phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
offset = php_stream_tell(fp);
link = phar_get_link_source(entry TSRMLS_CC);
if (!link) {
link = entry;
}
if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
/* save for potential restore on error */
entry->cfp = entry->fp;
entry->fp = NULL;
}
/* set new location of file contents */
entry->fp_type = PHAR_FP;
entry->offset = offset;
return SUCCESS;
}
/* }}} */
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, newentry;
zval *ret;
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
/* set whole-archive compression and type from parameter */
phar->flags = flags;
phar->is_data = source->is_data;
switch (convert) {
case PHAR_FORMAT_TAR:
phar->is_tar = 1;
break;
case PHAR_FORMAT_ZIP:
phar->is_zip = 1;
break;
default:
phar->is_data = 0;
break;
}
zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
phar->fp = php_stream_fopen_tmpfile();
if (phar->fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
return NULL;
}
phar->fname = source->fname;
phar->fname_len = source->fname_len;
phar->is_temporary_alias = source->is_temporary_alias;
phar->alias = source->alias;
if (source->metadata) {
zval *t;
t = source->metadata;
ALLOC_ZVAL(phar->metadata);
*phar->metadata = *t;
zval_copy_ctor(phar->metadata);
#if PHP_VERSION_ID < 50300
phar->metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(phar->metadata, 1);
#endif
phar->metadata_len = 0;
}
/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\"", source->fname);
return NULL;
}
newentry = *entry;
if (newentry.link) {
newentry.link = estrdup(newentry.link);
goto no_copy;
}
if (newentry.tmp) {
newentry.tmp = estrdup(newentry.tmp);
goto no_copy;
}
newentry.metadata_str.c = 0;
if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
/* exception already thrown */
return NULL;
}
no_copy:
newentry.filename = estrndup(newentry.filename, newentry.filename_len);
if (newentry.metadata) {
zval *t;
t = newentry.metadata;
ALLOC_ZVAL(newentry.metadata);
*newentry.metadata = *t;
zval_copy_ctor(newentry.metadata);
#if PHP_VERSION_ID < 50300
newentry.metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(newentry.metadata, 1);
#endif
newentry.metadata_str.c = NULL;
newentry.metadata_str.len = 0;
}
newentry.is_zip = phar->is_zip;
newentry.is_tar = phar->is_tar;
if (newentry.is_tar) {
newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
}
newentry.is_modified = 1;
newentry.phar = phar;
newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
phar_set_inode(&newentry TSRMLS_CC);
zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
}
if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) {
return ret;
} else {
zend_hash_destroy(&(phar->manifest));
zend_hash_destroy(&(phar->mounted_dirs));
zend_hash_destroy(&(phar->virtual_dirs));
if (phar->fp) {
php_stream_close(phar->fp);
}
efree(phar->fname);
efree(phar);
return NULL;
/* }}} */
| 165,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 void RemoveDuplicateLayers(Image **images,
ExceptionInfo *exception)
{
register Image
*curr,
*next;
RectangleInfo
bounds;
assert((*images) != (const 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);
curr=GetFirstImageInList(*images);
for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next)
{
if ( curr->columns != next->columns || curr->rows != next->rows
|| curr->page.x != next->page.x || curr->page.y != next->page.y )
continue;
bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception);
if ( bounds.x < 0 ) {
/*
the two images are the same, merge time delays and delete one.
*/
size_t time;
time = curr->delay*1000/curr->ticks_per_second;
time += next->delay*1000/next->ticks_per_second;
next->ticks_per_second = 100L;
next->delay = time*curr->ticks_per_second/1000;
next->iterations = curr->iterations;
*images = curr;
(void) DeleteImageFromList(images);
}
}
*images = GetFirstImageInList(*images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629
CWE ID: CWE-369 | MagickExport void RemoveDuplicateLayers(Image **images,
MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception)
{
RectangleInfo
bounds;
register Image
*image,
*next;
assert((*images) != (const 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);
image=GetFirstImageInList(*images);
for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next)
{
if ((image->columns != next->columns) || (image->rows != next->rows) ||
(image->page.x != next->page.x) || (image->page.y != next->page.y))
continue;
bounds=CompareImageBounds(image,next,CompareAnyLayer,exception);
if (bounds.x < 0)
{
/*
Two images are the same, merge time delays and delete one.
*/
size_t
time;
time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second);
time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second);
next->ticks_per_second=100L;
next->delay=time*image->ticks_per_second/1000;
next->iterations=image->iterations;
*images=image;
(void) DeleteImageFromList(images);
}
}
*images=GetFirstImageInList(*images);
}
| 169,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
skb_orphan(skb);
if (!(dev->flags & IFF_UP))
return NET_RX_DROP;
if (skb->len > (dev->mtu + dev->hard_header_len))
return NET_RX_DROP;
skb_set_dev(skb, dev);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, dev);
return netif_rx(skb);
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
skb_orphan(skb);
if (!(dev->flags & IFF_UP) ||
(skb->len > (dev->mtu + dev->hard_header_len))) {
kfree_skb(skb);
return NET_RX_DROP;
}
skb_set_dev(skb, dev);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, dev);
return netif_rx(skb);
}
| 166,089 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
Commit Message: proc: restrict access to /proc/PID/io
/proc/PID/io may be used for gathering private information. E.g. for
openssh and vsftpd daemons wchars/rchars may be used to learn the
precise password length. Restrict it to processes being able to ptrace
the target process.
ptrace_may_access() is needed to prevent keeping open file descriptor of
"io" file, executing setuid binary and gathering io information of the
setuid'ed process.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (!ptrace_may_access(task, PTRACE_MODE_READ))
return -EACCES;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
| 165,860 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target,
xmlAttrPtr attr)
{
const xmlChar *value;
xmlAttrPtr ret;
if ((ctxt == NULL) || (attr == NULL) || (target == NULL))
return(NULL);
if (attr->type != XML_ATTRIBUTE_NODE)
return(NULL);
/*
* Skip all XSLT attributes.
*/
#ifdef XSLT_REFACTORED
if (attr->psvi == xsltXSLTAttrMarker)
return(NULL);
#else
if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
return(NULL);
#endif
/*
* Get the value.
*/
if (attr->children != NULL) {
if ((attr->children->type != XML_TEXT_NODE) ||
(attr->children->next != NULL))
{
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: The children of an attribute node of a "
"literal result element are not in the expected form.\n");
return(NULL);
}
value = attr->children->content;
if (value == NULL)
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
} else
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
/*
* Overwrite duplicates.
*/
ret = target->properties;
while (ret != NULL) {
if (((attr->ns != NULL) == (ret->ns != NULL)) &&
xmlStrEqual(ret->name, attr->name) &&
((attr->ns == NULL) || xmlStrEqual(ret->ns->href, attr->ns->href)))
{
break;
}
ret = ret->next;
}
if (ret != NULL) {
/* free the existing value */
xmlFreeNodeList(ret->children);
ret->children = ret->last = NULL;
/*
* Adjust ns-prefix if needed.
*/
if ((ret->ns != NULL) &&
(! xmlStrEqual(ret->ns->prefix, attr->ns->prefix)))
{
ret->ns = xsltGetNamespace(ctxt, attr->parent, attr->ns, target);
}
} else {
/* create a new attribute */
if (attr->ns != NULL)
ret = xmlNewNsProp(target,
xsltGetNamespace(ctxt, attr->parent, attr->ns, target),
attr->name, NULL);
else
ret = xmlNewNsProp(target, NULL, attr->name, NULL);
}
/*
* Set the value.
*/
if (ret != NULL) {
xmlNodePtr text;
text = xmlNewText(NULL);
if (text != NULL) {
ret->last = ret->children = text;
text->parent = (xmlNodePtr) ret;
text->doc = ret->doc;
if (attr->psvi != NULL) {
/*
* Evaluate the Attribute Value Template.
*/
xmlChar *val;
val = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
if (val == NULL) {
/*
* TODO: Damn, we need an easy mechanism to report
* qualified names!
*/
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '%s'.\n",
attr->name);
}
text->content = xmlStrdup(BAD_CAST "");
} else {
text->content = val;
}
} else if ((ctxt->internalized) && (target != NULL) &&
(target->doc != NULL) &&
(target->doc->dict == ctxt->dict)) {
text->content = (xmlChar *) value;
} else {
text->content = xmlStrdup(value);
}
}
} else {
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '%s'.\n",
attr->name);
}
}
return(ret);
}
Commit Message: Fix dictionary string usage.
BUG=144799
Review URL: https://chromiumcodereview.appspot.com/10919019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154331 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target,
xmlAttrPtr attr)
{
const xmlChar *value;
xmlAttrPtr ret;
if ((ctxt == NULL) || (attr == NULL) || (target == NULL))
return(NULL);
if (attr->type != XML_ATTRIBUTE_NODE)
return(NULL);
/*
* Skip all XSLT attributes.
*/
#ifdef XSLT_REFACTORED
if (attr->psvi == xsltXSLTAttrMarker)
return(NULL);
#else
if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
return(NULL);
#endif
/*
* Get the value.
*/
if (attr->children != NULL) {
if ((attr->children->type != XML_TEXT_NODE) ||
(attr->children->next != NULL))
{
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: The children of an attribute node of a "
"literal result element are not in the expected form.\n");
return(NULL);
}
value = attr->children->content;
if (value == NULL)
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
} else
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
/*
* Overwrite duplicates.
*/
ret = target->properties;
while (ret != NULL) {
if (((attr->ns != NULL) == (ret->ns != NULL)) &&
xmlStrEqual(ret->name, attr->name) &&
((attr->ns == NULL) || xmlStrEqual(ret->ns->href, attr->ns->href)))
{
break;
}
ret = ret->next;
}
if (ret != NULL) {
/* free the existing value */
xmlFreeNodeList(ret->children);
ret->children = ret->last = NULL;
/*
* Adjust ns-prefix if needed.
*/
if ((ret->ns != NULL) &&
(! xmlStrEqual(ret->ns->prefix, attr->ns->prefix)))
{
ret->ns = xsltGetNamespace(ctxt, attr->parent, attr->ns, target);
}
} else {
/* create a new attribute */
if (attr->ns != NULL)
ret = xmlNewNsProp(target,
xsltGetNamespace(ctxt, attr->parent, attr->ns, target),
attr->name, NULL);
else
ret = xmlNewNsProp(target, NULL, attr->name, NULL);
}
/*
* Set the value.
*/
if (ret != NULL) {
xmlNodePtr text;
text = xmlNewText(NULL);
if (text != NULL) {
ret->last = ret->children = text;
text->parent = (xmlNodePtr) ret;
text->doc = ret->doc;
if (attr->psvi != NULL) {
/*
* Evaluate the Attribute Value Template.
*/
xmlChar *val;
val = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
if (val == NULL) {
/*
* TODO: Damn, we need an easy mechanism to report
* qualified names!
*/
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '%s'.\n",
attr->name);
}
text->content = xmlStrdup(BAD_CAST "");
} else {
text->content = val;
}
} else if ((ctxt->internalized) && (target != NULL) &&
(target->doc != NULL) &&
(target->doc->dict == ctxt->dict) &&
xmlDictOwns(ctxt->dict, value)) {
text->content = (xmlChar *) value;
} else {
text->content = xmlStrdup(value);
}
}
} else {
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '%s'.\n",
attr->name);
}
}
return(ret);
}
| 170,860 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt);
break;
case BPF_TYPE_MAP:
bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
raw = bpf_prog_inc(raw);
break;
case BPF_TYPE_MAP:
raw = bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
| 167,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: bool AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringCase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringASCIICase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
| 171,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ProfileChooserView::SignOutAllWebAccounts() {
Hide();
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile())
->RevokeAllCredentials();
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void ProfileChooserView::SignOutAllWebAccounts() {
Hide();
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile())
->RevokeAllCredentials(signin_metrics::SourceForRefreshTokenOperation::
kUserMenu_SignOutAllAccounts);
}
| 172,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = alg->setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
}
Commit Message: crypto: skcipher - Add missing API setkey checks
The API setkey checks for key sizes and alignment went AWOL during the
skcipher conversion. This patch restores them.
Cc: <[email protected]>
Fixes: 4e6c3df4d729 ("crypto: skcipher - Add low-level skcipher...")
Reported-by: Baozeng <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = skcipher_setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
}
| 168,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
authctxt->user = buffer_get_string(m, NULL);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
CWE ID: CWE-20 | mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
| 166,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&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;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,
tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
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: https://github.com/ImageMagick/ImageMagick/issues/298
CWE ID: CWE-476 | static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&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;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
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,680 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 *ReadRGFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
byte;
ssize_t
y;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read RGF header.
*/
image->columns = (unsigned long) ReadBlobByte(image);
image->rows = (unsigned long) ReadBlobByte(image);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Initialize image structure.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read hex image data.
*/
data=(unsigned char *) AcquireQuantumMemory(image->rows,image->columns*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) (image->columns * image->rows); i++)
{
*p++=ReadBlobByte(image);
}
/*
Convert RGF image to pixel packets.
*/
p=data;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) (*p++);
SetPixelIndex(indexes+x,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00));
bit++;
byte>>=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
data=(unsigned char *) RelinquishMagickMemory(data);
(void) SyncImage(image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadRGFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
byte;
ssize_t
y;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read RGF header.
*/
image->columns = (unsigned long) ReadBlobByte(image);
image->rows = (unsigned long) ReadBlobByte(image);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Initialize image structure.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read hex image data.
*/
data=(unsigned char *) AcquireQuantumMemory(image->rows,image->columns*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) (image->columns * image->rows); i++)
{
*p++=ReadBlobByte(image);
}
/*
Convert RGF image to pixel packets.
*/
p=data;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) (*p++);
SetPixelIndex(indexes+x,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00));
bit++;
byte>>=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
data=(unsigned char *) RelinquishMagickMemory(data);
(void) SyncImage(image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TypingCommand::insertText(Document& document,
const String& text,
const VisibleSelection& selectionForInsertion,
Options options,
TextCompositionType compositionType,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
VisibleSelection currentSelection =
frame->selection().computeVisibleSelectionInDOMTreeDeprecated();
String newText = text;
if (compositionType != TextCompositionUpdate)
newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion);
if (compositionType == TextCompositionConfirm) {
if (dispatchTextInputEvent(frame, newText) !=
DispatchEventResult::NotCanceled)
return;
}
if (selectionForInsertion.isCaret() && newText.isEmpty())
return;
document.updateStyleAndLayoutIgnorePendingStylesheets();
const PlainTextRange selectionOffsets = getSelectionOffsets(frame);
if (selectionOffsets.isNull())
return;
const size_t selectionStart = selectionOffsets.start();
if (TypingCommand* lastTypingCommand =
lastTypingCommandIfStillOpenForTyping(frame)) {
if (lastTypingCommand->endingSelection() != selectionForInsertion) {
lastTypingCommand->setStartingSelection(selectionForInsertion);
lastTypingCommand->setEndingVisibleSelection(selectionForInsertion);
}
lastTypingCommand->setCompositionType(compositionType);
lastTypingCommand->setShouldRetainAutocorrectionIndicator(
options & RetainAutocorrectionIndicator);
lastTypingCommand->setShouldPreventSpellChecking(options &
PreventSpellChecking);
lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion;
lastTypingCommand->m_selectionStart = selectionStart;
EditingState editingState;
EventQueueScope eventQueueScope;
lastTypingCommand->insertText(newText, options & SelectInsertedText,
&editingState);
return;
}
TypingCommand* command = TypingCommand::create(document, InsertText, newText,
options, compositionType);
bool changeSelection = selectionForInsertion != currentSelection;
if (changeSelection) {
command->setStartingSelection(selectionForInsertion);
command->setEndingVisibleSelection(selectionForInsertion);
}
command->m_isIncrementalInsertion = isIncrementalInsertion;
command->m_selectionStart = selectionStart;
command->apply();
if (changeSelection) {
command->setEndingVisibleSelection(currentSelection);
frame->selection().setSelection(currentSelection.asSelection());
}
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID: | void TypingCommand::insertText(Document& document,
void TypingCommand::insertText(
Document& document,
const String& text,
const SelectionInDOMTree& passedSelectionForInsertion,
Options options,
TextCompositionType compositionType,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
VisibleSelection currentSelection =
frame->selection().computeVisibleSelectionInDOMTreeDeprecated();
const VisibleSelection& selectionForInsertion =
createVisibleSelection(passedSelectionForInsertion);
String newText = text;
if (compositionType != TextCompositionUpdate)
newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion);
if (compositionType == TextCompositionConfirm) {
if (dispatchTextInputEvent(frame, newText) !=
DispatchEventResult::NotCanceled)
return;
}
if (selectionForInsertion.isCaret() && newText.isEmpty())
return;
document.updateStyleAndLayoutIgnorePendingStylesheets();
const PlainTextRange selectionOffsets = getSelectionOffsets(frame);
if (selectionOffsets.isNull())
return;
const size_t selectionStart = selectionOffsets.start();
if (TypingCommand* lastTypingCommand =
lastTypingCommandIfStillOpenForTyping(frame)) {
if (lastTypingCommand->endingSelection() != selectionForInsertion) {
lastTypingCommand->setStartingSelection(selectionForInsertion);
lastTypingCommand->setEndingVisibleSelection(selectionForInsertion);
}
lastTypingCommand->setCompositionType(compositionType);
lastTypingCommand->setShouldRetainAutocorrectionIndicator(
options & RetainAutocorrectionIndicator);
lastTypingCommand->setShouldPreventSpellChecking(options &
PreventSpellChecking);
lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion;
lastTypingCommand->m_selectionStart = selectionStart;
EditingState editingState;
EventQueueScope eventQueueScope;
lastTypingCommand->insertText(newText, options & SelectInsertedText,
&editingState);
return;
}
TypingCommand* command = TypingCommand::create(document, InsertText, newText,
options, compositionType);
bool changeSelection = selectionForInsertion != currentSelection;
if (changeSelection) {
command->setStartingSelection(selectionForInsertion);
command->setEndingVisibleSelection(selectionForInsertion);
}
command->m_isIncrementalInsertion = isIncrementalInsertion;
command->m_selectionStart = selectionStart;
command->apply();
if (changeSelection) {
command->setEndingVisibleSelection(currentSelection);
frame->selection().setSelection(currentSelection.asSelection());
}
}
| 172,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec)
{
WORD16 *pi2_vld_out;
UWORD32 i;
yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf;
UWORD32 u4_frm_offset = 0;
const dec_mb_params_t *ps_dec_mb_params;
IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
pi2_vld_out = ps_dec->ai2_vld_buf;
memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv));
ps_dec->u2_prev_intra_mb = 0;
ps_dec->u2_first_mb = 1;
ps_dec->u2_picture_width = ps_dec->u2_frame_width;
if(ps_dec->u2_picture_structure != FRAME_PICTURE)
{
ps_dec->u2_picture_width <<= 1;
if(ps_dec->u2_picture_structure == BOTTOM_FIELD)
{
u4_frm_offset = ps_dec->u2_frame_width;
}
}
do
{
UWORD32 u4_x_offset, u4_y_offset;
WORD32 ret;
UWORD32 u4_x_dst_offset = 0;
UWORD32 u4_y_dst_offset = 0;
UWORD8 *pu1_out_p;
UWORD8 *pu1_pred;
WORD32 u4_pred_strd;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
if(ps_dec->e_pic_type == B_PIC)
ret = impeg2d_dec_pnb_mb_params(ps_dec);
else
ret = impeg2d_dec_p_mb_params(ps_dec);
if(ret)
return IMPEG2D_MB_TEX_DECODE_ERR;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4);
u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width;
pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset;
if(ps_dec->u2_prev_intra_mb == 0)
{
UWORD32 offset_x, offset_y, stride;
UWORD16 index = (ps_dec->u2_motion_type);
/*only for non intra mb's*/
if(ps_dec->e_mb_pred == BIDIRECT)
{
ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index];
}
else
{
ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index];
}
stride = ps_dec->u2_picture_width;
offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4);
offset_y = (ps_dec->u2_mb_y << 4);
ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x;
stride = stride >> 1;
ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride
+ (offset_x >> 1);
ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride
+ (offset_x >> 1);
PROFILE_DISABLE_MC_IF0
ps_dec_mb_params->pf_mc(ps_dec);
}
for(i = 0; i < NUM_LUMA_BLKS; ++i)
{
if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0)
{
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, Y_LUMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
u4_x_offset = gai2_impeg2_blk_x_off[i];
if(ps_dec->u2_field_dct == 0)
u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ;
else
u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ;
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset;
u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset,
8,
u4_pred_strd,
ps_dec->u2_picture_width << ps_dec->u2_field_dct,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
}
/* For U and V blocks, divide the x and y offsets by 2. */
u4_x_dst_offset >>= 1;
u4_y_dst_offset >>= 2;
/* In case of chrominance blocks the DCT will be frame DCT */
/* i = 0, U component and i = 1 is V componet */
if((ps_dec->u2_cbp & 0x02) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, U_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
if((ps_dec->u2_cbp & 0x01) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, V_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
ps_dec->u2_num_mbs_left--;
ps_dec->u2_first_mb = 0;
ps_dec->u2_mb_x++;
if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)
{
return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR;
}
else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb)
{
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y++;
}
}
while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0);
return e_error;
}
Commit Message: Fixed Memory Overflow Errors
In function impeg2d_dec_p_b_slice, there was no check for num_mbs_left ==
0 after skip_mbs function call. Hence, even though it should have returned
as an error, it goes ahead to decode the frame and writes beyond the
buffer allocated for output. Put a check for the same.
Bug: 38207066
Test: before/after execution of PoC on angler/nyc-mr2-dev
Change-Id: If4b7bea51032bf2fe2edd03f64a68847aa4f6a00
(cherry picked from commit 2df080153464bf57084d68ba3594e199bc140eb4)
CWE ID: CWE-119 | IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec)
{
WORD16 *pi2_vld_out;
UWORD32 i;
yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf;
UWORD32 u4_frm_offset = 0;
const dec_mb_params_t *ps_dec_mb_params;
IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
pi2_vld_out = ps_dec->ai2_vld_buf;
memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv));
ps_dec->u2_prev_intra_mb = 0;
ps_dec->u2_first_mb = 1;
ps_dec->u2_picture_width = ps_dec->u2_frame_width;
if(ps_dec->u2_picture_structure != FRAME_PICTURE)
{
ps_dec->u2_picture_width <<= 1;
if(ps_dec->u2_picture_structure == BOTTOM_FIELD)
{
u4_frm_offset = ps_dec->u2_frame_width;
}
}
do
{
UWORD32 u4_x_offset, u4_y_offset;
WORD32 ret;
UWORD32 u4_x_dst_offset = 0;
UWORD32 u4_y_dst_offset = 0;
UWORD8 *pu1_out_p;
UWORD8 *pu1_pred;
WORD32 u4_pred_strd;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
if(ps_dec->e_pic_type == B_PIC)
ret = impeg2d_dec_pnb_mb_params(ps_dec);
else
ret = impeg2d_dec_p_mb_params(ps_dec);
if(ret)
return IMPEG2D_MB_TEX_DECODE_ERR;
if(0 >= ps_dec->u2_num_mbs_left)
{
break;
}
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4);
u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width;
pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset;
if(ps_dec->u2_prev_intra_mb == 0)
{
UWORD32 offset_x, offset_y, stride;
UWORD16 index = (ps_dec->u2_motion_type);
/*only for non intra mb's*/
if(ps_dec->e_mb_pred == BIDIRECT)
{
ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index];
}
else
{
ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index];
}
stride = ps_dec->u2_picture_width;
offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4);
offset_y = (ps_dec->u2_mb_y << 4);
ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x;
stride = stride >> 1;
ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride
+ (offset_x >> 1);
ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride
+ (offset_x >> 1);
PROFILE_DISABLE_MC_IF0
ps_dec_mb_params->pf_mc(ps_dec);
}
for(i = 0; i < NUM_LUMA_BLKS; ++i)
{
if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0)
{
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, Y_LUMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
u4_x_offset = gai2_impeg2_blk_x_off[i];
if(ps_dec->u2_field_dct == 0)
u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ;
else
u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ;
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset;
u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset,
8,
u4_pred_strd,
ps_dec->u2_picture_width << ps_dec->u2_field_dct,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
}
/* For U and V blocks, divide the x and y offsets by 2. */
u4_x_dst_offset >>= 1;
u4_y_dst_offset >>= 2;
/* In case of chrominance blocks the DCT will be frame DCT */
/* i = 0, U component and i = 1 is V componet */
if((ps_dec->u2_cbp & 0x02) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, U_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
if((ps_dec->u2_cbp & 0x01) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, V_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
ps_dec->u2_num_mbs_left--;
ps_dec->u2_first_mb = 0;
ps_dec->u2_mb_x++;
if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)
{
return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR;
}
else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb)
{
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y++;
}
}
while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0);
return e_error;
}
| 173,995 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
if (!context || data || (scanline == 0))
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
if (context->priv->PlaneBuffersLength < rw * scanline)
return FALSE;
if (rw < scanline * 2)
return FALSE;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
return TRUE;
}
| 169,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 ptrace_triggered(struct perf_event *bp, int nmi,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions.
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | void ptrace_triggered(struct perf_event *bp, int nmi,
void ptrace_triggered(struct perf_event *bp,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions.
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
| 165,795 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length) {
assert(data != NULL);
assert(length > 0);
uint16_t transmitted_length = 0;
while (length > 0) {
ssize_t ret = write(fd, data + transmitted_length, length);
switch (ret) {
case -1:
LOG_ERROR("In %s, error writing to the serial port with fd %d: %s", __func__, fd, strerror(errno));
return transmitted_length;
case 0:
return transmitted_length;
default:
transmitted_length += ret;
length -= ret;
break;
}
}
return transmitted_length;
}
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 uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length) {
assert(data != NULL);
assert(length > 0);
uint16_t transmitted_length = 0;
while (length > 0) {
ssize_t ret = TEMP_FAILURE_RETRY(write(fd, data + transmitted_length, length));
switch (ret) {
case -1:
LOG_ERROR("In %s, error writing to the serial port with fd %d: %s", __func__, fd, strerror(errno));
return transmitted_length;
case 0:
return transmitted_length;
default:
transmitted_length += ret;
length -= ret;
break;
}
}
return transmitted_length;
}
| 173,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: void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped");
if (!view_) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
false,
0);
return;
}
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params;
gpu_params.surface_id = surface_id;
gpu_params.surface_handle = surface_handle;
gpu_params.route_id = route_id;
gpu_params.size = size;
#if defined(OS_MACOSX)
gpu_params.window = gfx::kNullPluginWindow;
#endif
view_->AcceleratedSurfaceBuffersSwapped(gpu_params,
gpu_process_host_id);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped");
if (!view_) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
surface_handle,
0);
return;
}
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params;
gpu_params.surface_id = surface_id;
gpu_params.surface_handle = surface_handle;
gpu_params.route_id = route_id;
gpu_params.size = size;
#if defined(OS_MACOSX)
gpu_params.window = gfx::kNullPluginWindow;
#endif
view_->AcceleratedSurfaceBuffersSwapped(gpu_params,
gpu_process_host_id);
}
| 171,367 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.