instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::DidProceedOnInterstitial() {
DCHECK(!(ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber()));
if (ShowingInterstitialPage() && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::DidProceedOnInterstitial() {
DCHECK(!(ShowingInterstitialPage() && interstitial_page_->pause_throbber()));
if (ShowingInterstitialPage() && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
| 172,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int t2p_process_jpeg_strip(
unsigned char* strip,
tsize_t* striplength,
unsigned char* buffer,
tsize_t* bufferoffset,
tstrip_t no,
uint32 height){
tsize_t i=0;
while (i < *striplength) {
tsize_t datalen;
uint16 ri;
uint16 v_samp;
uint16 h_samp;
int j;
int ncomp;
/* marker header: one or more FFs */
if (strip[i] != 0xff)
return(0);
i++;
while (i < *striplength && strip[i] == 0xff)
i++;
if (i >= *striplength)
return(0);
/* SOI is the only pre-SOS marker without a length word */
if (strip[i] == 0xd8)
datalen = 0;
else {
if ((*striplength - i) <= 2)
return(0);
datalen = (strip[i+1] << 8) | strip[i+2];
if (datalen < 2 || datalen >= (*striplength - i))
return(0);
}
switch( strip[i] ){
case 0xd8: /* SOI - start of image */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);
*bufferoffset+=2;
break;
case 0xc0: /* SOF0 */
case 0xc1: /* SOF1 */
case 0xc3: /* SOF3 */
case 0xc9: /* SOF9 */
case 0xca: /* SOF10 */
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
ncomp = buffer[*bufferoffset+9];
if (ncomp < 1 || ncomp > 4)
return(0);
v_samp=1;
h_samp=1;
for(j=0;j<ncomp;j++){
uint16 samp = buffer[*bufferoffset+11+(3*j)];
if( (samp>>4) > h_samp)
h_samp = (samp>>4);
if( (samp & 0x0f) > v_samp)
v_samp = (samp & 0x0f);
}
v_samp*=8;
h_samp*=8;
ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) |
(uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/
v_samp);
ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) |
(uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/
h_samp);
buffer[*bufferoffset+5]=
(unsigned char) ((height>>8) & 0xff);
buffer[*bufferoffset+6]=
(unsigned char) (height & 0xff);
*bufferoffset+=datalen+2;
/* insert a DRI marker */
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=0xdd;
buffer[(*bufferoffset)++]=0x00;
buffer[(*bufferoffset)++]=0x04;
buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
buffer[(*bufferoffset)++]= ri & 0xff;
}
break;
case 0xc4: /* DHT */
case 0xdb: /* DQT */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
break;
case 0xda: /* SOS */
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
} else {
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=
(unsigned char)(0xd0 | ((no-1)%8));
}
i += datalen + 1;
/* copy remainder of strip */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);
*bufferoffset+= *striplength - i;
return(1);
default:
/* ignore any other marker */
break;
}
i += datalen + 1;
}
/* failed to find SOS marker */
return(0);
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | int t2p_process_jpeg_strip(
unsigned char* strip,
tsize_t* striplength,
unsigned char* buffer,
tsize_t buffersize,
tsize_t* bufferoffset,
tstrip_t no,
uint32 height){
tsize_t i=0;
while (i < *striplength) {
tsize_t datalen;
uint16 ri;
uint16 v_samp;
uint16 h_samp;
int j;
int ncomp;
/* marker header: one or more FFs */
if (strip[i] != 0xff)
return(0);
i++;
while (i < *striplength && strip[i] == 0xff)
i++;
if (i >= *striplength)
return(0);
/* SOI is the only pre-SOS marker without a length word */
if (strip[i] == 0xd8)
datalen = 0;
else {
if ((*striplength - i) <= 2)
return(0);
datalen = (strip[i+1] << 8) | strip[i+2];
if (datalen < 2 || datalen >= (*striplength - i))
return(0);
}
switch( strip[i] ){
case 0xd8: /* SOI - start of image */
if( *bufferoffset + 2 > buffersize )
return(0);
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);
*bufferoffset+=2;
break;
case 0xc0: /* SOF0 */
case 0xc1: /* SOF1 */
case 0xc3: /* SOF3 */
case 0xc9: /* SOF9 */
case 0xca: /* SOF10 */
if(no==0){
if( *bufferoffset + datalen + 2 + 6 > buffersize )
return(0);
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
if( *bufferoffset + 9 >= buffersize )
return(0);
ncomp = buffer[*bufferoffset+9];
if (ncomp < 1 || ncomp > 4)
return(0);
v_samp=1;
h_samp=1;
if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize )
return(0);
for(j=0;j<ncomp;j++){
uint16 samp = buffer[*bufferoffset+11+(3*j)];
if( (samp>>4) > h_samp)
h_samp = (samp>>4);
if( (samp & 0x0f) > v_samp)
v_samp = (samp & 0x0f);
}
v_samp*=8;
h_samp*=8;
ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) |
(uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/
v_samp);
ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) |
(uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/
h_samp);
buffer[*bufferoffset+5]=
(unsigned char) ((height>>8) & 0xff);
buffer[*bufferoffset+6]=
(unsigned char) (height & 0xff);
*bufferoffset+=datalen+2;
/* insert a DRI marker */
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=0xdd;
buffer[(*bufferoffset)++]=0x00;
buffer[(*bufferoffset)++]=0x04;
buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
buffer[(*bufferoffset)++]= ri & 0xff;
}
break;
case 0xc4: /* DHT */
case 0xdb: /* DQT */
if( *bufferoffset + datalen + 2 > buffersize )
return(0);
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
break;
case 0xda: /* SOS */
if(no==0){
if( *bufferoffset + datalen + 2 > buffersize )
return(0);
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
} else {
if( *bufferoffset + 2 > buffersize )
return(0);
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=
(unsigned char)(0xd0 | ((no-1)%8));
}
i += datalen + 1;
/* copy remainder of strip */
if( *bufferoffset + *striplength - i > buffersize )
return(0);
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);
*bufferoffset+= *striplength - i;
return(1);
default:
/* ignore any other marker */
break;
}
i += datalen + 1;
}
/* failed to find SOS marker */
return(0);
}
| 166,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
{
struct ip_options *opt;
opt = inet_sk(sk)->opt;
if (opt == NULL || opt->cipso == 0)
return -ENOMSG;
return cipso_v4_getattr(opt->__data + opt->cipso - sizeof(struct iphdr),
secattr);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
{
struct ip_options_rcu *opt;
int res = -ENOMSG;
rcu_read_lock();
opt = rcu_dereference(inet_sk(sk)->inet_opt);
if (opt && opt->opt.cipso)
res = cipso_v4_getattr(opt->opt.__data +
opt->opt.cipso -
sizeof(struct iphdr),
secattr);
rcu_read_unlock();
return res;
}
| 165,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Block::GetTrackNumber() const
{
return m_track;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Block::GetTrackNumber() const
bool Block::IsKey() const {
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
}
| 174,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
return ch;
}
Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk
This helps protect against bugs where any part of a buf_t's memory
is passed to a function that expects a NUL-terminated input.
It also closes TROVE-2016-10-001 (aka bug 20384).
CWE ID: CWE-119 | chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
CHUNK_SET_SENTINEL(ch, alloc);
return ch;
}
| 168,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
if (!process_host) {
ClearForceUpdate();
context_ = nullptr;
return;
}
StoragePartition* partition = process_host->GetStoragePartition();
DCHECK(partition);
context_ = static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host,
void ServiceWorkerHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id);
if (!process_host) {
ClearForceUpdate();
context_ = nullptr;
return;
}
storage_partition_ =
static_cast<StoragePartitionImpl*>(process_host->GetStoragePartition());
DCHECK(storage_partition_);
context_ = static_cast<ServiceWorkerContextWrapper*>(
storage_partition_->GetServiceWorkerContext());
}
| 172,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int imap_subscribe(char *path, bool subscribe)
{
struct ImapData *idata = NULL;
char buf[LONG_STRING];
char mbox[LONG_STRING];
char errstr[STRING];
struct Buffer err, token;
struct ImapMbox mx;
if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)
{
mutt_error(_("Bad mailbox name"));
return -1;
}
idata = imap_conn_find(&(mx.account), 0);
if (!idata)
goto fail;
imap_fix_path(idata, mx.mbox, buf, sizeof(buf));
if (!*buf)
mutt_str_strfcpy(buf, "INBOX", sizeof(buf));
if (ImapCheckSubscribed)
{
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path);
if (mutt_parse_rc_line(mbox, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), buf);
else
mutt_message(_("Unsubscribing from %s..."), buf);
imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
if (imap_exec(idata, buf, 0) < 0)
goto fail;
imap_unmunge_mbox_name(idata, mx.mbox);
if (subscribe)
mutt_message(_("Subscribed to %s"), mx.mbox);
else
mutt_message(_("Unsubscribed from %s"), mx.mbox);
FREE(&mx.mbox);
return 0;
fail:
FREE(&mx.mbox);
return -1;
}
Commit Message: Quote path in imap_subscribe
CWE ID: CWE-77 | int imap_subscribe(char *path, bool subscribe)
{
struct ImapData *idata = NULL;
char buf[LONG_STRING];
char mbox[LONG_STRING];
char errstr[STRING];
struct Buffer err, token;
struct ImapMbox mx;
size_t len = 0;
if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)
{
mutt_error(_("Bad mailbox name"));
return -1;
}
idata = imap_conn_find(&(mx.account), 0);
if (!idata)
goto fail;
imap_fix_path(idata, mx.mbox, buf, sizeof(buf));
if (!*buf)
mutt_str_strfcpy(buf, "INBOX", sizeof(buf));
if (ImapCheckSubscribed)
{
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un");
imap_quote_string(mbox + len, sizeof(mbox) - len, path, true);
if (mutt_parse_rc_line(mbox, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), buf);
else
mutt_message(_("Unsubscribing from %s..."), buf);
imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
if (imap_exec(idata, buf, 0) < 0)
goto fail;
imap_unmunge_mbox_name(idata, mx.mbox);
if (subscribe)
mutt_message(_("Subscribed to %s"), mx.mbox);
else
mutt_message(_("Unsubscribed from %s"), mx.mbox);
FREE(&mx.mbox);
return 0;
fail:
FREE(&mx.mbox);
return -1;
}
| 169,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
base::MakeUnique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
std::make_unique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
| 173,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WebviewHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<WebviewInfo> info(new WebviewInfo());
const base::DictionaryValue* dict_value = NULL;
if (!extension->manifest()->GetDictionary(keys::kWebview,
&dict_value)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebview);
return false;
}
const base::ListValue* url_list = NULL;
if (!dict_value->GetList(keys::kWebviewAccessibleResources,
&url_list)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewAccessibleResourcesList);
return false;
}
for (size_t i = 0; i < url_list->GetSize(); ++i) {
std::string relative_path;
if (!url_list->GetString(i, &relative_path)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewAccessibleResource, base::IntToString(i));
return false;
}
URLPattern pattern(URLPattern::SCHEME_EXTENSION);
if (pattern.Parse(extension->url().spec()) != URLPattern::PARSE_SUCCESS) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, extension->url().spec());
return false;
}
while (relative_path[0] == '/')
relative_path = relative_path.substr(1, relative_path.length() - 1);
pattern.SetPath(pattern.path() + relative_path);
info->webview_accessible_resources_.AddPattern(pattern);
}
const base::ListValue* partition_list = NULL;
if (!dict_value->GetList(keys::kWebviewPrivilegedPartitions,
&partition_list)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewPrivilegedPartitionList);
return false;
}
for (size_t i = 0; i < partition_list->GetSize(); ++i) {
std::string partition_wildcard;
if (!partition_list->GetString(i, &partition_wildcard)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewPrivilegedPartition, base::IntToString(i));
return false;
}
info->webview_privileged_partitions_.push_back(partition_wildcard);
}
extension->SetManifestData(keys::kWebviewAccessibleResources, info.release());
return true;
}
Commit Message: <webview>: Update format for local file access in manifest.json
The new format is:
"webview" : {
"partitions" : [
{
"name" : "foo*",
"accessible_resources" : ["a.html", "b.html"]
},
{
"name" : "bar",
"accessible_resources" : ["a.html", "c.html"]
}
]
}
BUG=340291
Review URL: https://codereview.chromium.org/151923005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool WebviewHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<WebviewInfo> info(new WebviewInfo());
const base::DictionaryValue* dict_value = NULL;
if (!extension->manifest()->GetDictionary(keys::kWebview,
&dict_value)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebview);
return false;
}
const base::ListValue* partition_list = NULL;
if (!dict_value->GetList(keys::kWebviewPartitions, &partition_list)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewPartitionsList);
return false;
}
// The partition list must have at least one entry.
if (partition_list->GetSize() == 0) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewPartitionsList);
return false;
}
for (size_t i = 0; i < partition_list->GetSize(); ++i) {
const base::DictionaryValue* partition = NULL;
if (!partition_list->GetDictionary(i, &partition)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewPartition, base::IntToString(i));
return false;
}
std::string partition_pattern;
if (!partition->GetString(keys::kWebviewName, &partition_pattern)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewPartitionName, base::IntToString(i));
return false;
}
const base::ListValue* url_list = NULL;
if (!partition->GetList(keys::kWebviewAccessibleResources,
&url_list)) {
*error = base::ASCIIToUTF16(
errors::kInvalidWebviewAccessibleResourcesList);
return false;
}
// The URL list should have at least one entry.
if (url_list->GetSize() == 0) {
*error = base::ASCIIToUTF16(
errors::kInvalidWebviewAccessibleResourcesList);
return false;
}
scoped_ptr<PartitionItem> partition_item(
new PartitionItem(partition_pattern));
for (size_t i = 0; i < url_list->GetSize(); ++i) {
std::string relative_path;
if (!url_list->GetString(i, &relative_path)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewAccessibleResource, base::IntToString(i));
return false;
}
URLPattern pattern(URLPattern::SCHEME_EXTENSION,
Extension::GetResourceURL(extension->url(),
relative_path).spec());
partition_item->AddPattern(pattern);
}
info->AddPartitionItem(partition_item.Pass());
}
extension->SetManifestData(keys::kWebviewAccessibleResources, info.release());
return true;
}
| 171,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct vqp_common_header_t *vqp_common_header;
const struct vqp_obj_tlv_t *vqp_obj_tlv;
const u_char *tptr;
uint16_t vqp_obj_len;
uint32_t vqp_obj_type;
int tlen;
uint8_t nitems;
tptr=pptr;
tlen = len;
vqp_common_header = (const struct vqp_common_header_t *)pptr;
ND_TCHECK(*vqp_common_header);
/*
* Sanity checking of the header.
*/
if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {
ND_PRINT((ndo, "VQP version %u packet not supported",
VQP_EXTRACT_VERSION(vqp_common_header->version)));
return;
}
/* in non-verbose mode just lets print the basic Message Type */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
nitems = vqp_common_header->nitems;
ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
EXTRACT_32BITS(&vqp_common_header->sequence),
nitems,
len));
/* skip VQP Common header */
tptr+=sizeof(const struct vqp_common_header_t);
tlen-=sizeof(const struct vqp_common_header_t);
while (nitems > 0 && tlen > 0) {
vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;
vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);
vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);
tptr+=sizeof(struct vqp_obj_tlv_t);
tlen-=sizeof(struct vqp_obj_tlv_t);
ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ",
tok2str(vqp_obj_values, "Unknown", vqp_obj_type),
vqp_obj_type, vqp_obj_len));
/* basic sanity check */
if (vqp_obj_type == 0 || vqp_obj_len ==0) {
return;
}
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, vqp_obj_len);
switch(vqp_obj_type) {
case VQP_OBJ_IP_ADDRESS:
ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_PORT_NAME:
case VQP_OBJ_VLAN_NAME:
case VQP_OBJ_VTP_DOMAIN:
case VQP_OBJ_ETHERNET_PKT:
safeputs(ndo, tptr, vqp_obj_len);
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_MAC_ADDRESS:
case VQP_OBJ_MAC_NULL:
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr)));
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len);
break;
}
tptr += vqp_obj_len;
tlen -= vqp_obj_len;
nitems--;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|VQP]"));
}
Commit Message: CVE-2017-13045/VQP: add some bounds checks
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct vqp_common_header_t *vqp_common_header;
const struct vqp_obj_tlv_t *vqp_obj_tlv;
const u_char *tptr;
uint16_t vqp_obj_len;
uint32_t vqp_obj_type;
u_int tlen;
uint8_t nitems;
tptr=pptr;
tlen = len;
vqp_common_header = (const struct vqp_common_header_t *)pptr;
ND_TCHECK(*vqp_common_header);
if (sizeof(struct vqp_common_header_t) > tlen)
goto trunc;
/*
* Sanity checking of the header.
*/
if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {
ND_PRINT((ndo, "VQP version %u packet not supported",
VQP_EXTRACT_VERSION(vqp_common_header->version)));
return;
}
/* in non-verbose mode just lets print the basic Message Type */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
nitems = vqp_common_header->nitems;
ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
EXTRACT_32BITS(&vqp_common_header->sequence),
nitems,
len));
/* skip VQP Common header */
tptr+=sizeof(const struct vqp_common_header_t);
tlen-=sizeof(const struct vqp_common_header_t);
while (nitems > 0 && tlen > 0) {
vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;
ND_TCHECK(*vqp_obj_tlv);
if (sizeof(struct vqp_obj_tlv_t) > tlen)
goto trunc;
vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);
vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);
tptr+=sizeof(struct vqp_obj_tlv_t);
tlen-=sizeof(struct vqp_obj_tlv_t);
ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ",
tok2str(vqp_obj_values, "Unknown", vqp_obj_type),
vqp_obj_type, vqp_obj_len));
/* basic sanity check */
if (vqp_obj_type == 0 || vqp_obj_len ==0) {
return;
}
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, vqp_obj_len);
if (vqp_obj_len > tlen)
goto trunc;
switch(vqp_obj_type) {
case VQP_OBJ_IP_ADDRESS:
if (vqp_obj_len != 4)
goto trunc;
ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_PORT_NAME:
case VQP_OBJ_VLAN_NAME:
case VQP_OBJ_VTP_DOMAIN:
case VQP_OBJ_ETHERNET_PKT:
safeputs(ndo, tptr, vqp_obj_len);
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_MAC_ADDRESS:
case VQP_OBJ_MAC_NULL:
if (vqp_obj_len != ETHER_ADDR_LEN)
goto trunc;
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr)));
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len);
break;
}
tptr += vqp_obj_len;
tlen -= vqp_obj_len;
nitems--;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|VQP]"));
}
| 167,830 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
Commit Message: Slightly different fix for #714
CWE ID: CWE-834 | static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
| 170,016 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLInputElement::HandleBlurEvent() {
input_type_->DisableSecureTextInput();
input_type_view_->HandleBlurEvent();
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void HTMLInputElement::HandleBlurEvent() {
input_type_view_->HandleBlurEvent();
}
| 171,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ChromeMockRenderThread::print_preview_pages_remaining() {
return print_preview_pages_remaining_;
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | int ChromeMockRenderThread::print_preview_pages_remaining() {
int ChromeMockRenderThread::print_preview_pages_remaining() const {
return print_preview_pages_remaining_;
}
| 170,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-254 | PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
| 165,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
{
opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */
OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256];
OPJ_UINT8 const* pLUT[3];
opj_image_t * image = NULL;
FILE *IN;
OPJ_BITMAPFILEHEADER File_h;
OPJ_BITMAPINFOHEADER Info_h;
OPJ_UINT32 i, palette_len, numcmpts = 1U;
OPJ_BOOL l_result = OPJ_FALSE;
OPJ_UINT8* pData = NULL;
OPJ_UINT32 stride;
pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B;
IN = fopen(filename, "rb");
if (!IN)
{
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return NULL;
}
if (!bmp_read_file_header(IN, &File_h)) {
fclose(IN);
return NULL;
}
if (!bmp_read_info_header(IN, &Info_h)) {
fclose(IN);
return NULL;
}
/* Load palette */
if (Info_h.biBitCount <= 8U)
{
memset(&lut_R[0], 0, sizeof(lut_R));
memset(&lut_G[0], 0, sizeof(lut_G));
memset(&lut_B[0], 0, sizeof(lut_B));
palette_len = Info_h.biClrUsed;
if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) {
palette_len = (1U << Info_h.biBitCount);
}
if (palette_len > 256U) {
palette_len = 256U;
}
if (palette_len > 0U) {
OPJ_UINT8 has_color = 0U;
for (i = 0U; i < palette_len; i++) {
lut_B[i] = (OPJ_UINT8)getc(IN);
lut_G[i] = (OPJ_UINT8)getc(IN);
lut_R[i] = (OPJ_UINT8)getc(IN);
(void)getc(IN); /* padding */
has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]);
}
if(has_color) {
numcmpts = 3U;
}
}
} else {
numcmpts = 3U;
if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) {
numcmpts++;
}
}
stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */
if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */
stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U;
}
pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8));
if (pData == NULL) {
fclose(IN);
return NULL;
}
/* Place the cursor at the beginning of the image information */
fseek(IN, 0, SEEK_SET);
fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
switch (Info_h.biCompression) {
case 0:
case 3:
/* read raw data */
l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
case 1:
/* read rle8 data */
l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
case 2:
/* read rle4 data */
l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
default:
fprintf(stderr, "Unsupported BMP compression\n");
l_result = OPJ_FALSE;
break;
}
if (!l_result) {
free(pData);
fclose(IN);
return NULL;
}
/* create the image */
memset(&cmptparm[0], 0, sizeof(cmptparm));
for(i = 0; i < 4U; i++)
{
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy;
cmptparm[i].w = Info_h.biWidth;
cmptparm[i].h = Info_h.biHeight;
}
image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB);
if(!image) {
fclose(IN);
free(pData);
return NULL;
}
if (numcmpts == 4U) {
image->comps[3].alpha = 1;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U;
image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U;
/* Read the data */
if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */
bmp24toimage(pData, stride, image);
}
else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */
bmp8toimage(pData, stride, image, pLUT);
}
else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/
bmp8toimage(pData, stride, image, pLUT);
}
else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/
bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */
}
else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */
bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U);
}
else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */
bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask);
}
else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */
bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U);
}
else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */
if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) {
Info_h.biRedMask = 0xF800U;
Info_h.biGreenMask = 0x07E0U;
Info_h.biBlueMask = 0x001FU;
}
bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask);
}
else {
opj_image_destroy(image);
image = NULL;
fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
}
free(pData);
fclose(IN);
return image;
}
Commit Message: Merge pull request #834 from trylab/issue833
Fix issue 833.
CWE ID: CWE-190 | opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
{
opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */
OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256];
OPJ_UINT8 const* pLUT[3];
opj_image_t * image = NULL;
FILE *IN;
OPJ_BITMAPFILEHEADER File_h;
OPJ_BITMAPINFOHEADER Info_h;
OPJ_UINT32 i, palette_len, numcmpts = 1U;
OPJ_BOOL l_result = OPJ_FALSE;
OPJ_UINT8* pData = NULL;
OPJ_UINT32 stride;
pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B;
IN = fopen(filename, "rb");
if (!IN)
{
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return NULL;
}
if (!bmp_read_file_header(IN, &File_h)) {
fclose(IN);
return NULL;
}
if (!bmp_read_info_header(IN, &Info_h)) {
fclose(IN);
return NULL;
}
/* Load palette */
if (Info_h.biBitCount <= 8U)
{
memset(&lut_R[0], 0, sizeof(lut_R));
memset(&lut_G[0], 0, sizeof(lut_G));
memset(&lut_B[0], 0, sizeof(lut_B));
palette_len = Info_h.biClrUsed;
if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) {
palette_len = (1U << Info_h.biBitCount);
}
if (palette_len > 256U) {
palette_len = 256U;
}
if (palette_len > 0U) {
OPJ_UINT8 has_color = 0U;
for (i = 0U; i < palette_len; i++) {
lut_B[i] = (OPJ_UINT8)getc(IN);
lut_G[i] = (OPJ_UINT8)getc(IN);
lut_R[i] = (OPJ_UINT8)getc(IN);
(void)getc(IN); /* padding */
has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]);
}
if(has_color) {
numcmpts = 3U;
}
}
} else {
numcmpts = 3U;
if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) {
numcmpts++;
}
}
if (Info_h.biWidth == 0 || Info_h.biHeight == 0) {
fclose(IN);
return NULL;
}
if (Info_h.biBitCount > (((OPJ_UINT32)-1) - 31) / Info_h.biWidth) {
fclose(IN);
return NULL;
}
stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */
if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */
if (8 > (((OPJ_UINT32)-1) - 31) / Info_h.biWidth) {
fclose(IN);
return NULL;
}
stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U;
}
if (stride > ((OPJ_UINT32)-1) / sizeof(OPJ_UINT8) / Info_h.biHeight) {
fclose(IN);
return NULL;
}
pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8));
if (pData == NULL) {
fclose(IN);
return NULL;
}
/* Place the cursor at the beginning of the image information */
fseek(IN, 0, SEEK_SET);
fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
switch (Info_h.biCompression) {
case 0:
case 3:
/* read raw data */
l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
case 1:
/* read rle8 data */
l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
case 2:
/* read rle4 data */
l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight);
break;
default:
fprintf(stderr, "Unsupported BMP compression\n");
l_result = OPJ_FALSE;
break;
}
if (!l_result) {
free(pData);
fclose(IN);
return NULL;
}
/* create the image */
memset(&cmptparm[0], 0, sizeof(cmptparm));
for(i = 0; i < 4U; i++)
{
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy;
cmptparm[i].w = Info_h.biWidth;
cmptparm[i].h = Info_h.biHeight;
}
image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB);
if(!image) {
fclose(IN);
free(pData);
return NULL;
}
if (numcmpts == 4U) {
image->comps[3].alpha = 1;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U;
image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U;
/* Read the data */
if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */
bmp24toimage(pData, stride, image);
}
else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */
bmp8toimage(pData, stride, image, pLUT);
}
else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/
bmp8toimage(pData, stride, image, pLUT);
}
else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/
bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */
}
else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */
bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U);
}
else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */
bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask);
}
else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */
bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U);
}
else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */
if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) {
Info_h.biRedMask = 0xF800U;
Info_h.biGreenMask = 0x07E0U;
Info_h.biBlueMask = 0x001FU;
}
bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask);
}
else {
opj_image_destroy(image);
image = NULL;
fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
}
free(pData);
fclose(IN);
return image;
}
| 168,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock, int flags,
int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
struct sockaddr_ieee802154 *saddr;
saddr = (struct sockaddr_ieee802154 *)msg->msg_name;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
saddr->addr = mac_cb(skb)->sa;
}
if (addr_len)
*addr_len = sizeof(*saddr);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock, int flags,
int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
struct sockaddr_ieee802154 *saddr;
saddr = (struct sockaddr_ieee802154 *)msg->msg_name;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
saddr->addr = mac_cb(skb)->sa;
*addr_len = sizeof(*saddr);
}
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
| 166,476 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
return 0;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125 | int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
return 0;
}
| 169,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name,
const char* event_name) {
base::CStringTokenizer category_group_tokens(
category_group_name, category_group_name + strlen(category_group_name),
",");
while (category_group_tokens.GetNext()) {
const std::string& category_group_token = category_group_tokens.token();
for (int i = 0; kEventArgsWhitelist[i][0] != NULL; ++i) {
DCHECK(kEventArgsWhitelist[i][1]);
if (base::MatchPattern(category_group_token.c_str(),
kEventArgsWhitelist[i][0]) &&
base::MatchPattern(event_name, kEventArgsWhitelist[i][1])) {
return true;
}
}
}
return false;
}
Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments
R=dsinclair,shatch
BUG=546093
Review URL: https://codereview.chromium.org/1415013003
Cr-Commit-Position: refs/heads/master@{#356690}
CWE ID: CWE-399 | bool IsTraceEventArgsWhitelisted(const char* category_group_name,
bool IsTraceArgumentNameWhitelisted(const char* const* granular_filter,
const char* arg_name) {
for (int i = 0; granular_filter[i] != nullptr; ++i) {
if (base::MatchPattern(arg_name, granular_filter[i]))
return true;
}
return false;
}
bool IsTraceEventArgsWhitelisted(
const char* category_group_name,
const char* event_name,
base::trace_event::ArgumentNameFilterPredicate* arg_name_filter) {
DCHECK(arg_name_filter);
base::CStringTokenizer category_group_tokens(
category_group_name, category_group_name + strlen(category_group_name),
",");
while (category_group_tokens.GetNext()) {
const std::string& category_group_token = category_group_tokens.token();
for (int i = 0; kEventArgsWhitelist[i].category_name != nullptr; ++i) {
const WhitelistEntry& whitelist_entry = kEventArgsWhitelist[i];
DCHECK(whitelist_entry.event_name);
if (base::MatchPattern(category_group_token.c_str(),
whitelist_entry.category_name) &&
base::MatchPattern(event_name, whitelist_entry.event_name)) {
if (whitelist_entry.arg_name_filter) {
*arg_name_filter = base::Bind(&IsTraceArgumentNameWhitelisted,
whitelist_entry.arg_name_filter);
}
return true;
}
}
}
return false;
}
| 171,680 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void local_socket_close(asocket* s) {
adb_mutex_lock(&socket_list_lock);
local_socket_close_locked(s);
adb_mutex_unlock(&socket_list_lock);
}
Commit Message: adb: switch the socket list mutex to a recursive_mutex.
sockets.cpp was branching on whether a socket close function was
local_socket_close in order to avoid a potential deadlock if the socket
list lock was held while closing a peer socket.
Bug: http://b/28347842
Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3
(cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa)
CWE ID: CWE-264 | static void local_socket_close(asocket* s) {
| 174,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_tsquery(char *buf,
PushFunction pushval,
Datum opaque,
bool isplain)
{
struct TSQueryParserStateData state;
int i;
TSQuery query;
int commonlen;
QueryItem *ptr;
ListCell *cell;
/* init state */
state.buffer = buf;
state.buf = buf;
state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND;
state.count = 0;
state.polstr = NIL;
/* init value parser's state */
state.valstate = init_tsvector_parser(state.buffer, true, true);
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state, pushval, opaque);
close_tsvector_parser(state.valstate);
if (list_length(state.polstr) == 0)
{
ereport(NOTICE,
(errmsg("text-search query doesn't contain lexemes: \"%s\"",
state.buffer)));
query = (TSQuery) palloc(HDRSIZETQ);
SET_VARSIZE(query, HDRSIZETQ);
query->size = 0;
return query;
}
/* Pack the QueryItems in the final TSQuery struct to return to caller */
commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);
query = (TSQuery) palloc0(commonlen);
SET_VARSIZE(query, commonlen);
query->size = list_length(state.polstr);
ptr = GETQUERY(query);
/* Copy QueryItems to TSQuery */
i = 0;
foreach(cell, state.polstr)
{
QueryItem *item = (QueryItem *) lfirst(cell);
switch (item->type)
{
case QI_VAL:
memcpy(&ptr[i], item, sizeof(QueryOperand));
break;
case QI_VALSTOP:
ptr[i].type = QI_VALSTOP;
break;
case QI_OPR:
memcpy(&ptr[i], item, sizeof(QueryOperator));
break;
default:
elog(ERROR, "unrecognized QueryItem type: %d", item->type);
}
i++;
}
/* Copy all the operand strings to TSQuery */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* Set left operand pointers for every operator. */
findoprnd(ptr, query->size);
return query;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | parse_tsquery(char *buf,
PushFunction pushval,
Datum opaque,
bool isplain)
{
struct TSQueryParserStateData state;
int i;
TSQuery query;
int commonlen;
QueryItem *ptr;
ListCell *cell;
/* init state */
state.buffer = buf;
state.buf = buf;
state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND;
state.count = 0;
state.polstr = NIL;
/* init value parser's state */
state.valstate = init_tsvector_parser(state.buffer, true, true);
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state, pushval, opaque);
close_tsvector_parser(state.valstate);
if (list_length(state.polstr) == 0)
{
ereport(NOTICE,
(errmsg("text-search query doesn't contain lexemes: \"%s\"",
state.buffer)));
query = (TSQuery) palloc(HDRSIZETQ);
SET_VARSIZE(query, HDRSIZETQ);
query->size = 0;
return query;
}
if (TSQUERY_TOO_BIG(list_length(state.polstr), state.sumlen))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("tsquery is too large")));
commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);
/* Pack the QueryItems in the final TSQuery struct to return to caller */
query = (TSQuery) palloc0(commonlen);
SET_VARSIZE(query, commonlen);
query->size = list_length(state.polstr);
ptr = GETQUERY(query);
/* Copy QueryItems to TSQuery */
i = 0;
foreach(cell, state.polstr)
{
QueryItem *item = (QueryItem *) lfirst(cell);
switch (item->type)
{
case QI_VAL:
memcpy(&ptr[i], item, sizeof(QueryOperand));
break;
case QI_VALSTOP:
ptr[i].type = QI_VALSTOP;
break;
case QI_OPR:
memcpy(&ptr[i], item, sizeof(QueryOperator));
break;
default:
elog(ERROR, "unrecognized QueryItem type: %d", item->type);
}
i++;
}
/* Copy all the operand strings to TSQuery */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* Set left operand pointers for every operator. */
findoprnd(ptr, query->size);
return query;
}
| 166,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
Commit Message: Fix a wrong check in rfc_parse_data
Bug: 78288018
Bug: 111436796
Test: manual
Change-Id: I16e6026acbaac230fe1453bbac040d1b75bcea2a
(cherry picked from commit d1ced302cd1066087588c891027b1756be31db46)
CWE ID: CWE-125 | uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
eal = *(p_data)&RFCOMM_EA;
len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1;
if (eal == 0 && p_buf->len > RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
android_errorWriteLog(0x534e4554, "78288018");
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
| 174,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfssvc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_writeargs *args)
{
unsigned int len, hdr, dlen;
struct kvec *head = rqstp->rq_arg.head;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p++; /* beginoffset */
args->offset = ntohl(*p++); /* offset */
p++; /* totalcount */
len = args->len = ntohl(*p++);
/*
* The protocol specifies a maximum of 8192 bytes.
*/
if (len > NFSSVC_MAXBLKSIZE_V2)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
dlen = head->iov_len + rqstp->rq_arg.page_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
Commit Message: nfsd: stricter decoding of write-like NFSv2/v3 ops
The NFSv2/v3 code does not systematically check whether we decode past
the end of the buffer. This generally appears to be harmless, but there
are a few places where we do arithmetic on the pointers involved and
don't account for the possibility that a length could be negative. Add
checks to catch these.
Reported-by: Tuomas Haanpää <[email protected]>
Reported-by: Ari Kauppi <[email protected]>
Reviewed-by: NeilBrown <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-119 | nfssvc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_writeargs *args)
{
unsigned int len, hdr, dlen;
struct kvec *head = rqstp->rq_arg.head;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p++; /* beginoffset */
args->offset = ntohl(*p++); /* offset */
p++; /* totalcount */
len = args->len = ntohl(*p++);
/*
* The protocol specifies a maximum of 8192 bytes.
*/
if (len > NFSSVC_MAXBLKSIZE_V2)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
if (hdr > head->iov_len)
return 0;
dlen = head->iov_len + rqstp->rq_arg.page_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
| 168,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsController::OnSpeechFinished(
int request_id, const std::string& error_message) {
if (!current_utterance_ || request_id != current_utterance_->id())
return;
current_utterance_->set_error(error_message);
FinishCurrentUtterance();
SpeakNextUtterance();
}
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 | void ExtensionTtsController::OnSpeechFinished(
| 170,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
len = plain->resplen;
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
| 169,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void * calloc(size_t n, size_t lb)
{
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Commit Message: Fix calloc() overflow
* malloc.c (calloc): Check multiplication overflow in calloc(),
assuming REDIRECT_MALLOC.
CWE ID: CWE-189 | void * calloc(size_t n, size_t lb)
{
if (lb && n > SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
| 165,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_list_algorithms)
{
char **modules;
char *lib_dir = MCG(algorithms_dir);
int lib_dir_len;
int i, count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
&lib_dir, &lib_dir_len) == FAILURE) {
return;
}
array_init(return_value);
modules = mcrypt_list_algorithms(lib_dir, &count);
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
}
for (i = 0; i < count; i++) {
add_index_string(return_value, i, modules[i], 1);
}
mcrypt_free_p(modules, count);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_list_algorithms)
{
char **modules;
char *lib_dir = MCG(algorithms_dir);
int lib_dir_len;
int i, count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
&lib_dir, &lib_dir_len) == FAILURE) {
return;
}
array_init(return_value);
modules = mcrypt_list_algorithms(lib_dir, &count);
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
}
for (i = 0; i < count; i++) {
add_index_string(return_value, i, modules[i], 1);
}
mcrypt_free_p(modules, count);
}
| 167,102 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
ImageBitmapRejectionReason reason) {
switch (reason) {
case kUndecodableImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The source image could not be decoded."));
break;
case kAllocationFailureImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The ImageBitmap could not be allocated."));
break;
default:
NOTREACHED();
}
factory_->DidFinishLoading(this);
}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416 | void ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
ImageBitmapRejectionReason reason) {
switch (reason) {
case kUndecodableImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The source image could not be decoded."));
break;
case kAllocationFailureImageBitmapRejectionReason:
resolver_->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"The ImageBitmap could not be allocated."));
break;
default:
NOTREACHED();
}
loader_.reset();
factory_->DidFinishLoading(this);
}
| 173,069 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetOutputInfoReply rep;
xRRGetOutputInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRROutputInfo *xoi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetOutputInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetOutputInfo;
req->output = output;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
nbytes = ((long) (rep.length) << 2) - OutputInfoExtra;
nbytesRead = (long) (rep.nCrtcs * 4 +
rep.nCrtcs * sizeof (RRCrtc) +
rep.nModes * sizeof (RRMode) +
rep.nClones * sizeof (RROutput) +
rep.nameLength + 1); /* '\0' terminate name */
xoi = (XRROutputInfo *) Xmalloc(rbytes);
if (xoi == NULL) {
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
xoi->timestamp = rep.timestamp;
xoi->crtc = rep.crtc;
xoi->mm_width = rep.mmWidth;
xoi->mm_height = rep.mmHeight;
xoi->connection = rep.connection;
xoi->subpixel_order = rep.subpixelOrder;
xoi->ncrtc = rep.nCrtcs;
xoi->crtcs = (RRCrtc *) (xoi + 1);
xoi->nmode = rep.nModes;
xoi->npreferred = rep.nPreferred;
xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs);
xoi->nclone = rep.nClones;
xoi->clones = (RROutput *) (xoi->modes + rep.nModes);
xoi->name = (char *) (xoi->clones + rep.nClones);
_XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2);
_XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2);
_XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2);
/*
* Read name and '\0' terminate
*/
_XReadPad (dpy, xoi->name, rep.nameLength);
xoi->name[rep.nameLength] = '\0';
xoi->nameLen = rep.nameLength;
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRROutputInfo *) xoi;
}
Commit Message:
CWE ID: CWE-787 | XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetOutputInfoReply rep;
xRRGetOutputInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRROutputInfo *xoi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetOutputInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetOutputInfo;
req->output = output;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
if (rep.length > INT_MAX >> 2 || rep.length < (OutputInfoExtra >> 2))
{
if (rep.length > (OutputInfoExtra >> 2))
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
else
_XEatDataWords (dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = ((long) (rep.length) << 2) - OutputInfoExtra;
nbytesRead = (long) (rep.nCrtcs * 4 +
rep.nCrtcs * sizeof (RRCrtc) +
rep.nModes * sizeof (RRMode) +
rep.nClones * sizeof (RROutput) +
rep.nameLength + 1); /* '\0' terminate name */
xoi = (XRROutputInfo *) Xmalloc(rbytes);
if (xoi == NULL) {
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
xoi->timestamp = rep.timestamp;
xoi->crtc = rep.crtc;
xoi->mm_width = rep.mmWidth;
xoi->mm_height = rep.mmHeight;
xoi->connection = rep.connection;
xoi->subpixel_order = rep.subpixelOrder;
xoi->ncrtc = rep.nCrtcs;
xoi->crtcs = (RRCrtc *) (xoi + 1);
xoi->nmode = rep.nModes;
xoi->npreferred = rep.nPreferred;
xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs);
xoi->nclone = rep.nClones;
xoi->clones = (RROutput *) (xoi->modes + rep.nModes);
xoi->name = (char *) (xoi->clones + rep.nClones);
_XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2);
_XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2);
_XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2);
/*
* Read name and '\0' terminate
*/
_XReadPad (dpy, xoi->name, rep.nameLength);
xoi->name[rep.nameLength] = '\0';
xoi->nameLen = rep.nameLength;
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRROutputInfo *) xoi;
}
| 164,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NavigationControllerImpl::Reload(ReloadType reload_type,
bool check_for_repost) {
DCHECK_NE(ReloadType::NONE, reload_type);
if (transient_entry_index_ != -1) {
NavigationEntryImpl* transient_entry = GetTransientEntry();
if (!transient_entry)
return;
LoadURL(transient_entry->GetURL(),
Referrer(),
ui::PAGE_TRANSITION_RELOAD,
transient_entry->extra_headers());
return;
}
NavigationEntryImpl* entry = nullptr;
int current_index = -1;
if (IsInitialNavigation() && pending_entry_) {
entry = pending_entry_;
current_index = pending_entry_index_;
} else {
DiscardNonCommittedEntriesInternal();
current_index = GetCurrentEntryIndex();
if (current_index != -1) {
entry = GetEntryAtIndex(current_index);
}
}
if (!entry)
return;
if (last_committed_reload_type_ != ReloadType::NONE) {
DCHECK(!last_committed_reload_time_.is_null());
base::Time now =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DCHECK_GT(now, last_committed_reload_time_);
if (!last_committed_reload_time_.is_null() &&
now > last_committed_reload_time_) {
base::TimeDelta delta = now - last_committed_reload_time_;
UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration",
delta);
if (last_committed_reload_type_ == ReloadType::NORMAL) {
UMA_HISTOGRAM_MEDIUM_TIMES(
"Navigation.Reload.ReloadMainResourceToReloadDuration", delta);
}
}
}
entry->set_reload_type(reload_type);
if (g_check_for_repost && check_for_repost &&
entry->GetHasPostData()) {
delegate_->NotifyBeforeFormRepostWarningShow();
pending_reload_ = reload_type;
delegate_->ActivateAndShowRepostFormWarningDialog();
} else {
if (!IsInitialNavigation())
DiscardNonCommittedEntriesInternal();
SiteInstanceImpl* site_instance = entry->site_instance();
bool is_for_guests_only = site_instance && site_instance->HasProcess() &&
site_instance->GetProcess()->IsForGuestsOnly();
if (!is_for_guests_only && site_instance &&
site_instance->HasWrongProcessForURL(entry->GetURL())) {
NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(),
entry->GetTransitionType(), false,
entry->extra_headers(), browser_context_,
nullptr /* blob_url_loader_factory */)
.release());
reload_type = ReloadType::NONE;
nav_entry->set_should_replace_entry(true);
pending_entry_ = nav_entry;
DCHECK_EQ(-1, pending_entry_index_);
} else {
pending_entry_ = entry;
pending_entry_index_ = current_index;
pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
}
NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */);
}
}
Commit Message: Preserve renderer-initiated bit when reloading in a new process.
BUG=847718
TEST=See bug for repro steps.
Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227
Reviewed-on: https://chromium-review.googlesource.com/1080235
Commit-Queue: Charlie Reis <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563312}
CWE ID: | void NavigationControllerImpl::Reload(ReloadType reload_type,
bool check_for_repost) {
DCHECK_NE(ReloadType::NONE, reload_type);
if (transient_entry_index_ != -1) {
NavigationEntryImpl* transient_entry = GetTransientEntry();
if (!transient_entry)
return;
LoadURL(transient_entry->GetURL(),
Referrer(),
ui::PAGE_TRANSITION_RELOAD,
transient_entry->extra_headers());
return;
}
NavigationEntryImpl* entry = nullptr;
int current_index = -1;
if (IsInitialNavigation() && pending_entry_) {
entry = pending_entry_;
current_index = pending_entry_index_;
} else {
DiscardNonCommittedEntriesInternal();
current_index = GetCurrentEntryIndex();
if (current_index != -1) {
entry = GetEntryAtIndex(current_index);
}
}
if (!entry)
return;
if (last_committed_reload_type_ != ReloadType::NONE) {
DCHECK(!last_committed_reload_time_.is_null());
base::Time now =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DCHECK_GT(now, last_committed_reload_time_);
if (!last_committed_reload_time_.is_null() &&
now > last_committed_reload_time_) {
base::TimeDelta delta = now - last_committed_reload_time_;
UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration",
delta);
if (last_committed_reload_type_ == ReloadType::NORMAL) {
UMA_HISTOGRAM_MEDIUM_TIMES(
"Navigation.Reload.ReloadMainResourceToReloadDuration", delta);
}
}
}
entry->set_reload_type(reload_type);
if (g_check_for_repost && check_for_repost &&
entry->GetHasPostData()) {
delegate_->NotifyBeforeFormRepostWarningShow();
pending_reload_ = reload_type;
delegate_->ActivateAndShowRepostFormWarningDialog();
} else {
if (!IsInitialNavigation())
DiscardNonCommittedEntriesInternal();
SiteInstanceImpl* site_instance = entry->site_instance();
bool is_for_guests_only = site_instance && site_instance->HasProcess() &&
site_instance->GetProcess()->IsForGuestsOnly();
if (!is_for_guests_only && site_instance &&
site_instance->HasWrongProcessForURL(entry->GetURL())) {
NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(),
entry->GetTransitionType(), false,
entry->extra_headers(), browser_context_,
nullptr /* blob_url_loader_factory */)
.release());
reload_type = ReloadType::NONE;
nav_entry->set_should_replace_entry(true);
nav_entry->set_is_renderer_initiated(entry->is_renderer_initiated());
pending_entry_ = nav_entry;
DCHECK_EQ(-1, pending_entry_index_);
} else {
pending_entry_ = entry;
pending_entry_index_ = current_index;
pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
}
NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */);
}
}
| 173,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: asn1_get_octet_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *str_len)
{
int len_len;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
/* if(str==NULL) return ASN1_SUCCESS; */
*str_len = asn1_get_length_der (der, der_len, &len_len);
if (*str_len < 0)
return ASN1_DER_ERROR;
*ret_len = *str_len + len_len;
if (str_size >= *str_len)
memcpy (str, der + len_len, *str_len);
else
{
return ASN1_MEM_ERROR;
}
return ASN1_SUCCESS;
}
Commit Message:
CWE ID: CWE-189 | asn1_get_octet_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *str_len)
{
int len_len = 0;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
/* if(str==NULL) return ASN1_SUCCESS; */
*str_len = asn1_get_length_der (der, der_len, &len_len);
if (*str_len < 0)
return ASN1_DER_ERROR;
*ret_len = *str_len + len_len;
if (str_size >= *str_len)
memcpy (str, der + len_len, *str_len);
else
{
return ASN1_MEM_ERROR;
}
return ASN1_SUCCESS;
}
| 165,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick || list->next == NULL) {
g_hash_table_remove(channel->nicks, nick->nick);
if (list->next != NULL) {
g_hash_table_insert(channel->nicks, nick->next->nick,
nick->next);
}
} else {
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
}
Commit Message: Merge branch 'security' into 'master'
Security
Closes #10
See merge request !17
CWE ID: CWE-416 | static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list, *newlist;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick) {
newlist = nick->next;
} else {
newlist = list;
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
g_hash_table_remove(channel->nicks, nick->nick);
if (newlist != NULL) {
g_hash_table_insert(channel->nicks, newlist->nick,
newlist);
}
}
| 168,057 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: is_link_trusted (NautilusFile *file,
gboolean is_launcher)
{
GFile *location;
gboolean res;
if (!is_launcher)
{
return TRUE;
}
if (nautilus_file_can_execute (file))
{
return TRUE;
}
res = FALSE;
if (nautilus_file_is_local (file))
{
location = nautilus_file_get_location (file);
res = nautilus_is_in_system_dir (location);
g_object_unref (location);
}
return res;
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | is_link_trusted (NautilusFile *file,
gboolean is_launcher)
{
GFile *location;
gboolean res;
g_autofree gchar* trusted = NULL;
if (!is_launcher)
{
return TRUE;
}
trusted = nautilus_file_get_metadata (file,
NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED,
NULL);
if (nautilus_file_can_execute (file) && trusted != NULL)
{
return TRUE;
}
res = FALSE;
if (nautilus_file_is_local (file))
{
location = nautilus_file_get_location (file);
res = nautilus_is_in_system_dir (location);
g_object_unref (location);
}
return res;
}
| 167,746 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
switch (l3_proto) {
case ETH_P_IP:
l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, sizeof(struct ip_header));
if (bytes_read < sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
Commit Message:
CWE ID: CWE-119 | static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < sizeof(struct eth_header)) {
l2_hdr->iov_len = 0;
return false;
}
l2_hdr->iov_len = sizeof(struct eth_header);
switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {
case ETH_P_VLAN:
l2_hdr->iov_len += sizeof(struct vlan_header);
break;
case ETH_P_DVLAN:
l2_hdr->iov_len += 2 * sizeof(struct vlan_header);
break;
}
if (bytes_read < l2_hdr->iov_len) {
l2_hdr->iov_len = 0;
return false;
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
switch (l3_proto) {
case ETH_P_IP:
l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, sizeof(struct ip_header));
if (bytes_read < sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
if(l3_hdr->iov_len < sizeof(struct ip_header))
{
l3_hdr->iov_len = 0;
return false;
}
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
| 164,950 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
if (callbacks.on_cached_encoded_logo_available) {
std::move(callbacks.on_cached_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_cached_decoded_logo_available) {
std::move(callbacks.on_cached_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_encoded_logo_available) {
std::move(callbacks.on_fresh_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_decoded_logo_available) {
std::move(callbacks.on_fresh_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
| 171,958 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FailStoreGroup() {
PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup,
base::Unretained(this)));
const int64_t kTooBig = 10 * 1024 * 1024; // 10M
group_ =
new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId());
cache_ = new AppCache(storage(), storage()->NewCacheId());
cache_->AddEntry(kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, 1, kTooBig));
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async.
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void FailStoreGroup() {
void FailStoreGroup_SizeTooBig() {
PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup,
base::Unretained(this)));
// Set up some preconditions. Create a group and newest cache that
const int64_t kTooBig = 10 * 1024 * 1024; // 10M
group_ =
new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId());
cache_ = new AppCache(storage(), storage()->NewCacheId());
cache_->AddEntry(kManifestUrl, AppCacheEntry(AppCacheEntry::MANIFEST,
/*response_id=*/1,
/*response_size=*/kTooBig,
/*padding_size=*/0));
// Hold a ref to the cache to simulate the UpdateJob holding that ref,
// and hold a ref to the group to simulate the CacheHost holding that ref.
// Conduct the store test.
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async.
}
void FailStoreGroup_PaddingTooBig() {
// Store a group and its newest cache. Should complete asynchronously.
PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_FailStoreGroup,
base::Unretained(this)));
// Set up some preconditions. Create a group and newest cache that
// appear to be "unstored" and big enough to exceed the 5M limit.
const int64_t kTooBig = 10 * 1024 * 1024; // 10M
group_ =
new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId());
cache_ = new AppCache(storage(), storage()->NewCacheId());
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT,
/*response_id=*/1,
/*response_size=*/1,
/*padding_size=*/kTooBig));
// Hold a ref to the cache to simulate the UpdateJob holding that ref,
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_); // Expected to be async.
}
| 172,985 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothOptionsHandler::GenerateFakeDiscoveredDevice(
const std::string& name,
const std::string& address,
const std::string& icon,
bool paired,
bool connected) {
DictionaryValue device;
device.SetString("name", name);
device.SetString("address", address);
device.SetString("icon", icon);
device.SetBoolean("paired", paired);
device.SetBoolean("connected", connected);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.addBluetoothDevice", device);
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void BluetoothOptionsHandler::GenerateFakeDiscoveredDevice(
void BluetoothOptionsHandler::GenerateFakeDevice(
const std::string& name,
const std::string& address,
const std::string& icon,
bool paired,
| 170,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int SeekHead::GetCount() const
{
return m_entry_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | int SeekHead::GetCount() const
const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const {
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
| 174,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragInOrderSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = BuildTestPacket(id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p1, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p3, NULL);
if (reassembled == NULL) {
goto end;
}
if (IPV4_GET_HLEN(reassembled) != 20) {
goto end;
}
if (IPV4_GET_IPLEN(reassembled) != 39) {
goto end;
}
/* 20 bytes in we should find 8 bytes of A. */
for (i = 20; i < 20 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A') {
goto end;
}
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 28; i < 28 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B') {
goto end;
}
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 36; i < 36 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragInOrderSimpleTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;
Packet *reassembled = NULL;
int id = 12;
int i;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8);
if (p2 == NULL)
goto end;
p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3);
if (p3 == NULL)
goto end;
if (Defrag(NULL, NULL, p1, NULL) != NULL)
goto end;
if (Defrag(NULL, NULL, p2, NULL) != NULL)
goto end;
reassembled = Defrag(NULL, NULL, p3, NULL);
if (reassembled == NULL) {
goto end;
}
if (IPV4_GET_HLEN(reassembled) != 20) {
goto end;
}
if (IPV4_GET_IPLEN(reassembled) != 39) {
goto end;
}
/* 20 bytes in we should find 8 bytes of A. */
for (i = 20; i < 20 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'A') {
goto end;
}
}
/* 28 bytes in we should find 8 bytes of B. */
for (i = 28; i < 28 + 8; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'B') {
goto end;
}
}
/* And 36 bytes in we should find 3 bytes of C. */
for (i = 36; i < 36 + 3; i++) {
if (GET_PKT_DATA(reassembled)[i] != 'C')
goto end;
}
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
if (p3 != NULL)
SCFree(p3);
if (reassembled != NULL)
SCFree(reassembled);
DefragDestroy();
return ret;
}
| 168,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
| 167,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK_EQ(-1, mapped_file_);
if (options.size == 0) return false;
if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
base::ThreadRestrictions::ScopedAllowIO allow_io;
FILE *fp;
bool fix_size = true;
FilePath path;
if (options.name == NULL || options.name->empty()) {
DCHECK(!options.open_existing);
fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable);
if (fp) {
if (unlink(path.value().c_str()))
PLOG(WARNING) << "unlink";
}
} else {
if (!FilePathForMemoryName(*options.name, &path))
return false;
fp = file_util::OpenFile(path, "w+x");
if (fp == NULL && options.open_existing) {
fp = file_util::OpenFile(path, "a+");
fix_size = false;
}
}
if (fp && fix_size) {
struct stat stat;
if (fstat(fileno(fp), &stat) != 0) {
file_util::CloseFile(fp);
return false;
}
const size_t current_size = stat.st_size;
if (current_size != options.size) {
if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) {
file_util::CloseFile(fp);
return false;
}
}
requested_size_ = options.size;
}
if (fp == NULL) {
#if !defined(OS_MACOSX)
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
FilePath dir = path.DirName();
if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
if (dir.value() == "/dev/shm") {
LOG(FATAL) << "This is frequently caused by incorrect permissions on "
<< "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
}
}
#else
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
#endif
return false;
}
return PrepareMapFile(fp);
}
Commit Message: Posix: fix named SHM mappings permissions.
Make sure that named mappings in /dev/shm/ aren't created with
broad permissions.
BUG=254159
[email protected], [email protected]
Review URL: https://codereview.chromium.org/17779002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209814 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK_EQ(-1, mapped_file_);
if (options.size == 0) return false;
if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
base::ThreadRestrictions::ScopedAllowIO allow_io;
FILE *fp;
bool fix_size = true;
FilePath path;
if (options.name == NULL || options.name->empty()) {
DCHECK(!options.open_existing);
fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable);
if (fp) {
if (unlink(path.value().c_str()))
PLOG(WARNING) << "unlink";
}
} else {
if (!FilePathForMemoryName(*options.name, &path))
return false;
// Make sure that the file is opened without any permission
// to other users on the system.
const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
// First, try to create the file.
int fd = HANDLE_EINTR(
open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
if (fd == -1 && options.open_existing) {
// If this doesn't work, try and open an existing file in append mode.
// Opening an existing file in a world writable directory has two main
// security implications:
// - Attackers could plant a file under their control, so ownership of
// the file is checked below.
// - Attackers could plant a symbolic link so that an unexpected file
// is opened, so O_NOFOLLOW is passed to open().
fd = HANDLE_EINTR(
open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
// Check that the current user owns the file.
// If uid != euid, then a more complex permission model is used and this
// API is not appropriate.
const uid_t real_uid = getuid();
const uid_t effective_uid = geteuid();
struct stat sb;
if (fd >= 0 &&
(fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
sb.st_uid != effective_uid)) {
LOG(ERROR) <<
"Invalid owner when opening existing shared memory file.";
HANDLE_EINTR(close(fd));
return false;
}
// An existing file was opened, so its size should not be fixed.
fix_size = false;
}
fp = NULL;
if (fd >= 0) {
// "a+" is always appropriate: if it's a new file, a+ is similar to w+.
fp = fdopen(fd, "a+");
}
}
if (fp && fix_size) {
struct stat stat;
if (fstat(fileno(fp), &stat) != 0) {
file_util::CloseFile(fp);
return false;
}
const size_t current_size = stat.st_size;
if (current_size != options.size) {
if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) {
file_util::CloseFile(fp);
return false;
}
}
requested_size_ = options.size;
}
if (fp == NULL) {
#if !defined(OS_MACOSX)
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
FilePath dir = path.DirName();
if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
if (dir.value() == "/dev/shm") {
LOG(FATAL) << "This is frequently caused by incorrect permissions on "
<< "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
}
}
#else
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
#endif
return false;
}
return PrepareMapFile(fp);
}
| 171,197 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
GetRenderManager()->set_interstitial_page(interstitial_page);
CancelActiveAndPendingDialogs();
for (auto& observer : observers_)
observer.DidAttachInterstitialPage();
if (frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(
static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
interstitial_page->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(!interstitial_page_ && interstitial_page);
interstitial_page_ = interstitial_page;
CancelActiveAndPendingDialogs();
for (auto& observer : observers_)
observer.DidAttachInterstitialPage();
if (frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(
static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
interstitial_page->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
}
| 172,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font)
{
int code = 0;
font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42");
if (!font->font)
return gs_throw(gs_error_VMerror, "out of memory");
/* no shortage of things to initialize */
{
gs_font_type42 *p42 = (gs_font_type42*) font->font;
/* Common to all fonts: */
p42->next = 0;
p42->prev = 0;
p42->memory = ctx->memory;
p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */
p42->base = font->font; /* NB also set by gs_definefont later */
p42->is_resource = false;
gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory));
p42->id = gs_next_ids(ctx->memory, 1);
p42->client_data = font; /* that's us */
/* this is overwritten in grid_fit() */
gs_make_identity(&p42->FontMatrix);
gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */
p42->FontType = ft_TrueType;
p42->BitmapWidths = false;
p42->ExactSize = fbit_use_outlines;
p42->InBetweenSize = fbit_use_outlines;
p42->TransformedChar = fbit_use_outlines;
p42->WMode = 0;
p42->PaintType = 0;
p42->StrokeWidth = 0;
p42->is_cached = 0;
p42->procs.define_font = gs_no_define_font;
p42->procs.make_font = gs_no_make_font;
p42->procs.font_info = gs_type42_font_info;
p42->procs.same_font = gs_default_same_font;
p42->procs.encode_char = xps_true_callback_encode_char;
p42->procs.decode_glyph = xps_true_callback_decode_glyph;
p42->procs.enumerate_glyph = gs_type42_enumerate_glyph;
p42->procs.glyph_info = gs_type42_glyph_info;
p42->procs.glyph_outline = gs_type42_glyph_outline;
p42->procs.glyph_name = xps_true_callback_glyph_name;
p42->procs.init_fstack = gs_default_init_fstack;
p42->procs.next_char_glyph = gs_default_next_char_glyph;
p42->procs.build_char = xps_true_callback_build_char;
memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars));
xps_load_sfnt_name(font, (char*)p42->font_name.chars);
p42->font_name.size = strlen((char*)p42->font_name.chars);
memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));
strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars);
p42->key_name.size = strlen((char*)p42->key_name.chars);
/* Base font specific: */
p42->FontBBox.p.x = 0;
p42->FontBBox.p.y = 0;
p42->FontBBox.q.x = 0;
p42->FontBBox.q.y = 0;
uid_set_UniqueID(&p42->UID, p42->id);
p42->encoding_index = ENCODING_INDEX_UNKNOWN;
p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1;
p42->FAPI = 0;
p42->FAPI_font_data = 0;
/* Type 42 specific: */
p42->data.string_proc = xps_true_callback_string_proc;
p42->data.proc_data = font;
gs_type42_font_init(p42, font->subfontid);
p42->data.get_glyph_index = xps_true_get_glyph_index;
}
if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) {
return(code);
}
code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length);
return code;
}
Commit Message:
CWE ID: CWE-119 | xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font)
{
int code = 0;
font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42");
if (!font->font)
return gs_throw(gs_error_VMerror, "out of memory");
/* no shortage of things to initialize */
{
gs_font_type42 *p42 = (gs_font_type42*) font->font;
/* Common to all fonts: */
p42->next = 0;
p42->prev = 0;
p42->memory = ctx->memory;
p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */
p42->base = font->font; /* NB also set by gs_definefont later */
p42->is_resource = false;
gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory));
p42->id = gs_next_ids(ctx->memory, 1);
p42->client_data = font; /* that's us */
/* this is overwritten in grid_fit() */
gs_make_identity(&p42->FontMatrix);
gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */
p42->FontType = ft_TrueType;
p42->BitmapWidths = false;
p42->ExactSize = fbit_use_outlines;
p42->InBetweenSize = fbit_use_outlines;
p42->TransformedChar = fbit_use_outlines;
p42->WMode = 0;
p42->PaintType = 0;
p42->StrokeWidth = 0;
p42->is_cached = 0;
p42->procs.define_font = gs_no_define_font;
p42->procs.make_font = gs_no_make_font;
p42->procs.font_info = gs_type42_font_info;
p42->procs.same_font = gs_default_same_font;
p42->procs.encode_char = xps_true_callback_encode_char;
p42->procs.decode_glyph = xps_true_callback_decode_glyph;
p42->procs.enumerate_glyph = gs_type42_enumerate_glyph;
p42->procs.glyph_info = gs_type42_glyph_info;
p42->procs.glyph_outline = gs_type42_glyph_outline;
p42->procs.glyph_name = xps_true_callback_glyph_name;
p42->procs.init_fstack = gs_default_init_fstack;
p42->procs.next_char_glyph = gs_default_next_char_glyph;
p42->procs.build_char = xps_true_callback_build_char;
memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars));
xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars));
p42->font_name.size = strlen((char*)p42->font_name.chars);
memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));
strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars);
p42->key_name.size = strlen((char*)p42->key_name.chars);
/* Base font specific: */
p42->FontBBox.p.x = 0;
p42->FontBBox.p.y = 0;
p42->FontBBox.q.x = 0;
p42->FontBBox.q.y = 0;
uid_set_UniqueID(&p42->UID, p42->id);
p42->encoding_index = ENCODING_INDEX_UNKNOWN;
p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1;
p42->FAPI = 0;
p42->FAPI_font_data = 0;
/* Type 42 specific: */
p42->data.string_proc = xps_true_callback_string_proc;
p42->data.proc_data = font;
gs_type42_font_init(p42, font->subfontid);
p42->data.get_glyph_index = xps_true_get_glyph_index;
}
if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) {
return(code);
}
code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length);
return code;
}
| 164,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
| 167,949 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device *rcv = NULL;
struct veth_priv *priv, *rcv_priv;
struct veth_net_stats *stats, *rcv_stats;
int length;
priv = netdev_priv(dev);
rcv = priv->peer;
rcv_priv = netdev_priv(rcv);
stats = this_cpu_ptr(priv->stats);
rcv_stats = this_cpu_ptr(rcv_priv->stats);
if (!(rcv->flags & IFF_UP))
goto tx_drop;
if (dev->features & NETIF_F_NO_CSUM)
skb->ip_summed = rcv_priv->ip_summed;
length = skb->len + ETH_HLEN;
if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS)
goto rx_drop;
stats->tx_bytes += length;
stats->tx_packets++;
rcv_stats->rx_bytes += length;
rcv_stats->rx_packets++;
return NETDEV_TX_OK;
tx_drop:
kfree_skb(skb);
stats->tx_dropped++;
return NETDEV_TX_OK;
rx_drop:
kfree_skb(skb);
rcv_stats->rx_dropped++;
return NETDEV_TX_OK;
}
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 | static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device *rcv = NULL;
struct veth_priv *priv, *rcv_priv;
struct veth_net_stats *stats, *rcv_stats;
int length;
priv = netdev_priv(dev);
rcv = priv->peer;
rcv_priv = netdev_priv(rcv);
stats = this_cpu_ptr(priv->stats);
rcv_stats = this_cpu_ptr(rcv_priv->stats);
if (!(rcv->flags & IFF_UP))
goto tx_drop;
if (dev->features & NETIF_F_NO_CSUM)
skb->ip_summed = rcv_priv->ip_summed;
length = skb->len + ETH_HLEN;
if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS)
goto rx_drop;
stats->tx_bytes += length;
stats->tx_packets++;
rcv_stats->rx_bytes += length;
rcv_stats->rx_packets++;
return NETDEV_TX_OK;
tx_drop:
kfree_skb(skb);
stats->tx_dropped++;
return NETDEV_TX_OK;
rx_drop:
rcv_stats->rx_dropped++;
return NETDEV_TX_OK;
}
| 166,088 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,214 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (*p) + datalen >= max) {
zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ce->name);
object_init_ex(*rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
Commit Message:
CWE ID: CWE-189 | static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (max - (*p)) <= datalen) {
zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ce->name);
object_init_ex(*rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
| 165,149 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AppCacheDatabase::FindEntriesForCache(int64_t cache_id,
std::vector<EntryRecord>* records) {
DCHECK(records && records->empty());
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, url, flags, response_id, response_size FROM Entries"
" WHERE cache_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, cache_id);
while (statement.Step()) {
records->push_back(EntryRecord());
ReadEntryRecord(statement, &records->back());
DCHECK(records->back().cache_id == cache_id);
}
return statement.Succeeded();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | bool AppCacheDatabase::FindEntriesForCache(int64_t cache_id,
std::vector<EntryRecord>* records) {
DCHECK(records && records->empty());
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, url, flags, response_id, response_size, padding_size "
"FROM Entries"
" WHERE cache_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, cache_id);
while (statement.Step()) {
records->push_back(EntryRecord());
ReadEntryRecord(statement, &records->back());
DCHECK(records->back().cache_id == cache_id);
}
return statement.Succeeded();
}
| 172,975 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_krb5int_export_lucid_sec_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_error_code kret = 0;
OM_uint32 retval;
krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle;
void *lctx = NULL;
int version = 0;
gss_buffer_desc rep;
/* Assume failure */
retval = GSS_S_FAILURE;
*minor_status = 0;
*data_set = GSS_C_NO_BUFFER_SET;
retval = generic_gss_oid_decompose(minor_status,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH,
desired_object,
&version);
if (GSS_ERROR(retval))
return retval;
/* Externalize a structure of the right version */
switch (version) {
case 1:
kret = make_external_lucid_ctx_v1((krb5_pointer)ctx,
version, &lctx);
break;
default:
kret = (OM_uint32) KG_LUCID_VERSION;
break;
}
if (kret)
goto error_out;
rep.value = &lctx;
rep.length = sizeof(lctx);
retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set);
if (GSS_ERROR(retval))
goto error_out;
error_out:
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
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: | gss_krb5int_export_lucid_sec_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_error_code kret = 0;
OM_uint32 retval;
krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle;
void *lctx = NULL;
int version = 0;
gss_buffer_desc rep;
/* Assume failure */
retval = GSS_S_FAILURE;
*minor_status = 0;
*data_set = GSS_C_NO_BUFFER_SET;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
retval = generic_gss_oid_decompose(minor_status,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH,
desired_object,
&version);
if (GSS_ERROR(retval))
return retval;
/* Externalize a structure of the right version */
switch (version) {
case 1:
kret = make_external_lucid_ctx_v1((krb5_pointer)ctx,
version, &lctx);
break;
default:
kret = (OM_uint32) KG_LUCID_VERSION;
break;
}
if (kret)
goto error_out;
rep.value = &lctx;
rep.length = sizeof(lctx);
retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set);
if (GSS_ERROR(retval))
goto error_out;
error_out:
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
| 166,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size,
long long element_start, long long element_size)
: m_pSegment(pSegment),
m_start(payload_start),
m_size(payload_size),
m_element_start(element_start),
m_element_size(element_size),
m_tags(NULL),
m_tags_size(0),
m_tags_count(0) {}
Tags::~Tags() {
while (m_tags_count > 0) {
Tag& t = m_tags[--m_tags_count];
t.Clear();
}
delete[] m_tags;
}
long Tags::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x3373) { // Tag ID
status = ParseTag(pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
int Tags::GetTagCount() const { return m_tags_count; }
const Tags::Tag* Tags::GetTag(int idx) const {
if (idx < 0)
return NULL;
if (idx >= m_tags_count)
return NULL;
return m_tags + idx;
}
bool Tags::ExpandTagsArray() {
if (m_tags_size > m_tags_count)
return true; // nothing else to do
const int size = (m_tags_size == 0) ? 1 : 2 * m_tags_size;
Tag* const tags = new (std::nothrow) Tag[size];
if (tags == NULL)
return false;
for (int idx = 0; idx < m_tags_count; ++idx) {
m_tags[idx].ShallowCopy(tags[idx]);
}
delete[] m_tags;
m_tags = tags;
m_tags_size = size;
return true;
}
long Tags::ParseTag(long long pos, long long size) {
if (!ExpandTagsArray())
return -1;
Tag& t = m_tags[m_tags_count++];
t.Init();
return t.Parse(m_pSegment->m_pReader, pos, size);
}
Tags::Tag::Tag() {}
Tags::Tag::~Tag() {}
int Tags::Tag::GetSimpleTagCount() const { return m_simple_tags_count; }
const Tags::SimpleTag* Tags::Tag::GetSimpleTag(int index) const {
if (index < 0)
return NULL;
if (index >= m_simple_tags_count)
return NULL;
return m_simple_tags + index;
}
void Tags::Tag::Init() {
m_simple_tags = NULL;
m_simple_tags_size = 0;
m_simple_tags_count = 0;
}
void Tags::Tag::ShallowCopy(Tag& rhs) const {
rhs.m_simple_tags = m_simple_tags;
rhs.m_simple_tags_size = m_simple_tags_size;
rhs.m_simple_tags_count = m_simple_tags_count;
}
void Tags::Tag::Clear() {
while (m_simple_tags_count > 0) {
SimpleTag& d = m_simple_tags[--m_simple_tags_count];
d.Clear();
}
delete[] m_simple_tags;
m_simple_tags = NULL;
m_simple_tags_size = 0;
}
long Tags::Tag::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x27C8) { // SimpleTag ID
status = ParseSimpleTag(pReader, pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
long Tags::Tag::ParseSimpleTag(IMkvReader* pReader, long long pos,
long long size) {
if (!ExpandSimpleTagsArray())
return -1;
SimpleTag& st = m_simple_tags[m_simple_tags_count++];
st.Init();
return st.Parse(pReader, pos, size);
}
bool Tags::Tag::ExpandSimpleTagsArray() {
if (m_simple_tags_size > m_simple_tags_count)
return true; // nothing else to do
const int size = (m_simple_tags_size == 0) ? 1 : 2 * m_simple_tags_size;
SimpleTag* const displays = new (std::nothrow) SimpleTag[size];
if (displays == NULL)
return false;
for (int idx = 0; idx < m_simple_tags_count; ++idx) {
m_simple_tags[idx].ShallowCopy(displays[idx]);
}
delete[] m_simple_tags;
m_simple_tags = displays;
m_simple_tags_size = size;
return true;
}
Tags::SimpleTag::SimpleTag() {}
Tags::SimpleTag::~SimpleTag() {}
const char* Tags::SimpleTag::GetTagName() const { return m_tag_name; }
const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; }
void Tags::SimpleTag::Init() {
m_tag_name = NULL;
m_tag_string = NULL;
}
void Tags::SimpleTag::ShallowCopy(SimpleTag& rhs) const {
rhs.m_tag_name = m_tag_name;
rhs.m_tag_string = m_tag_string;
}
void Tags::SimpleTag::Clear() {
delete[] m_tag_name;
m_tag_name = NULL;
delete[] m_tag_string;
m_tag_string = NULL;
}
long Tags::SimpleTag::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x5A3) { // TagName ID
status = UnserializeString(pReader, pos, size, m_tag_name);
if (status)
return status;
} else if (id == 0x487) { // TagString ID
status = UnserializeString(pReader, pos, size, m_tag_string);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,841 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::UnserializeString(
IMkvReader* pReader,
long long pos,
long long size_,
char*& str)
{
delete[] str;
str = NULL;
if (size_ >= LONG_MAX) //we need (size+1) chars
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
str = new (std::nothrow) char[size+1];
if (str == NULL)
return -1;
unsigned char* const buf = reinterpret_cast<unsigned char*>(str);
const long status = pReader->Read(pos, size, buf);
if (status)
{
delete[] str;
str = NULL;
return status;
}
str[size] = '\0';
return 0; //success
}
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 mkvparser::UnserializeString(
if (status) {
delete[] str;
str = NULL;
return status;
}
str[size] = '\0';
return 0; // success
}
| 174,449 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CheckFakeData(uint8* audio_data, int frames_written,
double playback_rate) {
size_t length =
(frames_written * algorithm_.bytes_per_frame())
/ algorithm_.bytes_per_channel();
switch (algorithm_.bytes_per_channel()) {
case 4:
DoCheckFakeData<int32>(audio_data, length);
break;
case 2:
DoCheckFakeData<int16>(audio_data, length);
break;
case 1:
DoCheckFakeData<uint8>(audio_data, length);
break;
default:
NOTREACHED() << "Unsupported audio bit depth in crossfade.";
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void CheckFakeData(uint8* audio_data, int frames_written,
| 171,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint();
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254 | void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsingState(InDOMContentLoaded);
if (!m_documentTiming.domContentLoadedEventStart())
m_documentTiming.setDomContentLoadedEventStart(monotonicallyIncreasingTime());
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd())
m_documentTiming.setDomContentLoadedEventEnd(monotonicallyIncreasingTime());
setParsingState(FinishedParsing);
RefPtrWillBeRawPtr<Document> protect(this);
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
if (mainResourceWasAlreadyRequested)
updateLayoutTreeIfNeeded();
frame->loader().finishedParsing();
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame.get()));
InspectorInstrumentation::domContentLoadedEventFired(frame.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
}
| 171,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SandboxIPCHandler::HandleLocaltime(
int fd,
base::PickleIterator iter,
const std::vector<base::ScopedFD>& fds) {
std::string time_string;
if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t))
return;
time_t time;
memcpy(&time, time_string.data(), sizeof(time));
const struct tm* expanded_time = localtime(&time);
std::string result_string;
const char* time_zone_string = "";
if (expanded_time) {
result_string = std::string(reinterpret_cast<const char*>(expanded_time),
sizeof(struct tm));
time_zone_string = expanded_time->tm_zone;
}
base::Pickle reply;
reply.WriteString(result_string);
reply.WriteString(time_zone_string);
SendRendererReply(fds, reply, -1);
}
Commit Message: Serialize struct tm in a safe way.
BUG=765512
Change-Id: If235b8677eb527be2ac0fe621fc210e4116a7566
Reviewed-on: https://chromium-review.googlesource.com/679441
Commit-Queue: Chris Palmer <[email protected]>
Reviewed-by: Julien Tinnes <[email protected]>
Cr-Commit-Position: refs/heads/master@{#503948}
CWE ID: CWE-119 | void SandboxIPCHandler::HandleLocaltime(
int fd,
base::PickleIterator iter,
const std::vector<base::ScopedFD>& fds) {
// The other side of this call is in |ProxyLocaltimeCallToBrowser|, in
// zygote_main_linux.cc.
std::string time_string;
if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t))
return;
time_t time;
memcpy(&time, time_string.data(), sizeof(time));
// We use |localtime| here because we need the |tm_zone| field to be filled
const struct tm* expanded_time = localtime(&time);
base::Pickle reply;
if (expanded_time) {
WriteTimeStruct(&reply, expanded_time);
} else {
// The {} constructor ensures the struct is 0-initialized.
struct tm zeroed_time = {};
WriteTimeStruct(&reply, &zeroed_time);
}
SendRendererReply(fds, reply, -1);
}
| 172,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | CreateFileHelper(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
CreateFileHelper(CreateFileResult* result, const String& name, const KURL& url, FileSystemType type)
: m_result(result)
, m_name(name)
, m_url(url)
, m_type(type)
{
}
| 171,412 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void wifi_cleanup(wifi_handle handle, wifi_cleaned_up_handler handler)
{
hal_info *info = getHalInfo(handle);
char buf[64];
info->cleaned_up_handler = handler;
if (write(info->cleanup_socks[0], "Exit", 4) < 1) {
ALOGE("could not write to the cleanup socket");
} else {
memset(buf, 0, sizeof(buf));
int result = read(info->cleanup_socks[0], buf, sizeof(buf));
ALOGE("%s: Read after POLL returned %d, error no = %d", __FUNCTION__, result, errno);
if (strncmp(buf, "Done", 4) == 0) {
ALOGE("Event processing terminated");
} else {
ALOGD("Rx'ed %s", buf);
}
}
info->clean_up = true;
pthread_mutex_lock(&info->cb_lock);
int bad_commands = 0;
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGI("Command left in event_cb %p:%s", cmd, (cmd ? cmd->getType(): ""));
}
while (info->num_cmd > bad_commands) {
int num_cmd = info->num_cmd;
cmd_info *cmdi = &(info->cmd[bad_commands]);
WifiCommand *cmd = cmdi->cmd;
if (cmd != NULL) {
ALOGI("Cancelling command %p:%s", cmd, cmd->getType());
pthread_mutex_unlock(&info->cb_lock);
cmd->cancel();
pthread_mutex_lock(&info->cb_lock);
/* release reference added when command is saved */
cmd->releaseRef();
if (num_cmd == info->num_cmd) {
ALOGI("Cancelling command %p:%s did not work", cmd, (cmd ? cmd->getType(): ""));
bad_commands++;
}
}
}
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGE("Leaked command %p", cmd);
}
pthread_mutex_unlock(&info->cb_lock);
internal_cleaned_up_handler(handle);
}
Commit Message: Fix use-after-free in wifi_cleanup()
Release reference to cmd only after possibly calling getType().
BUG: 25753768
Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb
(cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223)
CWE ID: CWE-264 | void wifi_cleanup(wifi_handle handle, wifi_cleaned_up_handler handler)
{
hal_info *info = getHalInfo(handle);
char buf[64];
info->cleaned_up_handler = handler;
if (write(info->cleanup_socks[0], "Exit", 4) < 1) {
ALOGE("could not write to the cleanup socket");
} else {
memset(buf, 0, sizeof(buf));
int result = read(info->cleanup_socks[0], buf, sizeof(buf));
ALOGE("%s: Read after POLL returned %d, error no = %d", __FUNCTION__, result, errno);
if (strncmp(buf, "Done", 4) == 0) {
ALOGE("Event processing terminated");
} else {
ALOGD("Rx'ed %s", buf);
}
}
info->clean_up = true;
pthread_mutex_lock(&info->cb_lock);
int bad_commands = 0;
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGI("Command left in event_cb %p:%s", cmd, (cmd ? cmd->getType(): ""));
}
while (info->num_cmd > bad_commands) {
int num_cmd = info->num_cmd;
cmd_info *cmdi = &(info->cmd[bad_commands]);
WifiCommand *cmd = cmdi->cmd;
if (cmd != NULL) {
ALOGI("Cancelling command %p:%s", cmd, cmd->getType());
pthread_mutex_unlock(&info->cb_lock);
cmd->cancel();
pthread_mutex_lock(&info->cb_lock);
if (num_cmd == info->num_cmd) {
ALOGI("Cancelling command %p:%s did not work", cmd, (cmd ? cmd->getType(): ""));
bad_commands++;
}
/* release reference added when command is saved */
cmd->releaseRef();
}
}
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGE("Leaked command %p", cmd);
}
pthread_mutex_unlock(&info->cb_lock);
internal_cleaned_up_handler(handle);
}
| 173,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView)
{
Settings* settings = core(webView)->settings();
const gchar* name = g_intern_string(pspec->name);
GValue value = { 0, { { 0 } } };
g_value_init(&value, pspec->value_type);
g_object_get_property(G_OBJECT(webSettings), name, &value);
if (name == g_intern_string("default-encoding"))
settings->setDefaultTextEncodingName(g_value_get_string(&value));
else if (name == g_intern_string("cursive-font-family"))
settings->setCursiveFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-family"))
settings->setStandardFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("fantasy-font-family"))
settings->setFantasyFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("monospace-font-family"))
settings->setFixedFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("sans-serif-font-family"))
settings->setSansSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("serif-font-family"))
settings->setSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-size"))
settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("default-monospace-font-size"))
settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-font-size"))
settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-logical-font-size"))
settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("enforce-96-dpi"))
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
else if (name == g_intern_string("auto-load-images"))
settings->setLoadsImagesAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("auto-shrink-images"))
settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value));
else if (name == g_intern_string("print-backgrounds"))
settings->setShouldPrintBackgrounds(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-scripts"))
settings->setJavaScriptEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-plugins"))
settings->setPluginsEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dns-prefetching"))
settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("resizable-text-areas"))
settings->setTextAreasAreResizable(g_value_get_boolean(&value));
else if (name == g_intern_string("user-stylesheet-uri"))
settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value)));
else if (name == g_intern_string("enable-developer-extras"))
settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-private-browsing"))
settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-caret-browsing"))
settings->setCaretBrowsingEnabled(g_value_get_boolean(&value));
#if ENABLE(DATABASE)
else if (name == g_intern_string("enable-html5-database")) {
AbstractDatabase::setIsAvailable(g_value_get_boolean(&value));
}
#endif
else if (name == g_intern_string("enable-html5-local-storage"))
settings->setLocalStorageEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-xss-auditor"))
settings->setXSSAuditorEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-spatial-navigation"))
settings->setSpatialNavigationEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-frame-flattening"))
settings->setFrameFlatteningEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-open-windows-automatically"))
settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-access-clipboard"))
settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-offline-web-application-cache"))
settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("editing-behavior"))
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(g_value_get_enum(&value)));
else if (name == g_intern_string("enable-universal-access-from-file-uris"))
settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-file-access-from-file-uris"))
settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dom-paste"))
settings->setDOMPasteAllowed(g_value_get_boolean(&value));
else if (name == g_intern_string("tab-key-cycles-through-elements")) {
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value));
} else if (name == g_intern_string("enable-site-specific-quirks"))
settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-page-cache"))
settings->setUsesPageCache(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-java-applet"))
settings->setJavaEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-hyperlink-auditing"))
settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value));
#if ENABLE(SPELLCHECK)
else if (name == g_intern_string("spell-checking-languages")) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value));
}
#endif
#if ENABLE(WEBGL)
else if (name == g_intern_string("enable-webgl"))
settings->setWebGLEnabled(g_value_get_boolean(&value));
#endif
else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name))
g_warning("Unexpected setting '%s'", name);
g_value_unset(&value);
}
Commit Message: 2011-06-02 Joone Hur <[email protected]>
Reviewed by Martin Robinson.
[GTK] Only load dictionaries if spell check is enabled
https://bugs.webkit.org/show_bug.cgi?id=32879
We don't need to call enchant if enable-spell-checking is false.
* webkit/webkitwebview.cpp:
(webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false.
(webkit_web_view_settings_notify): Ditto.
git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView)
{
Settings* settings = core(webView)->settings();
const gchar* name = g_intern_string(pspec->name);
GValue value = { 0, { { 0 } } };
g_value_init(&value, pspec->value_type);
g_object_get_property(G_OBJECT(webSettings), name, &value);
if (name == g_intern_string("default-encoding"))
settings->setDefaultTextEncodingName(g_value_get_string(&value));
else if (name == g_intern_string("cursive-font-family"))
settings->setCursiveFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-family"))
settings->setStandardFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("fantasy-font-family"))
settings->setFantasyFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("monospace-font-family"))
settings->setFixedFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("sans-serif-font-family"))
settings->setSansSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("serif-font-family"))
settings->setSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-size"))
settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("default-monospace-font-size"))
settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-font-size"))
settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-logical-font-size"))
settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("enforce-96-dpi"))
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
else if (name == g_intern_string("auto-load-images"))
settings->setLoadsImagesAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("auto-shrink-images"))
settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value));
else if (name == g_intern_string("print-backgrounds"))
settings->setShouldPrintBackgrounds(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-scripts"))
settings->setJavaScriptEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-plugins"))
settings->setPluginsEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dns-prefetching"))
settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("resizable-text-areas"))
settings->setTextAreasAreResizable(g_value_get_boolean(&value));
else if (name == g_intern_string("user-stylesheet-uri"))
settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value)));
else if (name == g_intern_string("enable-developer-extras"))
settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-private-browsing"))
settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-caret-browsing"))
settings->setCaretBrowsingEnabled(g_value_get_boolean(&value));
#if ENABLE(DATABASE)
else if (name == g_intern_string("enable-html5-database")) {
AbstractDatabase::setIsAvailable(g_value_get_boolean(&value));
}
#endif
else if (name == g_intern_string("enable-html5-local-storage"))
settings->setLocalStorageEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-xss-auditor"))
settings->setXSSAuditorEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-spatial-navigation"))
settings->setSpatialNavigationEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-frame-flattening"))
settings->setFrameFlatteningEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-open-windows-automatically"))
settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-access-clipboard"))
settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-offline-web-application-cache"))
settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("editing-behavior"))
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(g_value_get_enum(&value)));
else if (name == g_intern_string("enable-universal-access-from-file-uris"))
settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-file-access-from-file-uris"))
settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dom-paste"))
settings->setDOMPasteAllowed(g_value_get_boolean(&value));
else if (name == g_intern_string("tab-key-cycles-through-elements")) {
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value));
} else if (name == g_intern_string("enable-site-specific-quirks"))
settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-page-cache"))
settings->setUsesPageCache(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-java-applet"))
settings->setJavaEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-hyperlink-auditing"))
settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value));
#if ENABLE(SPELLCHECK)
else if (name == g_intern_string("spell-checking-languages")) {
gboolean enableSpellChecking;
g_object_get(G_OBJECT(webSettings), "enable-spell-checking", &enableSpellChecking, NULL);
if (enableSpellChecking) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value));
}
}
#endif
#if ENABLE(WEBGL)
else if (name == g_intern_string("enable-webgl"))
settings->setWebGLEnabled(g_value_get_boolean(&value));
#endif
else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name))
g_warning("Unexpected setting '%s'", name);
g_value_unset(&value);
}
| 170,449 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
{
/* unprotected vars, we dont care of overwrites */
static u32 challenge_timestamp;
static unsigned int challenge_count;
struct tcp_sock *tp = tcp_sk(sk);
u32 now;
/* First check our per-socket dupack rate limit. */
if (tcp_oow_rate_limited(sock_net(sk), skb,
LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
&tp->last_oow_ack_time))
return;
/* Then check the check host-wide RFC 5961 rate limit. */
now = jiffies / HZ;
if (now != challenge_timestamp) {
challenge_timestamp = now;
challenge_count = 0;
}
if (++challenge_count <= sysctl_tcp_challenge_ack_limit) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
tcp_send_ack(sk);
}
}
Commit Message: tcp: make challenge acks less predictable
Yue Cao claims that current host rate limiting of challenge ACKS
(RFC 5961) could leak enough information to allow a patient attacker
to hijack TCP sessions. He will soon provide details in an academic
paper.
This patch increases the default limit from 100 to 1000, and adds
some randomization so that the attacker can no longer hijack
sessions without spending a considerable amount of probes.
Based on initial analysis and patch from Linus.
Note that we also have per socket rate limiting, so it is tempting
to remove the host limit in the future.
v2: randomize the count of challenge acks per second, not the period.
Fixes: 282f23c6ee34 ("tcp: implement RFC 5961 3.2")
Reported-by: Yue Cao <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Yuchung Cheng <[email protected]>
Cc: Neal Cardwell <[email protected]>
Acked-by: Neal Cardwell <[email protected]>
Acked-by: Yuchung Cheng <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
{
/* unprotected vars, we dont care of overwrites */
static u32 challenge_timestamp;
static unsigned int challenge_count;
struct tcp_sock *tp = tcp_sk(sk);
u32 count, now;
/* First check our per-socket dupack rate limit. */
if (tcp_oow_rate_limited(sock_net(sk), skb,
LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
&tp->last_oow_ack_time))
return;
/* Then check host-wide RFC 5961 rate limit. */
now = jiffies / HZ;
if (now != challenge_timestamp) {
u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1;
challenge_timestamp = now;
WRITE_ONCE(challenge_count, half +
prandom_u32_max(sysctl_tcp_challenge_ack_limit));
}
count = READ_ONCE(challenge_count);
if (count > 0) {
WRITE_ONCE(challenge_count, count - 1);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
tcp_send_ack(sk);
}
}
| 167,133 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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,
ext4_lblk_t iblock, unsigned int max_blocks,
struct ext4_ext_path *path, int flags,
unsigned int allocated, struct buffer_head *bh_result,
ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
"block %llu, max_blocks %u, flags %d, allocated %u",
inode->i_ino, (unsigned long long)iblock, max_blocks,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/* get_block() before submit the IO, split the extent */
if (flags == EXT4_GET_BLOCKS_PRE_IO) {
ret = ext4_split_unwritten_extents(handle,
inode, path, iblock,
max_blocks, flags);
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to convertion to written when IO is
* completed
*/
if (io)
io->flag = EXT4_IO_UNWRITTEN;
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
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);
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.
*/
set_buffer_unwritten(bh_result);
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode,
path, iblock,
max_blocks);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
set_buffer_new(bh_result);
/*
* 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 > max_blocks) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + max_blocks,
allocated - max_blocks);
allocated = max_blocks;
}
/*
* 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)
ext4_da_update_reserve_space(inode, allocated, 0);
map_out:
set_buffer_mapped(bh_result);
out1:
if (allocated > max_blocks)
allocated = max_blocks;
ext4_ext_show_leaf(inode, path);
bh_result->b_bdev = inode->i_sb->s_bdev;
bh_result->b_blocknr = newblock;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
ext4_lblk_t iblock, unsigned int max_blocks,
struct ext4_ext_path *path, int flags,
unsigned int allocated, struct buffer_head *bh_result,
ext4_fsblk_t newblock)
{
int ret = 0;
int err = 0;
ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
"block %llu, max_blocks %u, flags %d, allocated %u",
inode->i_ino, (unsigned long long)iblock, max_blocks,
flags, allocated);
ext4_ext_show_leaf(inode, path);
/* get_block() before submit the IO, split the extent */
if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
ret = ext4_split_unwritten_extents(handle,
inode, path, iblock,
max_blocks, flags);
/*
* Flag the inode(non aio case) or end_io struct (aio case)
* that this IO needs to convertion to written when IO is
* completed
*/
if (io)
io->flag = EXT4_IO_UNWRITTEN;
else
ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
if (ext4_should_dioread_nolock(inode))
set_buffer_uninit(bh_result);
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);
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.
*/
set_buffer_unwritten(bh_result);
goto out1;
}
/* buffered write, writepage time, convert*/
ret = ext4_ext_convert_to_initialized(handle, inode,
path, iblock,
max_blocks);
if (ret >= 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
out:
if (ret <= 0) {
err = ret;
goto out2;
} else
allocated = ret;
set_buffer_new(bh_result);
/*
* 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 > max_blocks) {
unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
newblock + max_blocks,
allocated - max_blocks);
allocated = max_blocks;
}
/*
* 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)
ext4_da_update_reserve_space(inode, allocated, 0);
map_out:
set_buffer_mapped(bh_result);
out1:
if (allocated > max_blocks)
allocated = max_blocks;
ext4_ext_show_leaf(inode, path);
bh_result->b_bdev = inode->i_sb->s_bdev;
bh_result->b_blocknr = newblock;
out2:
if (path) {
ext4_ext_drop_refs(path);
kfree(path);
}
return err ? err : allocated;
}
| 167,537 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void * calloc(size_t n, size_t lb)
{
if (lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Commit Message: Speedup calloc size overflow check by preventing division if small values
* malloc.c (GC_SQRT_SIZE_MAX): New macro.
* malloc.c (calloc): Add fast initial size overflow check to avoid
integer division for reasonably small values passed.
CWE ID: CWE-189 | void * calloc(size_t n, size_t lb)
{
if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial test */
&& lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
| 169,881 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
vstart += entry->vn_aux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8731 - Crash in ELF parser with negative 32bit number
CWE ID: CWE-125 | static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
st32 vnaux = entry->vn_aux;
if (vnaux < 1) {
goto beach;
}
vstart += vnaux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
}
| 167,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int HttpProxyClientSocket::DoReadHeadersComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
if (proxy_delegate_) {
proxy_delegate_->OnTunnelHeadersReceived(
HostPortPair::FromURL(request_.url),
proxy_server_,
*response_.headers);
}
switch (response_.headers->response_code()) {
case 200: // OK
if (http_stream_parser_->IsMoreDataBuffered())
return ERR_TUNNEL_CONNECTION_FAILED;
next_state_ = STATE_DONE;
return OK;
case 302: // Found / Moved Temporarily
if (is_https_proxy_ && SanitizeProxyRedirect(&response_, request_.url)) {
bool is_connection_reused = http_stream_parser_->IsConnectionReused();
redirect_has_load_timing_info_ =
transport_->GetLoadTimingInfo(
is_connection_reused, &redirect_load_timing_info_);
transport_.reset();
http_stream_parser_.reset();
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
}
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
case 407: // Proxy Authentication Required
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19 | int HttpProxyClientSocket::DoReadHeadersComplete(int result) {
if (result < 0)
return result;
if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0))
return ERR_TUNNEL_CONNECTION_FAILED;
net_log_.AddEvent(
NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
if (proxy_delegate_) {
proxy_delegate_->OnTunnelHeadersReceived(
HostPortPair::FromURL(request_.url),
proxy_server_,
*response_.headers);
}
switch (response_.headers->response_code()) {
case 200: // OK
if (http_stream_parser_->IsMoreDataBuffered())
return ERR_TUNNEL_CONNECTION_FAILED;
next_state_ = STATE_DONE;
return OK;
case 302: // Found / Moved Temporarily
if (!is_https_proxy_ || !SanitizeProxyRedirect(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
redirect_has_load_timing_info_ = transport_->GetLoadTimingInfo(
http_stream_parser_->IsConnectionReused(),
&redirect_load_timing_info_);
transport_.reset();
http_stream_parser_.reset();
return ERR_HTTPS_PROXY_TUNNEL_RESPONSE;
case 407: // Proxy Authentication Required
if (!SanitizeProxyAuth(&response_)) {
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_);
default:
LogBlockedTunnelResponse();
return ERR_TUNNEL_CONNECTION_FAILED;
}
}
| 172,039 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res)
{
unsigned char found;
const uni_to_enc *table;
size_t table_size;
switch (charset) {
case cs_8859_1:
/* identity mapping of code points to unicode */
if (code > 0xFF) {
return FAILURE;
}
*res = code;
break;
case cs_8859_5:
if (code <= 0xA0 || code == 0xAD /* soft hyphen */) {
*res = code;
} else if (code == 0x2116) {
*res = 0xF0; /* numero sign */
} else if (code == 0xA7) {
*res = 0xFD; /* section sign */
} else if (code >= 0x0401 && code <= 0x044F) {
if (code == 0x040D || code == 0x0450 || code == 0x045D)
return FAILURE;
*res = code - 0x360;
} else {
return FAILURE;
}
break;
case cs_8859_15:
if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) {
*res = code;
} else { /* between A4 and 0xBE */
found = unimap_bsearch(unimap_iso885915,
code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915));
if (found)
*res = found;
else
return FAILURE;
}
break;
case cs_cp1252:
if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) {
*res = code;
} else {
found = unimap_bsearch(unimap_win1252,
code, sizeof(unimap_win1252) / sizeof(*unimap_win1252));
if (found)
*res = found;
else
return FAILURE;
}
break;
case cs_macroman:
if (code == 0x7F)
return FAILURE;
table = unimap_macroman;
table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman);
goto table_over_7F;
case cs_cp1251:
table = unimap_win1251;
table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251);
goto table_over_7F;
case cs_koi8r:
table = unimap_koi8r;
table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r);
goto table_over_7F;
case cs_cp866:
table = unimap_cp866;
table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866);
table_over_7F:
if (code <= 0x7F) {
*res = code;
} else {
found = unimap_bsearch(table, code, table_size);
if (found)
*res = found;
else
return FAILURE;
}
break;
/* from here on, only map the possible characters in the ASCII range.
* to improve support here, it's a matter of building the unicode mappings.
* See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */
case cs_sjis:
case cs_eucjp:
/* we interpret 0x5C as the Yen symbol. This is not universal.
* See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */
if (code >= 0x20 && code <= 0x7D) {
if (code == 0x5C)
return FAILURE;
*res = code;
} else {
return FAILURE;
}
break;
case cs_big5:
case cs_big5hkscs:
case cs_gb2312:
if (code >= 0x20 && code <= 0x7D) {
*res = code;
} else {
return FAILURE;
}
break;
default:
return FAILURE;
}
return SUCCESS;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res)
{
unsigned char found;
const uni_to_enc *table;
size_t table_size;
switch (charset) {
case cs_8859_1:
/* identity mapping of code points to unicode */
if (code > 0xFF) {
return FAILURE;
}
*res = code;
break;
case cs_8859_5:
if (code <= 0xA0 || code == 0xAD /* soft hyphen */) {
*res = code;
} else if (code == 0x2116) {
*res = 0xF0; /* numero sign */
} else if (code == 0xA7) {
*res = 0xFD; /* section sign */
} else if (code >= 0x0401 && code <= 0x044F) {
if (code == 0x040D || code == 0x0450 || code == 0x045D)
return FAILURE;
*res = code - 0x360;
} else {
return FAILURE;
}
break;
case cs_8859_15:
if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) {
*res = code;
} else { /* between A4 and 0xBE */
found = unimap_bsearch(unimap_iso885915,
code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915));
if (found)
*res = found;
else
return FAILURE;
}
break;
case cs_cp1252:
if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) {
*res = code;
} else {
found = unimap_bsearch(unimap_win1252,
code, sizeof(unimap_win1252) / sizeof(*unimap_win1252));
if (found)
*res = found;
else
return FAILURE;
}
break;
case cs_macroman:
if (code == 0x7F)
return FAILURE;
table = unimap_macroman;
table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman);
goto table_over_7F;
case cs_cp1251:
table = unimap_win1251;
table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251);
goto table_over_7F;
case cs_koi8r:
table = unimap_koi8r;
table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r);
goto table_over_7F;
case cs_cp866:
table = unimap_cp866;
table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866);
table_over_7F:
if (code <= 0x7F) {
*res = code;
} else {
found = unimap_bsearch(table, code, table_size);
if (found)
*res = found;
else
return FAILURE;
}
break;
/* from here on, only map the possible characters in the ASCII range.
* to improve support here, it's a matter of building the unicode mappings.
* See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */
case cs_sjis:
case cs_eucjp:
/* we interpret 0x5C as the Yen symbol. This is not universal.
* See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */
if (code >= 0x20 && code <= 0x7D) {
if (code == 0x5C)
return FAILURE;
*res = code;
} else {
return FAILURE;
}
break;
case cs_big5:
case cs_big5hkscs:
case cs_gb2312:
if (code >= 0x20 && code <= 0x7D) {
*res = code;
} else {
return FAILURE;
}
break;
default:
return FAILURE;
}
return SUCCESS;
}
| 167,173 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119 | EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
if (pWTIntFrame->numSamples < 0) {
ALOGE("b/26366256");
pWTIntFrame->numSamples = 0;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
| 173,923 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec)
{
char *cp;
*tmask = DTK_TIME_M;
tm->tm_hour = strtol(str, &cp, 10);
if (*cp != ':')
return -1;
str = cp + 1;
tm->tm_min = strtol(str, &cp, 10);
if (*cp == '\0')
{
tm->tm_sec = 0;
*fsec = 0;
}
else if (*cp != ':')
return -1;
else
{
str = cp + 1;
tm->tm_sec = strtol(str, &cp, 10);
if (*cp == '\0')
*fsec = 0;
else if (*cp == '.')
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[MAXDATELEN + 1];
/*
* OK, we have at most six digits to work with. Let's construct a
* string and then do the conversion to an integer.
*/
strncpy(fstr, (cp + 1), 7);
strcpy(fstr + strlen(fstr), "000000");
*(fstr + 6) = '\0';
*fsec = strtol(fstr, &cp, 10);
#else
str = cp;
*fsec = strtod(str, &cp);
#endif
if (*cp != '\0')
return -1;
}
else
return -1;
}
/* do a sanity check */
#ifdef HAVE_INT64_TIMESTAMP
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC)
return -1;
#else
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1)
return -1;
#endif
return 0;
} /* DecodeTime() */
Commit Message: Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value. It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer. ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own. In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly. Back-patch to 8.4
(all supported versions).
Reported by Daniel Schüssler, reviewed by Tom Lane.
Security: CVE-2014-0063
CWE ID: CWE-119 | DecodeTime(char *str, int *tmask, struct tm * tm, fsec_t *fsec)
{
char *cp;
*tmask = DTK_TIME_M;
tm->tm_hour = strtol(str, &cp, 10);
if (*cp != ':')
return -1;
str = cp + 1;
tm->tm_min = strtol(str, &cp, 10);
if (*cp == '\0')
{
tm->tm_sec = 0;
*fsec = 0;
}
else if (*cp != ':')
return -1;
else
{
str = cp + 1;
tm->tm_sec = strtol(str, &cp, 10);
if (*cp == '\0')
*fsec = 0;
else if (*cp == '.')
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[7];
int i;
cp++;
/*
* OK, we have at most six digits to care about. Let's construct a
* string with those digits, zero-padded on the right, and then do
* the conversion to an integer.
*
* XXX This truncates the seventh digit, unlike rounding it as do
* the backend and the !HAVE_INT64_TIMESTAMP case.
*/
for (i = 0; i < 6; i++)
fstr[i] = *cp != '\0' ? *cp++ : '0';
fstr[i] = '\0';
*fsec = strtol(fstr, &cp, 10);
#else
str = cp;
*fsec = strtod(str, &cp);
#endif
if (*cp != '\0')
return -1;
}
else
return -1;
}
/* do a sanity check */
#ifdef HAVE_INT64_TIMESTAMP
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC)
return -1;
#else
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= 1)
return -1;
#endif
return 0;
} /* DecodeTime() */
| 166,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hns_xgmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_xgmac_stats_string);
return 0;
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int hns_xgmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS)
return ARRAY_SIZE(g_xgmac_stats_string);
return 0;
}
| 169,401 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t ucma_process_join(struct ucma_file *file,
struct rdma_ucm_join_mcast *cmd, int out_len)
{
struct rdma_ucm_create_id_resp resp;
struct ucma_context *ctx;
struct ucma_multicast *mc;
struct sockaddr *addr;
int ret;
u8 join_state;
if (out_len < sizeof(resp))
return -ENOSPC;
addr = (struct sockaddr *) &cmd->addr;
if (cmd->addr_size != rdma_addr_size(addr))
return -EINVAL;
if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER)
join_state = BIT(FULLMEMBER_JOIN);
else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER)
join_state = BIT(SENDONLY_FULLMEMBER_JOIN);
else
return -EINVAL;
ctx = ucma_get_ctx_dev(file, cmd->id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
mutex_lock(&file->mut);
mc = ucma_alloc_multicast(ctx);
if (!mc) {
ret = -ENOMEM;
goto err1;
}
mc->join_state = join_state;
mc->uid = cmd->uid;
memcpy(&mc->addr, addr, cmd->addr_size);
ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr,
join_state, mc);
if (ret)
goto err2;
resp.id = mc->id;
if (copy_to_user(u64_to_user_ptr(cmd->response),
&resp, sizeof(resp))) {
ret = -EFAULT;
goto err3;
}
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return 0;
err3:
rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr);
ucma_cleanup_mc_events(mc);
err2:
mutex_lock(&mut);
idr_remove(&multicast_idr, mc->id);
mutex_unlock(&mut);
list_del(&mc->list);
kfree(mc);
err1:
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return ret;
}
Commit Message: infiniband: fix a possible use-after-free bug
ucma_process_join() will free the new allocated "mc" struct,
if there is any error after that, especially the copy_to_user().
But in parallel, ucma_leave_multicast() could find this "mc"
through idr_find() before ucma_process_join() frees it, since it
is already published.
So "mc" could be used in ucma_leave_multicast() after it is been
allocated and freed in ucma_process_join(), since we don't refcnt
it.
Fix this by separating "publish" from ID allocation, so that we
can get an ID first and publish it later after copy_to_user().
Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support")
Reported-by: Noam Rathaus <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-416 | static ssize_t ucma_process_join(struct ucma_file *file,
struct rdma_ucm_join_mcast *cmd, int out_len)
{
struct rdma_ucm_create_id_resp resp;
struct ucma_context *ctx;
struct ucma_multicast *mc;
struct sockaddr *addr;
int ret;
u8 join_state;
if (out_len < sizeof(resp))
return -ENOSPC;
addr = (struct sockaddr *) &cmd->addr;
if (cmd->addr_size != rdma_addr_size(addr))
return -EINVAL;
if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER)
join_state = BIT(FULLMEMBER_JOIN);
else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER)
join_state = BIT(SENDONLY_FULLMEMBER_JOIN);
else
return -EINVAL;
ctx = ucma_get_ctx_dev(file, cmd->id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
mutex_lock(&file->mut);
mc = ucma_alloc_multicast(ctx);
if (!mc) {
ret = -ENOMEM;
goto err1;
}
mc->join_state = join_state;
mc->uid = cmd->uid;
memcpy(&mc->addr, addr, cmd->addr_size);
ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr,
join_state, mc);
if (ret)
goto err2;
resp.id = mc->id;
if (copy_to_user(u64_to_user_ptr(cmd->response),
&resp, sizeof(resp))) {
ret = -EFAULT;
goto err3;
}
mutex_lock(&mut);
idr_replace(&multicast_idr, mc, mc->id);
mutex_unlock(&mut);
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return 0;
err3:
rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr);
ucma_cleanup_mc_events(mc);
err2:
mutex_lock(&mut);
idr_remove(&multicast_idr, mc->id);
mutex_unlock(&mut);
list_del(&mc->list);
kfree(mc);
err1:
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return ret;
}
| 169,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
unsigned long arg)
{
struct vbg_session *session = filp->private_data;
size_t returned_size, size;
struct vbg_ioctl_hdr hdr;
bool is_vmmdev_req;
int ret = 0;
void *buf;
if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
return -EFAULT;
if (hdr.version != VBG_IOCTL_HDR_VERSION)
return -EINVAL;
if (hdr.size_in < sizeof(hdr) ||
(hdr.size_out && hdr.size_out < sizeof(hdr)))
return -EINVAL;
size = max(hdr.size_in, hdr.size_out);
if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
return -EINVAL;
if (size > SZ_16M)
return -E2BIG;
/*
* IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
* the need for a bounce-buffer and another copy later on.
*/
is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
req == VBG_IOCTL_VMMDEV_REQUEST_BIG;
if (is_vmmdev_req)
buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
else
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, (void *)arg, hdr.size_in)) {
ret = -EFAULT;
goto out;
}
if (hdr.size_in < size)
memset(buf + hdr.size_in, 0, size - hdr.size_in);
ret = vbg_core_ioctl(session, req, buf);
if (ret)
goto out;
returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
if (returned_size > size) {
vbg_debug("%s: too much output data %zu > %zu\n",
__func__, returned_size, size);
returned_size = size;
}
if (copy_to_user((void *)arg, buf, returned_size) != 0)
ret = -EFAULT;
out:
if (is_vmmdev_req)
vbg_req_free(buf, size);
else
kfree(buf);
return ret;
}
Commit Message: virt: vbox: Only copy_from_user the request-header once
In vbg_misc_device_ioctl(), the header of the ioctl argument is copied from
the userspace pointer 'arg' and saved to the kernel object 'hdr'. Then the
'version', 'size_in', and 'size_out' fields of 'hdr' are verified.
Before this commit, after the checks a buffer for the entire request would
be allocated and then all data including the verified header would be
copied from the userspace 'arg' pointer again.
Given that the 'arg' pointer resides in userspace, a malicious userspace
process can race to change the data pointed to by 'arg' between the two
copies. By doing so, the user can bypass the verifications on the ioctl
argument.
This commit fixes this by using the already checked copy of the header
to fill the header part of the allocated buffer and only copying the
remainder of the data from userspace.
Signed-off-by: Wenwen Wang <[email protected]>
Reviewed-by: Hans de Goede <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362 | static long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
unsigned long arg)
{
struct vbg_session *session = filp->private_data;
size_t returned_size, size;
struct vbg_ioctl_hdr hdr;
bool is_vmmdev_req;
int ret = 0;
void *buf;
if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
return -EFAULT;
if (hdr.version != VBG_IOCTL_HDR_VERSION)
return -EINVAL;
if (hdr.size_in < sizeof(hdr) ||
(hdr.size_out && hdr.size_out < sizeof(hdr)))
return -EINVAL;
size = max(hdr.size_in, hdr.size_out);
if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
return -EINVAL;
if (size > SZ_16M)
return -E2BIG;
/*
* IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
* the need for a bounce-buffer and another copy later on.
*/
is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
req == VBG_IOCTL_VMMDEV_REQUEST_BIG;
if (is_vmmdev_req)
buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
else
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
*((struct vbg_ioctl_hdr *)buf) = hdr;
if (copy_from_user(buf + sizeof(hdr), (void *)arg + sizeof(hdr),
hdr.size_in - sizeof(hdr))) {
ret = -EFAULT;
goto out;
}
if (hdr.size_in < size)
memset(buf + hdr.size_in, 0, size - hdr.size_in);
ret = vbg_core_ioctl(session, req, buf);
if (ret)
goto out;
returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
if (returned_size > size) {
vbg_debug("%s: too much output data %zu > %zu\n",
__func__, returned_size, size);
returned_size = size;
}
if (copy_to_user((void *)arg, buf, returned_size) != 0)
ret = -EFAULT;
out:
if (is_vmmdev_req)
vbg_req_free(buf, size);
else
kfree(buf);
return ret;
}
| 169,188 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]));
}
return 0;
}
Commit Message: Changed the JPC bitstream code to more gracefully handle a request
for a larger sized integer than what can be handled (i.e., return
with an error instead of failing an assert).
CWE ID: | static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])),
i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])));
}
return 0;
}
| 168,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void _xml_unparsedEntityDeclHandler(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
xml_parser *parser = (xml_parser *)userData;
if (parser && parser->unparsedEntityDeclHandler) {
zval *retval, *args[6];
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding);
args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding);
args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding);
args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding);
args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) {
zval_ptr_dtor(&retval);
}
}
}
Commit Message:
CWE ID: CWE-119 | void _xml_unparsedEntityDeclHandler(void *userData,
void _xml_unparsedEntityDeclHandler(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
xml_parser *parser = (xml_parser *)userData;
if (parser && parser->unparsedEntityDeclHandler) {
zval *retval, *args[6];
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding);
args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding);
args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding);
args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding);
args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) {
zval_ptr_dtor(&retval);
}
}
}
| 165,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t hash_str(const void *ptr)
{
const char *str = (const char *)ptr;
size_t hash = 5381;
size_t c;
while((c = (size_t)*str))
{
hash = ((hash << 5) + hash) + c;
str++;
}
return hash;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static size_t hash_str(const void *ptr)
extern volatile uint32_t hashtable_seed;
/* Implementation of the hash function */
#include "lookup3.h"
| 166,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(const int argc, const char * const * const argv)
{
/* For each file on the command line test it with a range of transforms */
int option_end, ilog = 0;
struct display d;
validate_T();
display_init(&d);
for (option_end=1; option_end<argc; ++option_end)
{
const char *name = argv[option_end];
if (strcmp(name, "--verbose") == 0)
d.options = (d.options & ~LEVEL_MASK) | VERBOSE;
else if (strcmp(name, "--warnings") == 0)
d.options = (d.options & ~LEVEL_MASK) | WARNINGS;
else if (strcmp(name, "--errors") == 0)
d.options = (d.options & ~LEVEL_MASK) | ERRORS;
else if (strcmp(name, "--quiet") == 0)
d.options = (d.options & ~LEVEL_MASK) | QUIET;
else if (strcmp(name, "--exhaustive") == 0)
d.options |= EXHAUSTIVE;
else if (strcmp(name, "--fast") == 0)
d.options &= ~EXHAUSTIVE;
else if (strcmp(name, "--strict") == 0)
d.options |= STRICT;
else if (strcmp(name, "--relaxed") == 0)
d.options &= ~STRICT;
else if (strcmp(name, "--log") == 0)
{
ilog = option_end; /* prevent display */
d.options |= LOG;
}
else if (strcmp(name, "--nolog") == 0)
d.options &= ~LOG;
else if (strcmp(name, "--continue") == 0)
d.options |= CONTINUE;
else if (strcmp(name, "--stop") == 0)
d.options &= ~CONTINUE;
else if (strcmp(name, "--skip-bugs") == 0)
d.options |= SKIP_BUGS;
else if (strcmp(name, "--test-all") == 0)
d.options &= ~SKIP_BUGS;
else if (strcmp(name, "--log-skipped") == 0)
d.options |= LOG_SKIPPED;
else if (strcmp(name, "--nolog-skipped") == 0)
d.options &= ~LOG_SKIPPED;
else if (strcmp(name, "--find-bad-combos") == 0)
d.options |= FIND_BAD_COMBOS;
else if (strcmp(name, "--nofind-bad-combos") == 0)
d.options &= ~FIND_BAD_COMBOS;
else if (name[0] == '-' && name[1] == '-')
{
fprintf(stderr, "pngimage: %s: unknown option\n", name);
return 99;
}
else
break; /* Not an option */
}
{
int i;
int errors = 0;
for (i=option_end; i<argc; ++i)
{
{
int ret = do_test(&d, argv[i]);
if (ret > QUIET) /* abort on user or internal error */
return 99;
}
/* Here on any return, including failures, except user/internal issues
*/
{
const int pass = (d.options & STRICT) ?
RESULT_STRICT(d.results) : RESULT_RELAXED(d.results);
if (!pass)
++errors;
if (d.options & LOG)
{
int j;
printf("%s: pngimage ", pass ? "PASS" : "FAIL");
for (j=1; j<option_end; ++j) if (j != ilog)
printf("%s ", argv[j]);
printf("%s\n", d.filename);
}
}
display_clean(&d);
}
return errors != 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | main(const int argc, const char * const * const argv)
{
/* For each file on the command line test it with a range of transforms */
int option_end, ilog = 0;
struct display d;
validate_T();
display_init(&d);
for (option_end=1; option_end<argc; ++option_end)
{
const char *name = argv[option_end];
if (strcmp(name, "--verbose") == 0)
d.options = (d.options & ~LEVEL_MASK) | VERBOSE;
else if (strcmp(name, "--warnings") == 0)
d.options = (d.options & ~LEVEL_MASK) | WARNINGS;
else if (strcmp(name, "--errors") == 0)
d.options = (d.options & ~LEVEL_MASK) | ERRORS;
else if (strcmp(name, "--quiet") == 0)
d.options = (d.options & ~LEVEL_MASK) | QUIET;
else if (strcmp(name, "--exhaustive") == 0)
d.options |= EXHAUSTIVE;
else if (strcmp(name, "--fast") == 0)
d.options &= ~EXHAUSTIVE;
else if (strcmp(name, "--strict") == 0)
d.options |= STRICT;
else if (strcmp(name, "--relaxed") == 0)
d.options &= ~STRICT;
else if (strcmp(name, "--log") == 0)
{
ilog = option_end; /* prevent display */
d.options |= LOG;
}
else if (strcmp(name, "--nolog") == 0)
d.options &= ~LOG;
else if (strcmp(name, "--continue") == 0)
d.options |= CONTINUE;
else if (strcmp(name, "--stop") == 0)
d.options &= ~CONTINUE;
else if (strcmp(name, "--skip-bugs") == 0)
d.options |= SKIP_BUGS;
else if (strcmp(name, "--test-all") == 0)
d.options &= ~SKIP_BUGS;
else if (strcmp(name, "--log-skipped") == 0)
d.options |= LOG_SKIPPED;
else if (strcmp(name, "--nolog-skipped") == 0)
d.options &= ~LOG_SKIPPED;
else if (strcmp(name, "--find-bad-combos") == 0)
d.options |= FIND_BAD_COMBOS;
else if (strcmp(name, "--nofind-bad-combos") == 0)
d.options &= ~FIND_BAD_COMBOS;
else if (strcmp(name, "--list-combos") == 0)
d.options |= LIST_COMBOS;
else if (strcmp(name, "--nolist-combos") == 0)
d.options &= ~LIST_COMBOS;
else if (name[0] == '-' && name[1] == '-')
{
fprintf(stderr, "pngimage: %s: unknown option\n", name);
return 99;
}
else
break; /* Not an option */
}
{
int i;
int errors = 0;
for (i=option_end; i<argc; ++i)
{
{
int ret = do_test(&d, argv[i]);
if (ret > QUIET) /* abort on user or internal error */
return 99;
}
/* Here on any return, including failures, except user/internal issues
*/
{
const int pass = (d.options & STRICT) ?
RESULT_STRICT(d.results) : RESULT_RELAXED(d.results);
if (!pass)
++errors;
if (d.options & LOG)
{
int j;
printf("%s: pngimage ", pass ? "PASS" : "FAIL");
for (j=1; j<option_end; ++j) if (j != ilog)
printf("%s ", argv[j]);
printf("%s\n", d.filename);
}
}
display_clean(&d);
}
/* Release allocated memory */
display_destroy(&d);
return errors != 0;
}
}
| 173,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
(*sp->encodepfunc)(tif, bp, cc);
return (*sp->encoderow)(tif, bp, cc, s);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
if( !(*sp->encodepfunc)(tif, bp, cc) )
return 0;
return (*sp->encoderow)(tif, bp, cc, s);
}
| 166,878 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error <= 0) {
acl = NULL;
if (error < 0)
return error;
}
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
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 | xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode;
error = posix_acl_update_mode(inode, &mode, &acl);
if (error)
return error;
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
| 166,979 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DevToolsAgentHostImpl::ForceDetachAllClients() {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
while (!session_by_client_.empty()) {
DevToolsAgentHostClient* client = session_by_client_.begin()->first;
InnerDetachClient(client);
client->AgentHostClosed(this);
}
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | void DevToolsAgentHostImpl::ForceDetachAllClients() {
void DevToolsAgentHostImpl::ForceDetachAllSessions() {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
while (!sessions_.empty()) {
DevToolsAgentHostClient* client = (*sessions_.begin())->client();
DetachClient(client);
client->AgentHostClosed(this);
}
}
| 173,245 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long VideoTrack::GetWidth() const
{
return m_width;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long VideoTrack::GetWidth() const
| 174,382 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
#ifndef _MSC_VER
char buf[EXT2_BLOCK_SIZE (data)];
#else
char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));
#endif
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len))
return 0;
else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
return -1;
}
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS)
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove
CWE ID: CWE-787 | grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
#ifndef _MSC_VER
char buf[EXT2_BLOCK_SIZE (data)];
#else
char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));
#endif
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len))
return 0;
else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
return -1;
}
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS) {
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
} else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
| 168,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_set_filter(png_structp png_ptr, int method, int filters)
{
png_debug(1, "in png_set_filter");
if (png_ptr == NULL)
return;
#ifdef PNG_MNG_FEATURES_SUPPORTED
if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(method == PNG_INTRAPIXEL_DIFFERENCING))
method = PNG_FILTER_TYPE_BASE;
#endif
if (method == PNG_FILTER_TYPE_BASE)
{
switch (filters & (PNG_ALL_FILTERS | 0x07))
{
#ifdef PNG_WRITE_FILTER_SUPPORTED
case 5:
case 6:
case 7: png_warning(png_ptr, "Unknown row filter for method 0");
#endif /* PNG_WRITE_FILTER_SUPPORTED */
case PNG_FILTER_VALUE_NONE:
png_ptr->do_filter = PNG_FILTER_NONE; break;
#ifdef PNG_WRITE_FILTER_SUPPORTED
case PNG_FILTER_VALUE_SUB:
png_ptr->do_filter = PNG_FILTER_SUB; break;
case PNG_FILTER_VALUE_UP:
png_ptr->do_filter = PNG_FILTER_UP; break;
case PNG_FILTER_VALUE_AVG:
png_ptr->do_filter = PNG_FILTER_AVG; break;
case PNG_FILTER_VALUE_PAETH:
png_ptr->do_filter = PNG_FILTER_PAETH; break;
default: png_ptr->do_filter = (png_byte)filters; break;
#else
default: png_warning(png_ptr, "Unknown row filter for method 0");
#endif /* PNG_WRITE_FILTER_SUPPORTED */
}
/* If we have allocated the row_buf, this means we have already started
* with the image and we should have allocated all of the filter buffers
* that have been selected. If prev_row isn't already allocated, then
* it is too late to start using the filters that need it, since we
* will be missing the data in the previous row. If an application
* wants to start and stop using particular filters during compression,
* it should start out with all of the filters, and then add and
* remove them after the start of compression.
*/
if (png_ptr->row_buf != NULL)
{
#ifdef PNG_WRITE_FILTER_SUPPORTED
if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
{
png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
}
if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Up filter after starting");
png_ptr->do_filter &= ~PNG_FILTER_UP;
}
else
{
png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
}
}
if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Average filter after starting");
png_ptr->do_filter &= ~PNG_FILTER_AVG;
}
else
{
png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
}
}
if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
png_ptr->paeth_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Paeth filter after starting");
png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
}
else
{
png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
}
}
if (png_ptr->do_filter == PNG_NO_FILTERS)
#endif /* PNG_WRITE_FILTER_SUPPORTED */
png_ptr->do_filter = PNG_FILTER_NONE;
}
}
else
png_error(png_ptr, "Unknown custom filter method");
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_set_filter(png_structp png_ptr, int method, int filters)
{
png_debug(1, "in png_set_filter");
if (png_ptr == NULL)
return;
#ifdef PNG_MNG_FEATURES_SUPPORTED
if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(method == PNG_INTRAPIXEL_DIFFERENCING))
method = PNG_FILTER_TYPE_BASE;
#endif
if (method == PNG_FILTER_TYPE_BASE)
{
switch (filters & (PNG_ALL_FILTERS | 0x07))
{
case PNG_FILTER_VALUE_NONE:
png_ptr->do_filter = PNG_FILTER_NONE; break;
#ifdef PNG_WRITE_FILTER_SUPPORTED
case 5:
case 6:
case 7: png_warning(png_ptr, "Unknown row filter for method 0");
break;
case PNG_FILTER_VALUE_SUB:
png_ptr->do_filter = PNG_FILTER_SUB; break;
case PNG_FILTER_VALUE_UP:
png_ptr->do_filter = PNG_FILTER_UP; break;
case PNG_FILTER_VALUE_AVG:
png_ptr->do_filter = PNG_FILTER_AVG; break;
case PNG_FILTER_VALUE_PAETH:
png_ptr->do_filter = PNG_FILTER_PAETH; break;
default: png_ptr->do_filter = (png_byte)filters; break;
#else
default: png_warning(png_ptr, "Unknown row filter for method 0");
break;
#endif /* PNG_WRITE_FILTER_SUPPORTED */
}
/* If we have allocated the row_buf, this means we have already started
* with the image and we should have allocated all of the filter buffers
* that have been selected. If prev_row isn't already allocated, then
* it is too late to start using the filters that need it, since we
* will be missing the data in the previous row. If an application
* wants to start and stop using particular filters during compression,
* it should start out with all of the filters, and then add and
* remove them after the start of compression.
*/
if (png_ptr->row_buf != NULL)
{
#ifdef PNG_WRITE_FILTER_SUPPORTED
if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
{
png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
}
if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Up filter after starting");
png_ptr->do_filter &= ~PNG_FILTER_UP;
}
else
{
png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
}
}
if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Average filter after starting");
png_ptr->do_filter &= ~PNG_FILTER_AVG;
}
else
{
png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
}
}
if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
png_ptr->paeth_row == NULL)
{
if (png_ptr->prev_row == NULL)
{
png_warning(png_ptr, "Can't add Paeth filter after starting");
png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
}
else
{
png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
(png_ptr->rowbytes + 1));
png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
}
}
if (png_ptr->do_filter == PNG_NO_FILTERS)
#endif /* PNG_WRITE_FILTER_SUPPORTED */
png_ptr->do_filter = PNG_FILTER_NONE;
}
}
else
png_error(png_ptr, "Unknown custom filter method");
}
| 172,187 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static RList *relocs(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *list = r_list_newf ((RListFree)free);
int i, len, n_got, amount;
if (!list || !obj) {
r_list_free (list);
return NULL;
}
if (obj->hdr->flags & FLAT_FLAG_GOTPIC) {
n_got = get_ngot_entries (obj);
if (n_got) {
amount = n_got * sizeof (ut32);
if (amount < n_got || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *got_table = calloc (1, n_got * sizeof (ut32));
if (got_table) {
ut32 offset = 0;
for (i = 0; i < n_got ; offset += 4, i++) {
ut32 got_entry;
if (obj->hdr->data_start + offset + 4 > obj->size ||
obj->hdr->data_start + offset + 4 < offset) {
break;
}
len = r_buf_read_at (obj->b, obj->hdr->data_start + offset,
(ut8 *)&got_entry, sizeof (ut32));
if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) {
break;
}
got_table[i].addr_to_patch = got_entry;
got_table[i].data_offset = got_entry + BFLT_HDR_SIZE;
}
obj->n_got = n_got;
obj->got_table = got_table;
}
}
}
if (obj->hdr->reloc_count > 0) {
int n_reloc = obj->hdr->reloc_count;
amount = n_reloc * sizeof (struct reloc_struct_t);
if (amount < n_reloc || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *reloc_table = calloc (1, amount + 1);
if (!reloc_table) {
goto out_error;
}
amount = n_reloc * sizeof (ut32);
if (amount < n_reloc || amount > UT32_MAX) {
free (reloc_table);
goto out_error;
}
ut32 *reloc_pointer_table = calloc (1, amount + 1);
if (!reloc_pointer_table) {
free (reloc_table);
goto out_error;
}
if (obj->hdr->reloc_start + amount > obj->size ||
obj->hdr->reloc_start + amount < amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, obj->hdr->reloc_start,
(ut8 *)reloc_pointer_table, amount);
if (len != amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
for (i = 0; i < obj->hdr->reloc_count; i++) {
ut32 reloc_offset =
r_swap_ut32 (reloc_pointer_table[i]) +
BFLT_HDR_SIZE;
if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) {
ut32 reloc_fixed, reloc_data_offset;
if (reloc_offset + sizeof (ut32) > obj->size ||
reloc_offset + sizeof (ut32) < reloc_offset) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, reloc_offset,
(ut8 *)&reloc_fixed,
sizeof (ut32));
if (len != sizeof (ut32)) {
eprintf ("problem while reading relocation entries\n");
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE;
reloc_table[i].addr_to_patch = reloc_offset;
reloc_table[i].data_offset = reloc_data_offset;
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
}
free (reloc_pointer_table);
obj->reloc_table = reloc_table;
}
return list;
out_error:
r_list_free (list);
return NULL;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119 | static RList *relocs(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *list = r_list_newf ((RListFree)free);
int i, len, n_got, amount;
if (!list || !obj) {
r_list_free (list);
return NULL;
}
if (obj->hdr->flags & FLAT_FLAG_GOTPIC) {
n_got = get_ngot_entries (obj);
if (n_got) {
amount = n_got * sizeof (ut32);
if (amount < n_got || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *got_table = calloc (
1, n_got * sizeof (struct reloc_struct_t));
if (got_table) {
ut32 offset = 0;
for (i = 0; i < n_got ; offset += 4, i++) {
ut32 got_entry;
if (obj->hdr->data_start + offset + 4 > obj->size ||
obj->hdr->data_start + offset + 4 < offset) {
break;
}
len = r_buf_read_at (obj->b, obj->hdr->data_start + offset,
(ut8 *)&got_entry, sizeof (ut32));
if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) {
break;
}
got_table[i].addr_to_patch = got_entry;
got_table[i].data_offset = got_entry + BFLT_HDR_SIZE;
}
obj->n_got = n_got;
obj->got_table = got_table;
}
}
}
if (obj->hdr->reloc_count > 0) {
int n_reloc = obj->hdr->reloc_count;
amount = n_reloc * sizeof (struct reloc_struct_t);
if (amount < n_reloc || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *reloc_table = calloc (1, amount + 1);
if (!reloc_table) {
goto out_error;
}
amount = n_reloc * sizeof (ut32);
if (amount < n_reloc || amount > UT32_MAX) {
free (reloc_table);
goto out_error;
}
ut32 *reloc_pointer_table = calloc (1, amount + 1);
if (!reloc_pointer_table) {
free (reloc_table);
goto out_error;
}
if (obj->hdr->reloc_start + amount > obj->size ||
obj->hdr->reloc_start + amount < amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, obj->hdr->reloc_start,
(ut8 *)reloc_pointer_table, amount);
if (len != amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
for (i = 0; i < obj->hdr->reloc_count; i++) {
ut32 reloc_offset =
r_swap_ut32 (reloc_pointer_table[i]) +
BFLT_HDR_SIZE;
if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) {
ut32 reloc_fixed, reloc_data_offset;
if (reloc_offset + sizeof (ut32) > obj->size ||
reloc_offset + sizeof (ut32) < reloc_offset) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, reloc_offset,
(ut8 *)&reloc_fixed,
sizeof (ut32));
if (len != sizeof (ut32)) {
eprintf ("problem while reading relocation entries\n");
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE;
reloc_table[i].addr_to_patch = reloc_offset;
reloc_table[i].data_offset = reloc_data_offset;
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
}
free (reloc_pointer_table);
obj->reloc_table = reloc_table;
}
return list;
out_error:
r_list_free (list);
return NULL;
}
| 168,364 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
| 167,207 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void xgroupCommand(client *c) {
const char *help[] = {
"CREATE <key> <groupname> <id or $> -- Create a new consumer group.",
"SETID <key> <groupname> <id or $> -- Set the current group ID.",
"DELGROUP <key> <groupname> -- Remove the specified group.",
"DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.",
"HELP -- Prints this help.",
NULL
};
stream *s = NULL;
sds grpname = NULL;
streamCG *cg = NULL;
char *opt = c->argv[1]->ptr; /* Subcommand name. */
/* Lookup the key now, this is common for all the subcommands but HELP. */
if (c->argc >= 4) {
robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr);
if (o == NULL) return;
s = o->ptr;
grpname = c->argv[3]->ptr;
/* Certain subcommands require the group to exist. */
if ((cg = streamLookupCG(s,grpname)) == NULL &&
(!strcasecmp(opt,"SETID") ||
!strcasecmp(opt,"DELCONSUMER")))
{
addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' "
"for key name '%s'",
(char*)grpname, (char*)c->argv[2]->ptr);
return;
}
}
/* Dispatch the different subcommands. */
if (!strcasecmp(opt,"CREATE") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id);
if (cg) {
addReply(c,shared.ok);
server.dirty++;
} else {
addReplySds(c,
sdsnew("-BUSYGROUP Consumer Group name already exists\r\n"));
}
} else if (!strcasecmp(opt,"SETID") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
cg->last_id = id;
addReply(c,shared.ok);
} else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) {
if (cg) {
raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL);
streamFreeCG(cg);
addReply(c,shared.cone);
} else {
addReply(c,shared.czero);
}
} else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) {
/* Delete the consumer and returns the number of pending messages
* that were yet associated with such a consumer. */
long long pending = streamDelConsumer(cg,c->argv[4]->ptr);
addReplyLongLong(c,pending);
server.dirty++;
} else if (!strcasecmp(opt,"HELP")) {
addReplyHelp(c, help);
} else {
addReply(c,shared.syntaxerr);
}
}
Commit Message: Abort in XGROUP if the key is not a stream
CWE ID: CWE-704 | void xgroupCommand(client *c) {
const char *help[] = {
"CREATE <key> <groupname> <id or $> -- Create a new consumer group.",
"SETID <key> <groupname> <id or $> -- Set the current group ID.",
"DELGROUP <key> <groupname> -- Remove the specified group.",
"DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.",
"HELP -- Prints this help.",
NULL
};
stream *s = NULL;
sds grpname = NULL;
streamCG *cg = NULL;
char *opt = c->argv[1]->ptr; /* Subcommand name. */
/* Lookup the key now, this is common for all the subcommands but HELP. */
if (c->argc >= 4) {
robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr);
if (o == NULL || checkType(c,o,OBJ_STREAM)) return;
s = o->ptr;
grpname = c->argv[3]->ptr;
/* Certain subcommands require the group to exist. */
if ((cg = streamLookupCG(s,grpname)) == NULL &&
(!strcasecmp(opt,"SETID") ||
!strcasecmp(opt,"DELCONSUMER")))
{
addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' "
"for key name '%s'",
(char*)grpname, (char*)c->argv[2]->ptr);
return;
}
}
/* Dispatch the different subcommands. */
if (!strcasecmp(opt,"CREATE") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id);
if (cg) {
addReply(c,shared.ok);
server.dirty++;
} else {
addReplySds(c,
sdsnew("-BUSYGROUP Consumer Group name already exists\r\n"));
}
} else if (!strcasecmp(opt,"SETID") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
cg->last_id = id;
addReply(c,shared.ok);
} else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) {
if (cg) {
raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL);
streamFreeCG(cg);
addReply(c,shared.cone);
} else {
addReply(c,shared.czero);
}
} else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) {
/* Delete the consumer and returns the number of pending messages
* that were yet associated with such a consumer. */
long long pending = streamDelConsumer(cg,c->argv[4]->ptr);
addReplyLongLong(c,pending);
server.dirty++;
} else if (!strcasecmp(opt,"HELP")) {
addReplyHelp(c, help);
} else {
addReply(c,shared.syntaxerr);
}
}
| 169,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetupMockGroup() {
std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo());
const int kMockInfoSize = GetResponseInfoSize(info.get());
scoped_refptr<AppCacheGroup> group(
new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId));
scoped_refptr<AppCache> cache(
new AppCache(service_->storage(), kMockCacheId));
cache->AddEntry(
kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId,
kMockInfoSize + kMockBodySize));
cache->set_complete(true);
group->AddCache(cache.get());
mock_storage()->AddStoredGroup(group.get());
mock_storage()->AddStoredCache(cache.get());
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void SetupMockGroup() {
std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo());
const int kMockInfoSize = GetResponseInfoSize(info.get());
scoped_refptr<AppCacheGroup> group(
new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId));
scoped_refptr<AppCache> cache(
new AppCache(service_->storage(), kMockCacheId));
cache->AddEntry(
kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId,
kMockInfoSize + kMockBodySize, /*padding_size=*/0));
cache->set_complete(true);
group->AddCache(cache.get());
mock_storage()->AddStoredGroup(group.get());
mock_storage()->AddStoredCache(cache.get());
}
| 172,984 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SubprocessMetricsProviderTest()
: thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) {
base::PersistentHistogramAllocator::GetCreateHistogramResultHistogram();
provider_.MergeHistogramDeltas();
test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting();
base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE,
0, "");
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | SubprocessMetricsProviderTest()
: thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) {
provider_.MergeHistogramDeltas();
test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting();
base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE,
0, "");
}
| 172,140 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int equalizer_get_parameter(effect_context_t *context, effect_param_t *p,
uint32_t *size)
{
equalizer_context_t *eq_ctxt = (equalizer_context_t *)context;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
int32_t *param_tmp = (int32_t *)p->data;
int32_t param = *param_tmp++;
int32_t param2;
char *name;
void *value = p->data + voffset;
int i;
ALOGV("%s", __func__);
p->status = 0;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (p->vsize < sizeof(int16_t))
p->status = -EINVAL;
p->vsize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (p->vsize < 2 * sizeof(int16_t))
p->status = -EINVAL;
p->vsize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (p->vsize < 2 * sizeof(int32_t))
p->status = -EINVAL;
p->vsize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (p->vsize < sizeof(int32_t))
p->status = -EINVAL;
p->vsize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (p->vsize < (2 + NUM_EQ_BANDS) * sizeof(uint16_t))
p->status = -EINVAL;
p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t);
break;
default:
p->status = -EINVAL;
}
*size = sizeof(effect_param_t) + voffset + p->vsize;
if (p->status != 0)
return 0;
switch (param) {
case EQ_PARAM_NUM_BANDS:
ALOGV("%s: EQ_PARAM_NUM_BANDS", __func__);
*(uint16_t *)value = (uint16_t)NUM_EQ_BANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
ALOGV("%s: EQ_PARAM_LEVEL_RANGE", __func__);
*(int16_t *)value = -1500;
*((int16_t *)value + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
ALOGV("%s: EQ_PARAM_BAND_LEVEL", __func__);
param2 = *param_tmp;
if (param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
break;
}
*(int16_t *)value = (int16_t)equalizer_get_band_level(eq_ctxt, param2);
break;
case EQ_PARAM_CENTER_FREQ:
ALOGV("%s: EQ_PARAM_CENTER_FREQ", __func__);
param2 = *param_tmp;
if (param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
break;
}
*(int32_t *)value = equalizer_get_center_frequency(eq_ctxt, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
ALOGV("%s: EQ_PARAM_BAND_FREQ_RANGE", __func__);
param2 = *param_tmp;
if (param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
break;
}
equalizer_get_band_freq_range(eq_ctxt, param2, (uint32_t *)value,
((uint32_t *)value + 1));
break;
case EQ_PARAM_GET_BAND:
ALOGV("%s: EQ_PARAM_GET_BAND", __func__);
param2 = *param_tmp;
*(uint16_t *)value = (uint16_t)equalizer_get_band(eq_ctxt, param2);
break;
case EQ_PARAM_CUR_PRESET:
ALOGV("%s: EQ_PARAM_CUR_PRESET", __func__);
*(uint16_t *)value = (uint16_t)equalizer_get_preset(eq_ctxt);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
ALOGV("%s: EQ_PARAM_GET_NUM_OF_PRESETS", __func__);
*(uint16_t *)value = (uint16_t)equalizer_get_num_presets(eq_ctxt);
break;
case EQ_PARAM_GET_PRESET_NAME:
ALOGV("%s: EQ_PARAM_GET_PRESET_NAME", __func__);
param2 = *param_tmp;
ALOGV("param2: %d", param2);
if (param2 >= equalizer_get_num_presets(eq_ctxt)) {
p->status = -EINVAL;
break;
}
name = (char *)value;
strlcpy(name, equalizer_get_preset_name(eq_ctxt, param2), p->vsize - 1);
name[p->vsize - 1] = 0;
p->vsize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
ALOGV("%s: EQ_PARAM_PROPERTIES", __func__);
int16_t *prop = (int16_t *)value;
prop[0] = (int16_t)equalizer_get_preset(eq_ctxt);
prop[1] = (int16_t)NUM_EQ_BANDS;
for (i = 0; i < NUM_EQ_BANDS; i++) {
prop[2 + i] = (int16_t)equalizer_get_band_level(eq_ctxt, i);
}
} break;
default:
p->status = -EINVAL;
break;
}
return 0;
}
Commit Message: Fix security vulnerability: Equalizer command might allow negative indexes
Bug: 32247948
Bug: 32438598
Bug: 32436341
Test: use POC on bug or cts security test
Change-Id: I56a92582687599b5b313dea1abcb8bcb19c7fc0e
(cherry picked from commit 3f37d4ef89f4f0eef9e201c5a91b7b2c77ed1071)
(cherry picked from commit ceb7b2d7a4c4cb8d03f166c61f5c7551c6c760aa)
CWE ID: CWE-200 | int equalizer_get_parameter(effect_context_t *context, effect_param_t *p,
uint32_t *size)
{
equalizer_context_t *eq_ctxt = (equalizer_context_t *)context;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
int32_t *param_tmp = (int32_t *)p->data;
int32_t param = *param_tmp++;
int32_t param2;
char *name;
void *value = p->data + voffset;
int i;
ALOGV("%s", __func__);
p->status = 0;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (p->vsize < sizeof(int16_t))
p->status = -EINVAL;
p->vsize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (p->vsize < 2 * sizeof(int16_t))
p->status = -EINVAL;
p->vsize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (p->vsize < 2 * sizeof(int32_t))
p->status = -EINVAL;
p->vsize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (p->vsize < sizeof(int32_t))
p->status = -EINVAL;
p->vsize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (p->vsize < (2 + NUM_EQ_BANDS) * sizeof(uint16_t))
p->status = -EINVAL;
p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t);
break;
default:
p->status = -EINVAL;
}
*size = sizeof(effect_param_t) + voffset + p->vsize;
if (p->status != 0)
return 0;
switch (param) {
case EQ_PARAM_NUM_BANDS:
ALOGV("%s: EQ_PARAM_NUM_BANDS", __func__);
*(uint16_t *)value = (uint16_t)NUM_EQ_BANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
ALOGV("%s: EQ_PARAM_LEVEL_RANGE", __func__);
*(int16_t *)value = -1500;
*((int16_t *)value + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
ALOGV("%s: EQ_PARAM_BAND_LEVEL", __func__);
param2 = *param_tmp;
if (param2 < 0 || param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32438598");
ALOGW("\tERROR EQ_PARAM_BAND_LEVEL band %d", param2);
}
break;
}
*(int16_t *)value = (int16_t)equalizer_get_band_level(eq_ctxt, param2);
break;
case EQ_PARAM_CENTER_FREQ:
ALOGV("%s: EQ_PARAM_CENTER_FREQ", __func__);
param2 = *param_tmp;
if (param2 < 0 || param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32436341");
ALOGW("\tERROR EQ_PARAM_CENTER_FREQ band %d", param2);
}
break;
}
*(int32_t *)value = equalizer_get_center_frequency(eq_ctxt, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
ALOGV("%s: EQ_PARAM_BAND_FREQ_RANGE", __func__);
param2 = *param_tmp;
if (param2 < 0 || param2 >= NUM_EQ_BANDS) {
p->status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32247948");
ALOGW("\tERROR EQ_PARAM_BAND_FREQ_RANGE band %d", param2);
}
break;
}
equalizer_get_band_freq_range(eq_ctxt, param2, (uint32_t *)value,
((uint32_t *)value + 1));
break;
case EQ_PARAM_GET_BAND:
ALOGV("%s: EQ_PARAM_GET_BAND", __func__);
param2 = *param_tmp;
*(uint16_t *)value = (uint16_t)equalizer_get_band(eq_ctxt, param2);
break;
case EQ_PARAM_CUR_PRESET:
ALOGV("%s: EQ_PARAM_CUR_PRESET", __func__);
*(uint16_t *)value = (uint16_t)equalizer_get_preset(eq_ctxt);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
ALOGV("%s: EQ_PARAM_GET_NUM_OF_PRESETS", __func__);
*(uint16_t *)value = (uint16_t)equalizer_get_num_presets(eq_ctxt);
break;
case EQ_PARAM_GET_PRESET_NAME:
ALOGV("%s: EQ_PARAM_GET_PRESET_NAME", __func__);
param2 = *param_tmp;
ALOGV("param2: %d", param2);
if (param2 >= equalizer_get_num_presets(eq_ctxt)) {
p->status = -EINVAL;
break;
}
name = (char *)value;
strlcpy(name, equalizer_get_preset_name(eq_ctxt, param2), p->vsize - 1);
name[p->vsize - 1] = 0;
p->vsize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
ALOGV("%s: EQ_PARAM_PROPERTIES", __func__);
int16_t *prop = (int16_t *)value;
prop[0] = (int16_t)equalizer_get_preset(eq_ctxt);
prop[1] = (int16_t)NUM_EQ_BANDS;
for (i = 0; i < NUM_EQ_BANDS; i++) {
prop[2 + i] = (int16_t)equalizer_get_band_level(eq_ctxt, i);
}
} break;
default:
p->status = -EINVAL;
break;
}
return 0;
}
| 174,611 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (defParams->nPortIndex >= mPorts.size()) {
return OMX_ErrorBadPortIndex;
}
if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUnsupportedSetting;
}
PortInfo *port =
&mPorts.editItemAt(defParams->nPortIndex);
if (defParams->nBufferSize > port->mDef.nBufferSize) {
port->mDef.nBufferSize = defParams->nBufferSize;
}
if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) {
ALOGW("component requires at least %u buffers (%u requested)",
port->mDef.nBufferCountMin, defParams->nBufferCountActual);
return OMX_ErrorUnsupportedSetting;
}
port->mDef.nBufferCountActual = defParams->nBufferCountActual;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (!isValidOMXParam(defParams)) {
return OMX_ErrorBadParameter;
}
if (defParams->nPortIndex >= mPorts.size()) {
return OMX_ErrorBadPortIndex;
}
if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUnsupportedSetting;
}
PortInfo *port =
&mPorts.editItemAt(defParams->nPortIndex);
if (defParams->nBufferSize > port->mDef.nBufferSize) {
port->mDef.nBufferSize = defParams->nBufferSize;
}
if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) {
ALOGW("component requires at least %u buffers (%u requested)",
port->mDef.nBufferCountMin, defParams->nBufferCountActual);
return OMX_ErrorUnsupportedSetting;
}
port->mDef.nBufferCountActual = defParams->nBufferCountActual;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
| 174,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadRequestLimiter::TabDownloadState::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
download_seen_ = false;
ui_status_ = DOWNLOAD_UI_DEFAULT;
if (navigation_handle->IsRendererInitiated() &&
(status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED)) {
return;
}
if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS ||
status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) {
if (!initial_page_host_.empty() &&
navigation_handle->GetURL().host_piece() == initial_page_host_) {
return;
}
}
NotifyCallbacks(false);
host_->Remove(this, web_contents());
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#574437}
CWE ID: | void DownloadRequestLimiter::TabDownloadState::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
download_seen_ = false;
ui_status_ = DOWNLOAD_UI_DEFAULT;
if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) {
std::string host = navigation_handle->GetURL().host();
// If the navigation is renderer-initiated (but not user-initiated), ensure
// that a prompting or blocking limiter state is not reset, so
// window.location.href or meta refresh can't be abused to avoid the
// limiter.
if (navigation_handle->IsRendererInitiated()) {
if (!host.empty())
restricted_hosts_.emplace(host);
return;
}
// If this is a forward/back navigation, also don't reset a prompting or
// blocking limiter state unless a new host is encounted. This prevents a
// page to use history forward/backward to trigger multiple downloads.
if (IsNavigationRestricted(navigation_handle))
return;
}
if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS ||
status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) {
if (!initial_page_host_.empty() &&
navigation_handle->GetURL().host_piece() == initial_page_host_) {
return;
}
}
NotifyCallbacks(false);
host_->Remove(this, web_contents());
}
| 173,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
depth,
packet_size,
quantum;
ssize_t
count,
y;
unsigned char
*colormap,
*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);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
status=AcquireImageColormap(image,(size_t)
(image->offset != 0 ? image->offset : 256));
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image colormap.
*/
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].red=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].green=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].blue=(Quantum) quantum;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read image pixels.
*/
packet_size=(size_t) (depth/8);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
count=ReadBlob(image,(size_t) packet_size*image->columns,pixels);
if (count != (ssize_t) (packet_size*image->columns))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
p++;
if (image->colors > 256)
{
index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p));
p++;
}
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (y < (ssize_t) image->rows)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
depth,
packet_size,
quantum;
ssize_t
count,
y;
unsigned char
*colormap,
*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);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
status=AcquireImageColormap(image,(size_t)
(image->offset != 0 ? image->offset : 256));
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image colormap.
*/
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].red=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].green=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].blue=(Quantum) quantum;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
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 image pixels.
*/
packet_size=(size_t) (depth/8);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
count=ReadBlob(image,(size_t) packet_size*image->columns,pixels);
if (count != (ssize_t) (packet_size*image->columns))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
p++;
if (image->colors > 256)
{
index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p));
p++;
}
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (y < (ssize_t) image->rows)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,579 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NaClListener::OnMsgStart(const nacl::NaClStartParams& params) {
struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
if (args == NULL) {
LOG(ERROR) << "NaClChromeMainArgsCreate() failed";
return;
}
if (params.enable_ipc_proxy) {
IPC::ChannelHandle channel_handle =
IPC::Channel::GenerateVerifiedChannelID("nacl");
scoped_refptr<NaClIPCAdapter> ipc_adapter(new NaClIPCAdapter(
channel_handle, io_thread_.message_loop_proxy()));
args->initial_ipc_desc = ipc_adapter.get()->MakeNaClDesc();
#if defined(OS_POSIX)
channel_handle.socket = base::FileDescriptor(
ipc_adapter.get()->TakeClientFileDescriptor(), true);
#endif
if (!Send(new NaClProcessHostMsg_PpapiChannelCreated(channel_handle)))
LOG(ERROR) << "Failed to send IPC channel handle to renderer.";
}
std::vector<nacl::FileDescriptor> handles = params.handles;
#if defined(OS_LINUX) || defined(OS_MACOSX)
args->urandom_fd = dup(base::GetUrandomFD());
if (args->urandom_fd < 0) {
LOG(ERROR) << "Failed to dup() the urandom FD";
return;
}
args->create_memory_object_func = CreateMemoryObject;
# if defined(OS_MACOSX)
CHECK(handles.size() >= 1);
g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
# endif
#endif
CHECK(handles.size() >= 1);
NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
#if defined(OS_WIN)
args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle),
_O_RDONLY | _O_BINARY);
if (args->irt_fd < 0) {
LOG(ERROR) << "_open_osfhandle() failed";
return;
}
#else
args->irt_fd = irt_handle;
#endif
if (params.validation_cache_enabled) {
CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
args->validation_cache = CreateValidationCache(
new BrowserValidationDBProxy(this), params.validation_cache_key,
params.version);
}
CHECK(handles.size() == 1);
args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]);
args->enable_exception_handling = params.enable_exception_handling;
args->enable_debug_stub = params.enable_debug_stub;
#if defined(OS_WIN)
args->broker_duplicate_handle_func = BrokerDuplicateHandle;
args->attach_debug_exception_handler_func = AttachDebugExceptionHandler;
#endif
NaClChromeMainStart(args);
NOTREACHED();
}
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 | void NaClListener::OnMsgStart(const nacl::NaClStartParams& params) {
struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
if (args == NULL) {
LOG(ERROR) << "NaClChromeMainArgsCreate() failed";
return;
}
std::vector<nacl::FileDescriptor> handles = params.handles;
#if defined(OS_LINUX) || defined(OS_MACOSX)
args->urandom_fd = dup(base::GetUrandomFD());
if (args->urandom_fd < 0) {
LOG(ERROR) << "Failed to dup() the urandom FD";
return;
}
args->create_memory_object_func = CreateMemoryObject;
# if defined(OS_MACOSX)
CHECK(handles.size() >= 1);
g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
# endif
#endif
CHECK(handles.size() >= 1);
NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
#if defined(OS_WIN)
args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle),
_O_RDONLY | _O_BINARY);
if (args->irt_fd < 0) {
LOG(ERROR) << "_open_osfhandle() failed";
return;
}
#else
args->irt_fd = irt_handle;
#endif
if (params.validation_cache_enabled) {
CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
args->validation_cache = CreateValidationCache(
new BrowserValidationDBProxy(this), params.validation_cache_key,
params.version);
}
CHECK(handles.size() == 1);
args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]);
args->enable_exception_handling = params.enable_exception_handling;
args->enable_debug_stub = params.enable_debug_stub;
#if defined(OS_WIN)
args->broker_duplicate_handle_func = BrokerDuplicateHandle;
args->attach_debug_exception_handler_func = AttachDebugExceptionHandler;
#endif
NaClChromeMainStart(args);
NOTREACHED();
}
| 170,732 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), 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;
transliterator_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add a few more confusable map entries
1. Map Malaylam U+0D1F to 's'.
2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase
letters.
The characters in new confusable map entries are replaced by their Latin
"look-alike" characters before the skeleton is calculated to compare with
top domain names.
Bug: 784761,773930
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee
Reviewed-on: https://chromium-review.googlesource.com/805214
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#521648}
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("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), 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();
// removal; NFC".
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// Supplement the Unicode confusable list by the following mapping.
// - U+04CF (ӏ) => l
// - {U+043A (к), U+0138(ĸ), U+03BA(κ)} => k
// - U+043F(п) => n
// - {U+0185 (ƅ), U+044C (ь)} => b
// - U+0432 (в) => b
// - U+043C (м) => m
// - U+043D (н) => h
// - U+0442 (т) => t
// - {U+0448 (ш), U+0449 (щ)} => w
// - U+0D1F (ട) => s
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString(
"ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; "
"т > t; [шщ] > w; ട > s;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCacheDatabase::ReadEntryRecord(
const sql::Statement& statement, EntryRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->url = GURL(statement.ColumnString(1));
record->flags = statement.ColumnInt(2);
record->response_id = statement.ColumnInt64(3);
record->response_size = statement.ColumnInt64(4);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCacheDatabase::ReadEntryRecord(
const sql::Statement& statement, EntryRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->url = GURL(statement.ColumnString(1));
record->flags = statement.ColumnInt(2);
record->response_id = statement.ColumnInt64(3);
record->response_size = statement.ColumnInt64(4);
record->padding_size = statement.ColumnInt64(5);
}
| 172,982 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id,
const QString &app_icon, const QString &summary, const QString &body,
const QStringList &actions, const QVariantMap &hints, int timeout)
{
uint partOf = 0;
const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString();
const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString();
const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool();
if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) {
partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt();
}
qDebug() << "Currrent active notifications:" << m_activeNotifications;
qDebug() << "Guessing partOf as:" << partOf;
qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf;
QString _body;
if (partOf > 0) {
const QString source = QStringLiteral("notification %1").arg(partOf);
Plasma::DataContainer *container = containerForSource(source);
if (container) {
_body = container->data()[QStringLiteral("body")].toString();
if (_body != body) {
_body.append("\n").append(body);
} else {
_body = body;
}
replaces_id = partOf;
CloseNotification(partOf);
}
}
uint id = replaces_id ? replaces_id : m_nextId++;
if (m_alwaysReplaceAppsList.contains(app_name)) {
if (m_notificationsFromReplaceableApp.contains(app_name)) {
id = m_notificationsFromReplaceableApp.value(app_name);
} else {
m_notificationsFromReplaceableApp.insert(app_name, id);
}
}
QString appname_str = app_name;
if (appname_str.isEmpty()) {
appname_str = i18n("Unknown Application");
}
bool isPersistent = timeout == 0;
const int AVERAGE_WORD_LENGTH = 6;
const int WORD_PER_MINUTE = 250;
int count = summary.length() + body.length();
timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE;
timeout = 2000 + qMax(timeout, 3000);
}
Commit Message:
CWE ID: CWE-200 | uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id,
const QString &app_icon, const QString &summary, const QString &body,
const QStringList &actions, const QVariantMap &hints, int timeout)
{
uint partOf = 0;
const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString();
const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString();
const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool();
if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) {
partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt();
}
qDebug() << "Currrent active notifications:" << m_activeNotifications;
qDebug() << "Guessing partOf as:" << partOf;
qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf;
QString bodyFinal = NotificationSanitizer::parse(body);
if (partOf > 0) {
const QString source = QStringLiteral("notification %1").arg(partOf);
Plasma::DataContainer *container = containerForSource(source);
if (container) {
const QString previousBody = container->data()[QStringLiteral("body")].toString();
if (previousBody != bodyFinal) {
// FIXME: This will just append the entire old XML document to another one, leading to:
// <?xml><html>old</html><br><?xml><html>new</html>
// It works but is not very clean.
bodyFinal = previousBody + QStringLiteral("<br/>") + bodyFinal;
}
replaces_id = partOf;
CloseNotification(partOf);
}
}
uint id = replaces_id ? replaces_id : m_nextId++;
if (m_alwaysReplaceAppsList.contains(app_name)) {
if (m_notificationsFromReplaceableApp.contains(app_name)) {
id = m_notificationsFromReplaceableApp.value(app_name);
} else {
m_notificationsFromReplaceableApp.insert(app_name, id);
}
}
QString appname_str = app_name;
if (appname_str.isEmpty()) {
appname_str = i18n("Unknown Application");
}
bool isPersistent = timeout == 0;
const int AVERAGE_WORD_LENGTH = 6;
const int WORD_PER_MINUTE = 250;
int count = summary.length() + body.length() - strlen("<?xml version=\"1.0\"><html></html>");
timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE;
timeout = 2000 + qMax(timeout, 3000);
}
| 165,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-13026/IS-IS: Clean up processing of subTLVs.
Add bounds checks, do a common check to make sure we captured the entire
subTLV, add checks to make sure the subTLV fits within the TLV.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add tests using the capture files supplied by the reporter(s), modified
so the capture files won't be rejected as an invalid capture.
Update existing tests for changes to IS-IS dissector.
CWE ID: CWE-125 | isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN)
goto trunc;
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN;
len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
| 167,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if ((stop >= 0) && (pos >= stop))
return E_FILE_FORMAT_INVALID;
long len;
id = ReadUInt(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if ((stop >= 0) && (pos >= stop))
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if ((stop >= 0) && ((pos + size) > stop))
return E_FILE_FORMAT_INVALID;
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos,
long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
// Invalid: Negative payload size, negative or 0 length integer, or integer
// larger than 64 bits (libwebm cannot handle them).
return E_FILE_FORMAT_INVALID;
}
// Avoid rolling over pos when very close to LONG_LONG_MAX.
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 173,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta,
gfx::Vector2dF overscroll_velocity) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(),
overscroll_delta.y(), overscroll_velocity.x(),
overscroll_velocity.y());
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta,
void AwContents::DidOverscroll(const gfx::Vector2d& overscroll_delta,
const gfx::Vector2dF& overscroll_velocity) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_didOverscroll(env, obj.obj(), overscroll_delta.x(),
overscroll_delta.y(), overscroll_velocity.x(),
overscroll_velocity.y());
}
| 171,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_emit_signal2 (MyObject *obj, GError **error)
{
GHashTable *table;
table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (table, "baz", "cow");
g_hash_table_insert (table, "bar", "foo");
g_signal_emit (obj, signals[SIG2], 0, table);
g_hash_table_destroy (table);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_emit_signal2 (MyObject *obj, GError **error)
| 165,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain == 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
Commit Message: Avoid potentially dangerous signed to unsigned conversion
We make sure to never pass a negative `rlen` as size to memcpy(). See
also <https://bugs.php.net/bug.php?id=73280>.
Patch provided by Emmanuel Law.
CWE ID: CWE-119 | static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
| 168,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/348
CWE ID: CWE-787 | static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
| 168,402 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
size_t dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, iter, iteriter, regexiter;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg, dir, dir_len);
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
zval_ptr_dtor(&arg);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
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, "Unable to instantiate directory iterator for %s", phar_obj->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;
if (SUCCESS != object_init_ex(®exiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(®exiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg2, regex, regex_len);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
zval_ptr_dtor(&arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(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, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
return;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? ®exiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->archive->ufp = pass.fp;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
size_t dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, iter, iteriter, regexiter;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg, dir, dir_len);
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
zval_ptr_dtor(&arg);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
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, "Unable to instantiate directory iterator for %s", phar_obj->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;
if (SUCCESS != object_init_ex(®exiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(®exiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg2, regex, regex_len);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
zval_ptr_dtor(&arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(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, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
return;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? ®exiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->archive->ufp = pass.fp;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
| 165,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
texture_layer_->setTextureId(params.surface_handle);
DCHECK(texture_layer_ == layer_);
layer_->setBounds(params.size);
texture_id_in_layer_ = params.surface_handle;
texture_size_in_layer_ = params.size;
DCHECK(!CompositorImpl::IsThreadingEnabled());
uint32 sync_point =
ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint();
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, true, sync_point);
}
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 RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
ImageTransportFactoryAndroid* factory =
ImageTransportFactoryAndroid::GetInstance();
// need to delay the ACK until after commit and use more than a single
// texture.
DCHECK(!CompositorImpl::IsThreadingEnabled());
uint64 previous_buffer = current_buffer_id_;
if (previous_buffer && texture_id_in_layer_) {
DCHECK(id_to_mailbox_.find(previous_buffer) != id_to_mailbox_.end());
ImageTransportFactoryAndroid::GetInstance()->ReleaseTexture(
texture_id_in_layer_,
reinterpret_cast<const signed char*>(
id_to_mailbox_[previous_buffer].c_str()));
}
current_buffer_id_ = params.surface_handle;
if (!texture_id_in_layer_) {
texture_id_in_layer_ = factory->CreateTexture();
texture_layer_->setTextureId(texture_id_in_layer_);
}
DCHECK(id_to_mailbox_.find(current_buffer_id_) != id_to_mailbox_.end());
ImageTransportFactoryAndroid::GetInstance()->AcquireTexture(
texture_id_in_layer_,
reinterpret_cast<const signed char*>(
id_to_mailbox_[current_buffer_id_].c_str()));
texture_layer_->setNeedsDisplay();
texture_layer_->setBounds(params.size);
texture_size_in_layer_ = params.size;
uint32 sync_point =
ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint();
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, gpu_host_id, previous_buffer, sync_point);
}
| 171,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_recv_plaintext(int sock)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = 512;
buf = calloc(1, chunk_size);
while (1) {
errno = 0;
rc = read(sock, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
if (errno == EINTR || errno == EAGAIN) {
crm_trace("Retry: %d", (int)rc);
if (rc > 0) {
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
}
} else if (rc < 0) {
crm_perror(LOG_ERR, "Error receiving message: %d", (int)rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_recv_plaintext(int sock)
/*!
* \internal
* \brief Read bytes off non blocking socket.
*
* \param session - tls session to read
* \param max_size - max bytes allowed to read for buffer. 0 assumes no limit
*
* \note only use with NON-Blocking sockets. Should only be used after polling socket.
* This function will return once max_size is met, the socket read buffer
* is empty, or an error is encountered.
*
* \retval '\0' terminated buffer on success
*/
static char *
crm_recv_plaintext(int sock, size_t max_size, size_t *recv_len, int *disconnected)
{
char *buf = NULL;
ssize_t rc = 0;
ssize_t len = 0;
ssize_t chunk_size = max_size ? max_size : 1024;
size_t buf_size = 0;
size_t read_size = 0;
if (sock <= 0) {
if (disconnected) {
*disconnected = 1;
}
goto done;
}
buf = calloc(1, chunk_size + 1);
buf_size = chunk_size;
while (TRUE) {
errno = 0;
read_size = buf_size - len;
/* automatically grow the buffer when needed if max_size is not set.*/
if (!max_size && (read_size < (chunk_size / 2))) {
buf_size += chunk_size;
crm_trace("Grow buffer by %d more bytes. buf is now %d bytes", (int)chunk_size, buf_size);
buf = realloc(buf, buf_size + 1);
CRM_ASSERT(buf != NULL);
read_size = buf_size - len;
}
rc = read(sock, buf + len, chunk_size);
if (rc > 0) {
crm_trace("Got %d more bytes. errno=%d", (int)rc, errno);
len += rc;
/* always null terminate buffer, the +1 to alloc always allows for this.*/
buf[len] = '\0';
}
if (max_size && (max_size == read_size)) {
crm_trace("Buffer max read size %d met" , max_size);
goto done;
}
if (rc > 0) {
continue;
} else if (rc == 0) {
if (disconnected) {
*disconnected = 1;
}
crm_trace("EOF encoutered during read");
goto done;
}
/* process errors */
if (errno == EINTR) {
crm_trace("EINTER encoutered, retry socket read.");
} else if (errno == EAGAIN) {
crm_trace("non-blocking, exiting read on rc = %d", rc);
goto done;
} else if (errno <= 0) {
if (disconnected) {
*disconnected = 1;
}
crm_debug("Error receiving message: %d", (int)rc);
goto done;
}
}
done:
if (recv_len) {
*recv_len = len;
}
if (!len) {
free(buf);
buf = NULL;
}
return buf;
}
| 166,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
Commit Message: Avoid uninitialized memory
As reported by https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16856
CWE ID: | Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
} else {
matvar->name[tmp - 1] = '\0';
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
| 169,491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.