instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: exsltCryptoRc4DecryptFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int key_len = 0, key_size = 0;
int str_len = 0, bin_len = 0, ret_len = 0;
xmlChar *key = NULL, *str = NULL, *padkey = NULL, *bin =
NULL, *ret = NULL;
xsltTransformContextPtr tctxt = NULL;
if (nargs != 2) {
xmlXPathSetArityError (ctxt);
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
str = xmlXPathPopString (ctxt);
str_len = xmlUTF8Strlen (str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (str);
return;
}
key = xmlXPathPopString (ctxt);
key_len = xmlUTF8Strlen (key);
if (key_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (key);
xmlFree (str);
return;
}
padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1);
if (padkey == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memset(padkey, 0, RC4_KEY_LENGTH + 1);
key_size = xmlUTF8Strsize (key, key_len);
if ((key_size > RC4_KEY_LENGTH) || (key_size < 0)) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: key size too long or key broken\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memcpy (padkey, key, key_size);
/* decode hex to binary */
bin_len = str_len;
bin = xmlMallocAtomic (bin_len);
if (bin == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate string\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
ret_len = exsltCryptoHex2Bin (str, str_len, bin, bin_len);
/* decrypt the binary blob */
ret = xmlMallocAtomic (ret_len + 1);
if (ret == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate result\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
PLATFORM_RC4_DECRYPT (ctxt, padkey, bin, ret_len, ret, ret_len);
ret[ret_len] = 0;
xmlXPathReturnString (ctxt, ret);
done:
if (key != NULL)
xmlFree (key);
if (str != NULL)
xmlFree (str);
if (padkey != NULL)
xmlFree (padkey);
if (bin != NULL)
xmlFree (bin);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | exsltCryptoRc4DecryptFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int key_len = 0;
int str_len = 0, bin_len = 0, ret_len = 0;
xmlChar *key = NULL, *str = NULL, *padkey = NULL, *bin =
NULL, *ret = NULL;
xsltTransformContextPtr tctxt = NULL;
if (nargs != 2) {
xmlXPathSetArityError (ctxt);
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
str = xmlXPathPopString (ctxt);
str_len = xmlStrlen (str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (str);
return;
}
key = xmlXPathPopString (ctxt);
key_len = xmlStrlen (key);
if (key_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (key);
xmlFree (str);
return;
}
padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1);
if (padkey == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memset(padkey, 0, RC4_KEY_LENGTH + 1);
if ((key_len > RC4_KEY_LENGTH) || (key_len < 0)) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: key size too long or key broken\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memcpy (padkey, key, key_len);
/* decode hex to binary */
bin_len = str_len;
bin = xmlMallocAtomic (bin_len);
if (bin == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate string\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
ret_len = exsltCryptoHex2Bin (str, str_len, bin, bin_len);
/* decrypt the binary blob */
ret = xmlMallocAtomic (ret_len + 1);
if (ret == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate result\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
PLATFORM_RC4_DECRYPT (ctxt, padkey, bin, ret_len, ret, ret_len);
ret[ret_len] = 0;
xmlXPathReturnString (ctxt, ret);
done:
if (key != NULL)
xmlFree (key);
if (str != NULL)
xmlFree (str);
if (padkey != NULL)
xmlFree (padkey);
if (bin != NULL)
xmlFree (bin);
}
| 173,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringCase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringCase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringCase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringCase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringCase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringCase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() ||
equalIgnoringASCIICase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringASCIICase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringASCIICase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringASCIICase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringASCIICase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringASCIICase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringASCIICase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
| 171,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
int completion)
{
int dir;
size_t len = 0;
const char *str = NULL;
int pid;
int ret;
int i;
USBDevice *dev;
USBEndpoint *ep;
struct ohci_iso_td iso_td;
uint32_t addr;
uint16_t starting_frame;
int16_t relative_frame_number;
int frame_count;
uint32_t start_offset, next_offset, end_offset = 0;
uint32_t start_addr, end_addr;
addr = ed->head & OHCI_DPTR_MASK;
if (ohci_read_iso_td(ohci, addr, &iso_td)) {
trace_usb_ohci_iso_td_read_failed(addr);
ohci_die(ohci);
return 0;
}
starting_frame = OHCI_BM(iso_td.flags, TD_SF);
frame_count = OHCI_BM(iso_td.flags, TD_FC);
relative_frame_number = USUB(ohci->frame_number, starting_frame);
trace_usb_ohci_iso_td_head(
ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
ohci->frame_number, starting_frame,
frame_count, relative_frame_number);
trace_usb_ohci_iso_td_head_offset(
iso_td.offset[0], iso_td.offset[1],
iso_td.offset[2], iso_td.offset[3],
iso_td.offset[4], iso_td.offset[5],
iso_td.offset[6], iso_td.offset[7]);
if (relative_frame_number < 0) {
trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number);
return 1;
} else if (relative_frame_number > frame_count) {
/* ISO TD expired - retire the TD to the Done Queue and continue with
the next ISO TD of the same ED */
trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number,
frame_count);
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
return 1;
}
return 0;
}
dir = OHCI_BM(ed->flags, ED_D);
switch (dir) {
case OHCI_TD_DIR_IN:
str = "in";
pid = USB_TOKEN_IN;
break;
case OHCI_TD_DIR_OUT:
str = "out";
pid = USB_TOKEN_OUT;
break;
case OHCI_TD_DIR_SETUP:
str = "setup";
pid = USB_TOKEN_SETUP;
break;
default:
trace_usb_ohci_iso_td_bad_direction(dir);
return 1;
}
if (!iso_td.bp || !iso_td.be) {
trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be);
return 1;
}
start_offset = iso_td.offset[relative_frame_number];
next_offset = iso_td.offset[relative_frame_number + 1];
if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||
((relative_frame_number < frame_count) &&
!(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset);
return 1;
}
if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset);
return 1;
}
if ((start_offset & 0x1000) == 0) {
start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
} else {
start_addr = (iso_td.be & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
}
if (relative_frame_number < frame_count) {
end_offset = next_offset - 1;
if ((end_offset & 0x1000) == 0) {
end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
} else {
end_addr = (iso_td.be & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
}
} else {
/* Last packet in the ISO TD */
end_addr = iso_td.be;
}
if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
- (start_addr & OHCI_OFFSET_MASK);
} else {
len = end_addr - start_addr + 1;
}
if (len && dir != OHCI_TD_DIR_IN) {
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
DMA_DIRECTION_TO_DEVICE)) {
ohci_die(ohci);
return 1;
}
}
if (!completion) {
bool int_req = relative_frame_number == frame_count &&
OHCI_BM(iso_td.flags, TD_DI) == 0;
dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
usb_handle_packet(dev, &ohci->usb_packet);
if (ohci->usb_packet.status == USB_RET_ASYNC) {
usb_device_flush_ep_queue(dev, ep);
return 1;
}
}
if (ohci->usb_packet.status == USB_RET_SUCCESS) {
ret = ohci->usb_packet.actual_length;
} else {
ret = ohci->usb_packet.status;
}
trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
str, len, ret);
/* Writeback */
if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
/* IN transfer succeeded */
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
DMA_DIRECTION_FROM_DEVICE)) {
ohci_die(ohci);
return 1;
}
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
} else if (dir == OHCI_TD_DIR_OUT && ret == len) {
/* OUT transfer succeeded */
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
} else {
if (ret > (ssize_t) len) {
trace_usb_ohci_iso_td_data_overrun(ret, len);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAOVERRUN);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
len);
} else if (ret >= 0) {
trace_usb_ohci_iso_td_data_underrun(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAUNDERRUN);
} else {
switch (ret) {
case USB_RET_IOERROR:
case USB_RET_NODEV:
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DEVICENOTRESPONDING);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
case USB_RET_NAK:
case USB_RET_STALL:
trace_usb_ohci_iso_td_nak(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_STALL);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
default:
trace_usb_ohci_iso_td_bad_response(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_UNDEXPETEDPID);
break;
}
}
}
if (relative_frame_number == frame_count) {
/* Last data packet of ISO TD - retire the TD to the Done Queue */
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
}
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
}
return 1;
}
Commit Message:
CWE ID: CWE-835 | static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
int completion)
{
int dir;
size_t len = 0;
const char *str = NULL;
int pid;
int ret;
int i;
USBDevice *dev;
USBEndpoint *ep;
struct ohci_iso_td iso_td;
uint32_t addr;
uint16_t starting_frame;
int16_t relative_frame_number;
int frame_count;
uint32_t start_offset, next_offset, end_offset = 0;
uint32_t start_addr, end_addr;
addr = ed->head & OHCI_DPTR_MASK;
if (ohci_read_iso_td(ohci, addr, &iso_td)) {
trace_usb_ohci_iso_td_read_failed(addr);
ohci_die(ohci);
return 1;
}
starting_frame = OHCI_BM(iso_td.flags, TD_SF);
frame_count = OHCI_BM(iso_td.flags, TD_FC);
relative_frame_number = USUB(ohci->frame_number, starting_frame);
trace_usb_ohci_iso_td_head(
ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
ohci->frame_number, starting_frame,
frame_count, relative_frame_number);
trace_usb_ohci_iso_td_head_offset(
iso_td.offset[0], iso_td.offset[1],
iso_td.offset[2], iso_td.offset[3],
iso_td.offset[4], iso_td.offset[5],
iso_td.offset[6], iso_td.offset[7]);
if (relative_frame_number < 0) {
trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number);
return 1;
} else if (relative_frame_number > frame_count) {
/* ISO TD expired - retire the TD to the Done Queue and continue with
the next ISO TD of the same ED */
trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number,
frame_count);
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
return 1;
}
return 0;
}
dir = OHCI_BM(ed->flags, ED_D);
switch (dir) {
case OHCI_TD_DIR_IN:
str = "in";
pid = USB_TOKEN_IN;
break;
case OHCI_TD_DIR_OUT:
str = "out";
pid = USB_TOKEN_OUT;
break;
case OHCI_TD_DIR_SETUP:
str = "setup";
pid = USB_TOKEN_SETUP;
break;
default:
trace_usb_ohci_iso_td_bad_direction(dir);
return 1;
}
if (!iso_td.bp || !iso_td.be) {
trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be);
return 1;
}
start_offset = iso_td.offset[relative_frame_number];
next_offset = iso_td.offset[relative_frame_number + 1];
if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||
((relative_frame_number < frame_count) &&
!(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset);
return 1;
}
if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset);
return 1;
}
if ((start_offset & 0x1000) == 0) {
start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
} else {
start_addr = (iso_td.be & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
}
if (relative_frame_number < frame_count) {
end_offset = next_offset - 1;
if ((end_offset & 0x1000) == 0) {
end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
} else {
end_addr = (iso_td.be & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
}
} else {
/* Last packet in the ISO TD */
end_addr = iso_td.be;
}
if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
- (start_addr & OHCI_OFFSET_MASK);
} else {
len = end_addr - start_addr + 1;
}
if (len && dir != OHCI_TD_DIR_IN) {
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
DMA_DIRECTION_TO_DEVICE)) {
ohci_die(ohci);
return 1;
}
}
if (!completion) {
bool int_req = relative_frame_number == frame_count &&
OHCI_BM(iso_td.flags, TD_DI) == 0;
dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
usb_handle_packet(dev, &ohci->usb_packet);
if (ohci->usb_packet.status == USB_RET_ASYNC) {
usb_device_flush_ep_queue(dev, ep);
return 1;
}
}
if (ohci->usb_packet.status == USB_RET_SUCCESS) {
ret = ohci->usb_packet.actual_length;
} else {
ret = ohci->usb_packet.status;
}
trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
str, len, ret);
/* Writeback */
if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
/* IN transfer succeeded */
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
DMA_DIRECTION_FROM_DEVICE)) {
ohci_die(ohci);
return 1;
}
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
} else if (dir == OHCI_TD_DIR_OUT && ret == len) {
/* OUT transfer succeeded */
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
} else {
if (ret > (ssize_t) len) {
trace_usb_ohci_iso_td_data_overrun(ret, len);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAOVERRUN);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
len);
} else if (ret >= 0) {
trace_usb_ohci_iso_td_data_underrun(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAUNDERRUN);
} else {
switch (ret) {
case USB_RET_IOERROR:
case USB_RET_NODEV:
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DEVICENOTRESPONDING);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
case USB_RET_NAK:
case USB_RET_STALL:
trace_usb_ohci_iso_td_nak(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_STALL);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
default:
trace_usb_ohci_iso_td_bad_response(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_UNDEXPETEDPID);
break;
}
}
}
if (relative_frame_number == frame_count) {
/* Last data packet of ISO TD - retire the TD to the Done Queue */
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
}
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
}
return 1;
}
| 164,798 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dccp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr;
struct inet_connection_sock *icsk = inet_csk(sk);
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo & IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* DCCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &dccp_ipv6_mapped;
sk->sk_backlog_rcv = dccp_v4_do_rcv;
err = dccp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &dccp_ipv6_af_ops;
sk->sk_backlog_rcv = dccp_v6_do_rcv;
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_DCCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
final_p = fl6_update_dst(&fl6, np->opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (saddr == NULL) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
icsk->icsk_ext_hdr_len = 0;
if (np->opt != NULL)
icsk->icsk_ext_hdr_len = (np->opt->opt_flen +
np->opt->opt_nflen);
inet->inet_dport = usin->sin6_port;
dccp_set_state(sk, DCCP_REQUESTING);
err = inet6_hash_connect(&dccp_death_row, sk);
if (err)
goto late_failure;
dp->dccps_iss = secure_dccpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = dccp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
dccp_set_state(sk, DCCP_CLOSED);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int dccp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr;
struct inet_connection_sock *icsk = inet_csk(sk);
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct ipv6_txoptions *opt;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo & IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* DCCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &dccp_ipv6_mapped;
sk->sk_backlog_rcv = dccp_v4_do_rcv;
err = dccp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &dccp_ipv6_af_ops;
sk->sk_backlog_rcv = dccp_v6_do_rcv;
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_DCCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
opt = rcu_dereference_protected(np->opt, sock_owned_by_user(sk));
final_p = fl6_update_dst(&fl6, opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (saddr == NULL) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
icsk->icsk_ext_hdr_len = 0;
if (opt)
icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen;
inet->inet_dport = usin->sin6_port;
dccp_set_state(sk, DCCP_REQUESTING);
err = inet6_hash_connect(&dccp_death_row, sk);
if (err)
goto late_failure;
dp->dccps_iss = secure_dccpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = dccp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
dccp_set_state(sk, DCCP_CLOSED);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
}
| 167,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit LogoDelegateImpl(
std::unique_ptr<image_fetcher::ImageDecoder> image_decoder)
: image_decoder_(std::move(image_decoder)) {}
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 | explicit LogoDelegateImpl(
| 171,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask,
UINT8 app_id)
{
UINT32 i;
btif_hh_device_t *p_dev = NULL;
if (dev_handle == BTA_HH_INVALID_HANDLE) {
APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...",
__FUNCTION__, dev_handle);
return;
}
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
p_dev = &btif_hh_cb.devices[i];
if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
p_dev->dev_handle == dev_handle) {
APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
"dev_status = %d",__FUNCTION__,
p_dev->dev_status);
APPL_TRACE_WARNING("%s: bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__,
p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2],
p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]);
APPL_TRACE_WARNING("%s: attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d",
__FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
if(p_dev->fd<0) {
p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
}
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
break;
}
p_dev = NULL;
}
if (p_dev == NULL) {
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
p_dev = &btif_hh_cb.devices[i];
p_dev->dev_handle = dev_handle;
p_dev->attr_mask = attr_mask;
p_dev->sub_class = sub_class;
p_dev->app_id = app_id;
p_dev->local_vup = FALSE;
btif_hh_cb.device_num++;
p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else{
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
}
break;
}
}
}
if (p_dev == NULL) {
APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__);
return;
}
p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask,
UINT8 app_id)
{
UINT32 i;
btif_hh_device_t *p_dev = NULL;
if (dev_handle == BTA_HH_INVALID_HANDLE) {
APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...",
__FUNCTION__, dev_handle);
return;
}
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
p_dev = &btif_hh_cb.devices[i];
if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
p_dev->dev_handle == dev_handle) {
APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
"dev_status = %d",__FUNCTION__,
p_dev->dev_status);
APPL_TRACE_WARNING("%s: bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__,
p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2],
p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]);
APPL_TRACE_WARNING("%s: attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d",
__FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
if(p_dev->fd<0) {
p_dev->fd = TEMP_FAILURE_RETRY(open(dev_path, O_RDWR | O_CLOEXEC));
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
}
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
break;
}
p_dev = NULL;
}
if (p_dev == NULL) {
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
p_dev = &btif_hh_cb.devices[i];
p_dev->dev_handle = dev_handle;
p_dev->attr_mask = attr_mask;
p_dev->sub_class = sub_class;
p_dev->app_id = app_id;
p_dev->local_vup = FALSE;
btif_hh_cb.device_num++;
p_dev->fd = TEMP_FAILURE_RETRY(open(dev_path, O_RDWR | O_CLOEXEC));
if (p_dev->fd < 0){
APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
__FUNCTION__,strerror(errno));
return;
}else{
APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
p_dev->hh_keep_polling = 1;
p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
}
break;
}
}
}
if (p_dev == NULL) {
APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__);
return;
}
p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status);
}
| 173,430 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaInterfaceProxy::OnConnectionError() {
DVLOG(1) << __FUNCTION__;
DCHECK(thread_checker_.CalledOnValidThread());
interface_factory_ptr_.reset();
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
CWE ID: CWE-119 | void MediaInterfaceProxy::OnConnectionError() {
media::mojom::InterfaceFactory* MediaInterfaceProxy::GetCdmInterfaceFactory() {
DVLOG(1) << __FUNCTION__;
DCHECK(thread_checker_.CalledOnValidThread());
#if !BUILDFLAG(ENABLE_STANDALONE_CDM_SERVICE)
return GetMediaInterfaceFactory();
#else
if (!cdm_interface_factory_ptr_)
ConnectToCdmService();
DCHECK(cdm_interface_factory_ptr_);
return cdm_interface_factory_ptr_.get();
#endif
}
void MediaInterfaceProxy::OnMediaServiceConnectionError() {
DVLOG(1) << __FUNCTION__;
DCHECK(thread_checker_.CalledOnValidThread());
interface_factory_ptr_.reset();
}
| 171,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,
int c0, int r1, int c1)
{
int i;
if (mat0->data_) {
if (!(mat0->flags_ & JAS_MATRIX_REF)) {
jas_free(mat0->data_);
}
mat0->data_ = 0;
mat0->datasize_ = 0;
}
if (mat0->rows_) {
jas_free(mat0->rows_);
mat0->rows_ = 0;
}
mat0->flags_ |= JAS_MATRIX_REF;
mat0->numrows_ = r1 - r0 + 1;
mat0->numcols_ = c1 - c0 + 1;
mat0->maxrows_ = mat0->numrows_;
if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {
/*
There is no way to indicate failure to the caller.
So, we have no choice but to abort.
Ideally, this function should have a non-void return type.
In practice, a non-void return type probably would not help
much anyways as the caller would just have to terminate anyways.
*/
abort();
}
for (i = 0; i < mat0->numrows_; ++i) {
mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
}
mat0->xstart_ = mat1->xstart_ + c0;
mat0->ystart_ = mat1->ystart_ + r0;
mat0->xend_ = mat0->xstart_ + mat0->numcols_;
mat0->yend_ = mat0->ystart_ + mat0->numrows_;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,
void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1,
jas_matind_t r0, jas_matind_t c0, jas_matind_t r1, jas_matind_t c1)
{
jas_matind_t i;
if (mat0->data_) {
if (!(mat0->flags_ & JAS_MATRIX_REF)) {
jas_free(mat0->data_);
}
mat0->data_ = 0;
mat0->datasize_ = 0;
}
if (mat0->rows_) {
jas_free(mat0->rows_);
mat0->rows_ = 0;
}
mat0->flags_ |= JAS_MATRIX_REF;
mat0->numrows_ = r1 - r0 + 1;
mat0->numcols_ = c1 - c0 + 1;
mat0->maxrows_ = mat0->numrows_;
if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {
/*
There is no way to indicate failure to the caller.
So, we have no choice but to abort.
Ideally, this function should have a non-void return type.
In practice, a non-void return type probably would not help
much anyways as the caller would just have to terminate anyways.
*/
abort();
}
for (i = 0; i < mat0->numrows_; ++i) {
mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
}
mat0->xstart_ = mat1->xstart_ + c0;
mat0->ystart_ = mat1->ystart_ + r0;
mat0->xend_ = mat0->xstart_ + mat0->numcols_;
mat0->yend_ = mat0->ystart_ + mat0->numrows_;
}
| 168,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
Commit Message: issue #53: error out on zero sample rate
CWE ID: CWE-835 | int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
if (!config->sample_rate) {
strcpy (wpc->error_message, "sample rate cannot be zero!");
return FALSE;
}
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
| 168,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
Commit Message: set_interface_var() doesn't check interface name and blindly does
fopen(path "/" ifname, "w") on it. As "ifname" is an untrusted input, it
should be checked for ".." and/or "/" in it. Otherwise, an infected
unprivileged daemon may overwrite contents of file named "mtu",
"hoplimit", etc. in arbitrary location with arbitrary 32-bit value in
decimal representation ("%d"). If an attacker has a local account or
may create arbitrary symlinks with these names in any location (e.g.
/tmp), any file may be overwritten with a decimal value.
CWE ID: CWE-22 | set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
/* No path traversal */
if (strstr(name, "..") || strchr(name, '/'))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
| 166,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line,
const FilePath& exposed_dir) {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
content::ProcessType type;
std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
if (type_str == switches::kRendererProcess) {
type = content::PROCESS_TYPE_RENDERER;
} else if (type_str == switches::kPluginProcess) {
type = content::PROCESS_TYPE_PLUGIN;
} else if (type_str == switches::kWorkerProcess) {
type = content::PROCESS_TYPE_WORKER;
} else if (type_str == switches::kNaClLoaderProcess) {
type = content::PROCESS_TYPE_NACL_LOADER;
} else if (type_str == switches::kUtilityProcess) {
type = content::PROCESS_TYPE_UTILITY;
} else if (type_str == switches::kNaClBrokerProcess) {
type = content::PROCESS_TYPE_NACL_BROKER;
} else if (type_str == switches::kGpuProcess) {
type = content::PROCESS_TYPE_GPU;
} else if (type_str == switches::kPpapiPluginProcess) {
type = content::PROCESS_TYPE_PPAPI_PLUGIN;
} else if (type_str == switches::kPpapiBrokerProcess) {
type = content::PROCESS_TYPE_PPAPI_BROKER;
} else {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
bool in_sandbox =
(type != content::PROCESS_TYPE_NACL_BROKER) &&
(type != content::PROCESS_TYPE_PLUGIN) &&
(type != content::PROCESS_TYPE_PPAPI_BROKER);
if ((type == content::PROCESS_TYPE_GPU) &&
(cmd_line->HasSwitch(switches::kDisableGpuSandbox))) {
in_sandbox = false;
DVLOG(1) << "GPU sandbox is disabled";
}
if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
cmd_line->HasSwitch(switches::kNoSandbox)) {
in_sandbox = false;
}
#if !defined (GOOGLE_CHROME_BUILD)
if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) {
in_sandbox = false;
}
#endif
if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) &&
!browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
browser_command_line.HasSwitch(switches::kInProcessWebGL)) {
in_sandbox = false;
}
if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
if (!cmd_line->HasSwitch(switches::kChromeFrame)) {
cmd_line->AppendSwitch(switches::kChromeFrame);
}
}
bool child_needs_help =
DebugFlags::ProcessDebugFlags(cmd_line, type, in_sandbox);
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type));
sandbox::ResultCode result;
base::win::ScopedProcessInformation target;
sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (type == content::PROCESS_TYPE_PLUGIN &&
!browser_command_line.HasSwitch(switches::kNoSandbox) &&
content::GetContentClient()->SandboxPlugin(cmd_line, policy)) {
in_sandbox = true;
}
#endif
if (!in_sandbox) {
policy->Release();
base::ProcessHandle process = 0;
base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
return process;
}
if (type == content::PROCESS_TYPE_PLUGIN) {
AddGenericDllEvictionPolicy(policy);
AddPluginDllEvictionPolicy(policy);
} else if (type == content::PROCESS_TYPE_GPU) {
if (!AddPolicyForGPU(cmd_line, policy))
return 0;
} else {
if (!AddPolicyForRenderer(policy))
return 0;
if (type == content::PROCESS_TYPE_RENDERER ||
type == content::PROCESS_TYPE_WORKER) {
AddBaseHandleClosePolicy(policy);
} else if (type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
if (!AddPolicyForPepperPlugin(policy))
return 0;
}
if (type_str != switches::kRendererProcess) {
cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
}
}
if (!exposed_dir.empty()) {
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_dir.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
FilePath exposed_files = exposed_dir.AppendASCII("*");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_files.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
}
if (!AddGenericPolicy(policy)) {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
result = g_broker_services->SpawnTarget(
cmd_line->GetProgram().value().c_str(),
cmd_line->GetCommandLineString().c_str(),
policy, target.Receive());
policy->Release();
TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
if (sandbox::SBOX_ALL_OK != result) {
DLOG(ERROR) << "Failed to launch process. Error: " << result;
return 0;
}
if (type == content::PROCESS_TYPE_NACL_LOADER &&
(base::win::OSInfo::GetInstance()->wow64_status() ==
base::win::OSInfo::WOW64_DISABLED)) {
const SIZE_T kOneGigabyte = 1 << 30;
void* nacl_mem = VirtualAllocEx(target.process_handle(),
NULL,
kOneGigabyte,
MEM_RESERVE,
PAGE_NOACCESS);
if (!nacl_mem) {
DLOG(WARNING) << "Failed to reserve address space for Native Client";
}
}
ResumeThread(target.thread_handle());
if (child_needs_help)
base::debug::SpawnDebuggerOnProcess(target.process_id());
return target.TakeProcessHandle();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line,
const FilePath& exposed_dir) {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
content::ProcessType type;
std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
if (type_str == switches::kRendererProcess) {
type = content::PROCESS_TYPE_RENDERER;
} else if (type_str == switches::kPluginProcess) {
type = content::PROCESS_TYPE_PLUGIN;
} else if (type_str == switches::kWorkerProcess) {
type = content::PROCESS_TYPE_WORKER;
} else if (type_str == switches::kNaClLoaderProcess) {
type = content::PROCESS_TYPE_NACL_LOADER;
} else if (type_str == switches::kUtilityProcess) {
type = content::PROCESS_TYPE_UTILITY;
} else if (type_str == switches::kNaClBrokerProcess) {
type = content::PROCESS_TYPE_NACL_BROKER;
} else if (type_str == switches::kGpuProcess) {
type = content::PROCESS_TYPE_GPU;
} else if (type_str == switches::kPpapiPluginProcess) {
type = content::PROCESS_TYPE_PPAPI_PLUGIN;
} else if (type_str == switches::kPpapiBrokerProcess) {
type = content::PROCESS_TYPE_PPAPI_BROKER;
} else {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
bool in_sandbox =
(type != content::PROCESS_TYPE_NACL_BROKER) &&
(type != content::PROCESS_TYPE_PLUGIN) &&
(type != content::PROCESS_TYPE_PPAPI_BROKER);
if ((type == content::PROCESS_TYPE_GPU) &&
(cmd_line->HasSwitch(switches::kDisableGpuSandbox))) {
in_sandbox = false;
DVLOG(1) << "GPU sandbox is disabled";
}
if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
cmd_line->HasSwitch(switches::kNoSandbox)) {
in_sandbox = false;
}
#if !defined (GOOGLE_CHROME_BUILD)
if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) {
in_sandbox = false;
}
#endif
if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) &&
!browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
browser_command_line.HasSwitch(switches::kInProcessWebGL)) {
in_sandbox = false;
}
if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
if (!cmd_line->HasSwitch(switches::kChromeFrame)) {
cmd_line->AppendSwitch(switches::kChromeFrame);
}
}
bool child_needs_help =
DebugFlags::ProcessDebugFlags(cmd_line, type, in_sandbox);
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type));
sandbox::ResultCode result;
base::win::ScopedProcessInformation target;
sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (type == content::PROCESS_TYPE_PLUGIN &&
!browser_command_line.HasSwitch(switches::kNoSandbox) &&
content::GetContentClient()->SandboxPlugin(cmd_line, policy)) {
in_sandbox = true;
}
#endif
if (!in_sandbox) {
policy->Release();
base::ProcessHandle process = 0;
base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
g_broker_services->AddTargetPeer(process);
return process;
}
if (type == content::PROCESS_TYPE_PLUGIN) {
AddGenericDllEvictionPolicy(policy);
AddPluginDllEvictionPolicy(policy);
} else if (type == content::PROCESS_TYPE_GPU) {
if (!AddPolicyForGPU(cmd_line, policy))
return 0;
} else {
if (!AddPolicyForRenderer(policy))
return 0;
if (type == content::PROCESS_TYPE_RENDERER ||
type == content::PROCESS_TYPE_WORKER) {
AddBaseHandleClosePolicy(policy);
} else if (type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
if (!AddPolicyForPepperPlugin(policy))
return 0;
}
if (type_str != switches::kRendererProcess) {
cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
}
}
if (!exposed_dir.empty()) {
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_dir.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
FilePath exposed_files = exposed_dir.AppendASCII("*");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_files.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
}
if (!AddGenericPolicy(policy)) {
NOTREACHED();
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
result = g_broker_services->SpawnTarget(
cmd_line->GetProgram().value().c_str(),
cmd_line->GetCommandLineString().c_str(),
policy, target.Receive());
policy->Release();
TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
if (sandbox::SBOX_ALL_OK != result) {
DLOG(ERROR) << "Failed to launch process. Error: " << result;
return 0;
}
if (type == content::PROCESS_TYPE_NACL_LOADER &&
(base::win::OSInfo::GetInstance()->wow64_status() ==
base::win::OSInfo::WOW64_DISABLED)) {
const SIZE_T kOneGigabyte = 1 << 30;
void* nacl_mem = VirtualAllocEx(target.process_handle(),
NULL,
kOneGigabyte,
MEM_RESERVE,
PAGE_NOACCESS);
if (!nacl_mem) {
DLOG(WARNING) << "Failed to reserve address space for Native Client";
}
}
ResumeThread(target.thread_handle());
if (child_needs_help)
base::debug::SpawnDebuggerOnProcess(target.process_id());
return target.TakeProcessHandle();
}
| 170,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Browser::TabDetachedAtImpl(TabContents* contents, int index,
DetachType type) {
if (type == DETACH_TYPE_DETACH) {
if (contents == chrome::GetActiveTabContents(this)) {
LocationBar* location_bar = window()->GetLocationBar();
if (location_bar)
location_bar->SaveStateToContents(contents->web_contents());
}
if (!tab_strip_model_->closing_all())
SyncHistoryWithTabs(0);
}
SetAsDelegate(contents->web_contents(), NULL);
RemoveScheduledUpdatesFor(contents->web_contents());
if (find_bar_controller_.get() && index == active_index()) {
find_bar_controller_->ChangeWebContents(NULL);
}
search_delegate_->OnTabDetached(contents->web_contents());
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents->web_contents()));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void Browser::TabDetachedAtImpl(TabContents* contents, int index,
void Browser::TabDetachedAtImpl(content::WebContents* contents,
int index,
DetachType type) {
if (type == DETACH_TYPE_DETACH) {
if (contents == chrome::GetActiveWebContents(this)) {
LocationBar* location_bar = window()->GetLocationBar();
if (location_bar)
location_bar->SaveStateToContents(contents);
}
if (!tab_strip_model_->closing_all())
SyncHistoryWithTabs(0);
}
SetAsDelegate(contents, NULL);
RemoveScheduledUpdatesFor(contents);
if (find_bar_controller_.get() && index == active_index()) {
find_bar_controller_->ChangeWebContents(NULL);
}
search_delegate_->OnTabDetached(contents);
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents));
}
| 171,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event = stuff->send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
Commit Message:
CWE ID: CWE-20 | XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
send_event = stuff->send_event;
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
| 165,436 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
spl_filesystem_iterator *iterator;
spl_filesystem_object *dir_object;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
iterator = spl_filesystem_object_to_iterator(dir_object);
/* initialize iterator if it wasn't gotten before */
if (iterator->intern.data == NULL) {
iterator->intern.data = object;
iterator->intern.funcs = &spl_filesystem_dir_it_funcs;
/* ->current must be initialized; rewind doesn't set it and valid
* doesn't check whether it's set */
iterator->current = object;
}
zval_add_ref(&object);
return (zend_object_iterator*)iterator;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
spl_filesystem_iterator *iterator;
spl_filesystem_object *dir_object;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
iterator = spl_filesystem_object_to_iterator(dir_object);
/* initialize iterator if it wasn't gotten before */
if (iterator->intern.data == NULL) {
iterator->intern.data = object;
iterator->intern.funcs = &spl_filesystem_dir_it_funcs;
/* ->current must be initialized; rewind doesn't set it and valid
* doesn't check whether it's set */
iterator->current = object;
}
zval_add_ref(&object);
return (zend_object_iterator*)iterator;
}
| 167,069 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) {
Mutex::Autolock autoLock(mLock);
if (offset >= mCachedOffset
&& offset + size <= mCachedOffset + mCachedSize) {
memcpy(data, &mCache[offset - mCachedOffset], size);
return size;
}
return mSource->readAt(offset, data, size);
}
Commit Message: Add AUtils::isInRange, and use it to detect malformed MPEG4 nal sizes
Bug: 19641538
Change-Id: I5aae3f100846c125decc61eec7cd6563e3f33777
CWE ID: CWE-119 | ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) {
Mutex::Autolock autoLock(mLock);
if (isInRange(mCachedOffset, mCachedSize, offset, size)) {
memcpy(data, &mCache[offset - mCachedOffset], size);
return size;
}
return mSource->readAt(offset, data, size);
}
| 173,364 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int BN_hex2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, h, m, i, j, k, c;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
a++;
}
for (i = 0; isxdigit((unsigned char)a[i]); i++) ;
num = i + neg;
if (bn == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
Commit Message:
CWE ID: | int BN_hex2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, h, m, i, j, k, c;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
a++;
}
for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++)
continue;
if (i > INT_MAX/4)
goto err;
num = i + neg;
if (bn == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
| 165,250 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
if (j >= length) return -1;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
Commit Message: evdns: name_parse(): fix remote stack overread
@asn-the-goblin-slayer:
"the name_parse() function in libevent's DNS code is vulnerable to a buffer overread.
971 if (cp != name_out) {
972 if (cp + 1 >= end) return -1;
973 *cp++ = '.';
974 }
975 if (cp + label_len >= end) return -1;
976 memcpy(cp, packet + j, label_len);
977 cp += label_len;
978 j += label_len;
No check is made against length before the memcpy occurs.
This was found through the Tor bug bounty program and the discovery should be credited to 'Guido Vranken'."
Reproducer for gdb (https://gist.github.com/azat/e4fcf540e9b89ab86d02):
set $PROT_NONE=0x0
set $PROT_READ=0x1
set $PROT_WRITE=0x2
set $MAP_ANONYMOUS=0x20
set $MAP_SHARED=0x01
set $MAP_FIXED=0x10
set $MAP_32BIT=0x40
start
set $length=202
# overread
set $length=2
# allocate with mmap to have a seg fault on page boundary
set $l=(1<<20)*2
p mmap(0, $l, $PROT_READ|$PROT_WRITE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_32BIT, -1, 0)
set $packet=(char *)$1+$l-$length
# hack the packet
set $packet[0]=63
set $packet[1]='/'
p malloc(sizeof(int))
set $idx=(int *)$2
set $idx[0]=0
set $name_out_len=202
p malloc($name_out_len)
set $name_out=$3
# have WRITE only mapping to fail on read
set $end=$1+$l
p (void *)mmap($end, 1<<12, $PROT_NONE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_FIXED|$MAP_32BIT, -1, 0)
set $m=$4
p name_parse($packet, $length, $idx, $name_out, $name_out_len)
x/2s (char *)$name_out
Before this patch:
$ gdb -ex 'source gdb' dns-example
$1 = 1073741824
$2 = (void *) 0x633010
$3 = (void *) 0x633030
$4 = (void *) 0x40200000
Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:33
After this patch:
$ gdb -ex 'source gdb' dns-example
$1 = 1073741824
$2 = (void *) 0x633010
$3 = (void *) 0x633030
$4 = (void *) 0x40200000
$5 = -1
0x633030: "/"
0x633032: ""
(gdb) p $m
$6 = (void *) 0x40200000
(gdb) p $1
$7 = 1073741824
(gdb) p/x $1
$8 = 0x40000000
(gdb) quit
P.S. plus drop one condition duplicate.
Fixes: #317
CWE ID: CWE-125 | name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
if (j + label_len > length) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
| 168,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. 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: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Chapters::Display::Parse(
| 174,403 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TabContentsContainerGtk::DetachTab(TabContents* tab) {
gfx::NativeView widget = tab->web_contents()->GetNativeView();
if (widget) {
GtkWidget* parent = gtk_widget_get_parent(widget);
if (parent) {
DCHECK_EQ(parent, expanded_);
gtk_container_remove(GTK_CONTAINER(expanded_), widget);
}
}
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void TabContentsContainerGtk::DetachTab(TabContents* tab) {
void TabContentsContainerGtk::DetachTab(WebContents* tab) {
gfx::NativeView widget = tab->GetNativeView();
if (widget) {
GtkWidget* parent = gtk_widget_get_parent(widget);
if (parent) {
DCHECK_EQ(parent, expanded_);
gtk_container_remove(GTK_CONTAINER(expanded_), widget);
}
}
}
| 171,515 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_EC
unsigned char *encodedPoint = NULL;
int encoded_pt_len = 0;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
goto err;
}
/* Generate encoding of client key */
encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
if (encoded_pt_len == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
goto err;
}
EVP_PKEY_free(ckey);
ckey = NULL;
*len = encoded_pt_len;
/* length of encoded point */
**p = *len;
*p += 1;
/* copy the point */
memcpy(*p, encodedPoint, *len);
/* increment len to account for length field */
*len += 1;
OPENSSL_free(encodedPoint);
return 1;
err:
EVP_PKEY_free(ckey);
return 0;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
Commit Message: Fix missing NULL checks in CKE processing
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-476 | static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_EC
unsigned char *encodedPoint = NULL;
int encoded_pt_len = 0;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ckey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
goto err;
}
if (ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
goto err;
}
/* Generate encoding of client key */
encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
if (encoded_pt_len == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
goto err;
}
EVP_PKEY_free(ckey);
ckey = NULL;
*len = encoded_pt_len;
/* length of encoded point */
**p = *len;
*p += 1;
/* copy the point */
memcpy(*p, encodedPoint, *len);
/* increment len to account for length field */
*len += 1;
OPENSSL_free(encodedPoint);
return 1;
err:
EVP_PKEY_free(ckey);
return 0;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
| 168,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
s->nextfunction = qemu_get_byte(f);
s->precision = qemu_get_byte(f);
s->nextprecision = qemu_get_byte(f);
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
Commit Message:
CWE ID: CWE-119 | static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
if (s->function < 0 || s->function >= ARRAY_SIZE(mode_regs)) {
return -EINVAL;
}
s->nextfunction = qemu_get_byte(f);
if (s->nextfunction < 0 || s->nextfunction >= ARRAY_SIZE(mode_regs)) {
return -EINVAL;
}
s->precision = qemu_get_byte(f);
if (s->precision < 0 || s->precision >= ARRAY_SIZE(resolution)) {
return -EINVAL;
}
s->nextprecision = qemu_get_byte(f);
if (s->nextprecision < 0 || s->nextprecision >= ARRAY_SIZE(resolution)) {
return -EINVAL;
}
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
| 165,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
{
if (!box().isMarquee()) {
if (m_scrollDimensionsDirty)
computeScrollDimensions();
}
if (scrollOffset() == toIntSize(newScrollOffset))
return;
setScrollOffset(toIntSize(newScrollOffset));
LocalFrame* frame = box().frame();
ASSERT(frame);
RefPtr<FrameView> frameView = box().frameView();
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScrollLayer", "data", InspectorScrollLayerEvent::data(&box()));
InspectorInstrumentation::willScrollLayer(&box());
const RenderLayerModelObject* paintInvalidationContainer = box().containerForPaintInvalidation();
if (!frameView->isInPerformLayout()) {
layer()->clipper().clearClipRectsIncludingDescendants();
box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(paintInvalidationContainer));
frameView->updateAnnotatedRegions();
frameView->updateWidgetPositions();
RELEASE_ASSERT(frameView->renderView());
updateCompositingLayersAfterScroll();
}
frame->selection().setCaretRectNeedsUpdate();
FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->renderer()->previousPaintInvalidationRect());
quadForFakeMouseMoveEvent = paintInvalidationContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
bool requiresPaintInvalidation = true;
if (!box().isMarquee() && box().view()->compositor()->inCompositingMode()) {
DisableCompositingQueryAsserts disabler;
bool onlyScrolledCompositedLayers = scrollsOverflow()
&& !layer()->hasVisibleNonLayerContent()
&& !layer()->hasNonCompositedChild()
&& !layer()->hasBlockSelectionGapBounds()
&& box().style()->backgroundLayers().attachment() != LocalBackgroundAttachment;
if (usesCompositedScrolling() || onlyScrolledCompositedLayers)
requiresPaintInvalidation = false;
}
if (requiresPaintInvalidation) {
if (box().frameView()->isInPerformLayout())
box().setShouldDoFullPaintInvalidation(true);
else
box().invalidatePaintUsingContainer(paintInvalidationContainer, layer()->renderer()->previousPaintInvalidationRect(), InvalidationScroll);
}
if (box().node())
box().node()->document().enqueueScrollEventForNode(box().node());
if (AXObjectCache* cache = box().document().existingAXObjectCache())
cache->handleScrollPositionChanged(&box());
InspectorInstrumentation::didScrollLayer(&box());
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
[email protected]
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416 | void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
{
if (!box().isMarquee()) {
if (m_scrollDimensionsDirty)
computeScrollDimensions();
}
if (scrollOffset() == toIntSize(newScrollOffset))
return;
setScrollOffset(toIntSize(newScrollOffset));
LocalFrame* frame = box().frame();
ASSERT(frame);
RefPtr<FrameView> frameView = box().frameView();
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScrollLayer", "data", InspectorScrollLayerEvent::data(&box()));
InspectorInstrumentation::willScrollLayer(&box());
const RenderLayerModelObject* paintInvalidationContainer = box().containerForPaintInvalidation();
if (!frameView->isInPerformLayout()) {
layer()->clipper().clearClipRectsIncludingDescendants();
box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(paintInvalidationContainer));
frameView->updateAnnotatedRegions();
frameView->setNeedsUpdateWidgetPositions();
updateCompositingLayersAfterScroll();
}
frame->selection().setCaretRectNeedsUpdate();
FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->renderer()->previousPaintInvalidationRect());
quadForFakeMouseMoveEvent = paintInvalidationContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
bool requiresPaintInvalidation = true;
if (!box().isMarquee() && box().view()->compositor()->inCompositingMode()) {
DisableCompositingQueryAsserts disabler;
bool onlyScrolledCompositedLayers = scrollsOverflow()
&& !layer()->hasVisibleNonLayerContent()
&& !layer()->hasNonCompositedChild()
&& !layer()->hasBlockSelectionGapBounds()
&& box().style()->backgroundLayers().attachment() != LocalBackgroundAttachment;
if (usesCompositedScrolling() || onlyScrolledCompositedLayers)
requiresPaintInvalidation = false;
}
if (requiresPaintInvalidation) {
if (box().frameView()->isInPerformLayout())
box().setShouldDoFullPaintInvalidation(true);
else
box().invalidatePaintUsingContainer(paintInvalidationContainer, layer()->renderer()->previousPaintInvalidationRect(), InvalidationScroll);
}
if (box().node())
box().node()->document().enqueueScrollEventForNode(box().node());
if (AXObjectCache* cache = box().document().existingAXObjectCache())
cache->handleScrollPositionChanged(&box());
InspectorInstrumentation::didScrollLayer(&box());
}
| 171,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef _WIN32_WCE
{
wchar_t time_buf[29];
wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer,
29, NULL, NULL);
}
#else
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
#endif /* _WIN32_WCE */
return ((png_charp)png_ptr->time_buffer);
}
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_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef _WIN32_WCE
{
wchar_t time_buf[29];
wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer,
29, NULL, NULL);
}
#else
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1U) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
#endif /* _WIN32_WCE */
return ((png_charp)png_ptr->time_buffer);
}
| 172,161 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileReaderLoader::FileReaderLoader(ReadType read_type,
FileReaderLoaderClient* client)
: read_type_(read_type),
client_(client),
handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
binding_(this) {}
Commit Message: Fix use-after-free in FileReaderLoader.
Anything that calls out to client_ can cause FileReaderLoader to be
destroyed, so make sure to check for that situation.
Bug: 835639
Change-Id: I57533d41b7118c06da17abec28bbf301e1f50646
Reviewed-on: https://chromium-review.googlesource.com/1024450
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552807}
CWE ID: CWE-416 | FileReaderLoader::FileReaderLoader(ReadType read_type,
FileReaderLoaderClient* client)
: read_type_(read_type),
client_(client),
handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
| 173,217 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline key_ref_t __key_update(key_ref_t key_ref,
struct key_preparsed_payload *prep)
{
struct key *key = key_ref_to_ptr(key_ref);
int ret;
/* need write permission on the key to update it */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
goto error;
ret = -EEXIST;
if (!key->type->update)
goto error;
down_write(&key->sem);
ret = key->type->update(key, prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
if (ret < 0)
goto error;
out:
return key_ref;
error:
key_put(key);
key_ref = ERR_PTR(ret);
goto out;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | static inline key_ref_t __key_update(key_ref_t key_ref,
struct key_preparsed_payload *prep)
{
struct key *key = key_ref_to_ptr(key_ref);
int ret;
/* need write permission on the key to update it */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
goto error;
ret = -EEXIST;
if (!key->type->update)
goto error;
down_write(&key->sem);
ret = key->type->update(key, prep);
if (ret == 0)
/* Updating a negative key positively instantiates it */
mark_key_instantiated(key, 0);
up_write(&key->sem);
if (ret < 0)
goto error;
out:
return key_ref;
error:
key_put(key);
key_ref = ERR_PTR(ret);
goto out;
}
| 167,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
if (!ND_TTEST(rp->rm_call.cb_proc))
return (0);
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
| 167,903 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SecureProxyChecker::SecureProxyChecker(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: url_loader_factory_(std::move(url_loader_factory)) {}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | SecureProxyChecker::SecureProxyChecker(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
| 172,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode)
{
if (state->state == mode)
return;
/* NB! List reordering - see the reclaim code for why. */
if ((mode & FMODE_WRITE) != (state->state & FMODE_WRITE)) {
if (mode & FMODE_WRITE)
list_move(&state->open_states, &state->owner->so_states);
else
list_move_tail(&state->open_states, &state->owner->so_states);
}
state->state = mode;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode)
nfs4_state_set_mode_locked(struct nfs4_state *state, fmode_t fmode)
{
if (state->state == fmode)
return;
/* NB! List reordering - see the reclaim code for why. */
if ((fmode & FMODE_WRITE) != (state->state & FMODE_WRITE)) {
if (fmode & FMODE_WRITE)
list_move(&state->open_states, &state->owner->so_states);
else
list_move_tail(&state->open_states, &state->owner->so_states);
}
state->state = fmode;
}
| 165,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_one(struct crypto_alg *alg,
struct crypto_user_alg *ualg, struct sk_buff *skb)
{
strlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name));
strlcpy(ualg->cru_driver_name, alg->cra_driver_name,
sizeof(ualg->cru_driver_name));
strlcpy(ualg->cru_module_name, module_name(alg->cra_module),
sizeof(ualg->cru_module_name));
ualg->cru_type = 0;
ualg->cru_mask = 0;
ualg->cru_flags = alg->cra_flags;
ualg->cru_refcnt = refcount_read(&alg->cra_refcnt);
if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))
goto nla_put_failure;
if (alg->cra_flags & CRYPTO_ALG_LARVAL) {
struct crypto_report_larval rl;
strlcpy(rl.type, "larval", sizeof(rl.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,
sizeof(struct crypto_report_larval), &rl))
goto nla_put_failure;
goto out;
}
if (alg->cra_type && alg->cra_type->report) {
if (alg->cra_type->report(skb, alg))
goto nla_put_failure;
goto out;
}
switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {
case CRYPTO_ALG_TYPE_CIPHER:
if (crypto_report_cipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_COMPRESS:
if (crypto_report_comp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_ACOMPRESS:
if (crypto_report_acomp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_AKCIPHER:
if (crypto_report_akcipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_KPP:
if (crypto_report_kpp(skb, alg))
goto nla_put_failure;
break;
}
out:
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_one(struct crypto_alg *alg,
struct crypto_user_alg *ualg, struct sk_buff *skb)
{
strncpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name));
strncpy(ualg->cru_driver_name, alg->cra_driver_name,
sizeof(ualg->cru_driver_name));
strncpy(ualg->cru_module_name, module_name(alg->cra_module),
sizeof(ualg->cru_module_name));
ualg->cru_type = 0;
ualg->cru_mask = 0;
ualg->cru_flags = alg->cra_flags;
ualg->cru_refcnt = refcount_read(&alg->cra_refcnt);
if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))
goto nla_put_failure;
if (alg->cra_flags & CRYPTO_ALG_LARVAL) {
struct crypto_report_larval rl;
strncpy(rl.type, "larval", sizeof(rl.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,
sizeof(struct crypto_report_larval), &rl))
goto nla_put_failure;
goto out;
}
if (alg->cra_type && alg->cra_type->report) {
if (alg->cra_type->report(skb, alg))
goto nla_put_failure;
goto out;
}
switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {
case CRYPTO_ALG_TYPE_CIPHER:
if (crypto_report_cipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_COMPRESS:
if (crypto_report_comp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_ACOMPRESS:
if (crypto_report_acomp(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_AKCIPHER:
if (crypto_report_akcipher(skb, alg))
goto nla_put_failure;
break;
case CRYPTO_ALG_TYPE_KPP:
if (crypto_report_kpp(skb, alg))
goto nla_put_failure;
break;
}
out:
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)
{
int c;
uchar buf[2];
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[0] = c;
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[1] = c;
hdr->magic = buf[0] << 8 | buf[1];
if (hdr->magic != PGX_MAGIC) {
jas_eprintf("invalid PGX signature\n");
goto error;
}
if ((c = pgx_getc(in)) == EOF || !isspace(c)) {
goto error;
}
if (pgx_getbyteorder(in, &hdr->bigendian)) {
jas_eprintf("cannot get byte order\n");
goto error;
}
if (pgx_getsgnd(in, &hdr->sgnd)) {
jas_eprintf("cannot get signedness\n");
goto error;
}
if (pgx_getuint32(in, &hdr->prec)) {
jas_eprintf("cannot get precision\n");
goto error;
}
if (pgx_getuint32(in, &hdr->width)) {
jas_eprintf("cannot get width\n");
goto error;
}
if (pgx_getuint32(in, &hdr->height)) {
jas_eprintf("cannot get height\n");
goto error;
}
return 0;
error:
return -1;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)
{
int c;
jas_uchar buf[2];
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[0] = c;
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
buf[1] = c;
hdr->magic = buf[0] << 8 | buf[1];
if (hdr->magic != PGX_MAGIC) {
jas_eprintf("invalid PGX signature\n");
goto error;
}
if ((c = pgx_getc(in)) == EOF || !isspace(c)) {
goto error;
}
if (pgx_getbyteorder(in, &hdr->bigendian)) {
jas_eprintf("cannot get byte order\n");
goto error;
}
if (pgx_getsgnd(in, &hdr->sgnd)) {
jas_eprintf("cannot get signedness\n");
goto error;
}
if (pgx_getuint32(in, &hdr->prec)) {
jas_eprintf("cannot get precision\n");
goto error;
}
if (pgx_getuint32(in, &hdr->width)) {
jas_eprintf("cannot get width\n");
goto error;
}
if (pgx_getuint32(in, &hdr->height)) {
jas_eprintf("cannot get height\n");
goto error;
}
return 0;
error:
return -1;
}
| 168,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GM2TabStyle::PaintTabBackgroundFill(gfx::Canvas* canvas,
bool active,
bool paint_hover_effect,
SkColor active_color,
SkColor inactive_color,
int fill_id,
int y_inset) const {
const SkPath fill_path =
GetPath(PathType::kFill, canvas->image_scale(), active);
gfx::ScopedCanvas scoped_canvas(canvas);
const float scale = canvas->UndoDeviceScaleFactor();
canvas->ClipPath(fill_path, true);
if (active || !fill_id) {
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(active ? active_color : inactive_color);
canvas->DrawRect(gfx::ScaleToEnclosingRect(tab_->GetLocalBounds(), scale),
flags);
}
if (fill_id) {
gfx::ScopedCanvas scale_scoper(canvas);
canvas->sk_canvas()->scale(scale, scale);
canvas->TileImageInt(*tab_->GetThemeProvider()->GetImageSkiaNamed(fill_id),
tab_->GetMirroredX() + tab_->background_offset(), 0, 0,
y_inset, tab_->width(), tab_->height());
}
if (paint_hover_effect) {
SkPoint hover_location(gfx::PointToSkPoint(hover_controller_->location()));
hover_location.scale(SkFloatToScalar(scale));
const SkScalar kMinHoverRadius = 16;
const SkScalar radius =
std::max(SkFloatToScalar(tab_->width() / 4.f), kMinHoverRadius);
DrawHighlight(canvas, hover_location, radius * scale,
SkColorSetA(active_color, hover_controller_->GetAlpha()));
}
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | void GM2TabStyle::PaintTabBackgroundFill(gfx::Canvas* canvas,
TabState active_state,
bool paint_hover_effect,
int fill_id,
int y_inset) const {
const SkPath fill_path = GetPath(PathType::kFill, canvas->image_scale(),
active_state == TAB_ACTIVE);
gfx::ScopedCanvas scoped_canvas(canvas);
const float scale = canvas->UndoDeviceScaleFactor();
canvas->ClipPath(fill_path, true);
if (ShouldPaintTabBackgroundColor(active_state, fill_id)) {
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(GetTabBackgroundColor(active_state));
canvas->DrawRect(gfx::ScaleToEnclosingRect(tab_->GetLocalBounds(), scale),
flags);
}
if (fill_id) {
gfx::ScopedCanvas scale_scoper(canvas);
canvas->sk_canvas()->scale(scale, scale);
canvas->TileImageInt(*tab_->GetThemeProvider()->GetImageSkiaNamed(fill_id),
tab_->GetMirroredX() + tab_->background_offset(), 0, 0,
y_inset, tab_->width(), tab_->height());
}
if (paint_hover_effect) {
SkPoint hover_location(gfx::PointToSkPoint(hover_controller_->location()));
hover_location.scale(SkFloatToScalar(scale));
const SkScalar kMinHoverRadius = 16;
const SkScalar radius =
std::max(SkFloatToScalar(tab_->width() / 4.f), kMinHoverRadius);
DrawHighlight(canvas, hover_location, radius * scale,
SkColorSetA(GetTabBackgroundColor(TAB_ACTIVE),
hover_controller_->GetAlpha()));
}
}
| 172,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: JSValue JSWebKitMutationObserver::observe(ExecState* exec)
{
if (exec->argumentCount() < 2)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
Node* target = toNode(exec->argument(0));
if (exec->hadException())
return jsUndefined();
JSObject* optionsObject = exec->argument(1).getObject();
if (!optionsObject) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
JSDictionary dictionary(exec, optionsObject);
MutationObserverOptions options = 0;
for (unsigned i = 0; i < numBooleanOptions; ++i) {
bool option = false;
if (!dictionary.tryGetProperty(booleanOptions[i].name, option))
return jsUndefined();
if (option)
options |= booleanOptions[i].value;
}
HashSet<AtomicString> attributeFilter;
if (!dictionary.tryGetProperty("attributeFilter", attributeFilter))
return jsUndefined();
if (!attributeFilter.isEmpty())
options |= WebKitMutationObserver::AttributeFilter;
ExceptionCode ec = 0;
impl()->observe(target, options, attributeFilter, ec);
if (ec)
setDOMException(exec, ec);
return jsUndefined();
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | JSValue JSWebKitMutationObserver::observe(ExecState* exec)
{
if (exec->argumentCount() < 2)
return throwError(exec, createNotEnoughArgumentsError(exec));
Node* target = toNode(exec->argument(0));
if (exec->hadException())
return jsUndefined();
JSObject* optionsObject = exec->argument(1).getObject();
if (!optionsObject) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
JSDictionary dictionary(exec, optionsObject);
MutationObserverOptions options = 0;
for (unsigned i = 0; i < numBooleanOptions; ++i) {
bool option = false;
if (!dictionary.tryGetProperty(booleanOptions[i].name, option))
return jsUndefined();
if (option)
options |= booleanOptions[i].value;
}
HashSet<AtomicString> attributeFilter;
if (!dictionary.tryGetProperty("attributeFilter", attributeFilter))
return jsUndefined();
if (!attributeFilter.isEmpty())
options |= WebKitMutationObserver::AttributeFilter;
ExceptionCode ec = 0;
impl()->observe(target, options, attributeFilter, ec);
if (ec)
setDOMException(exec, ec);
return jsUndefined();
}
| 170,564 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SchedulerObject::suspend(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true);
return true;
}
Commit Message:
CWE ID: CWE-20 | SchedulerObject::suspend(std::string key, std::string &/*reason*/, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true);
return true;
}
| 164,836 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void si_conn_send(struct connection *conn)
{
struct stream_interface *si = conn->owner;
struct channel *chn = si->ob;
int ret;
if (chn->pipe && conn->xprt->snd_pipe) {
ret = conn->xprt->snd_pipe(conn, chn->pipe);
if (ret > 0)
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->pipe->data) {
put_pipe(chn->pipe);
chn->pipe = NULL;
}
if (conn->flags & CO_FL_ERROR)
return;
}
/* At this point, the pipe is empty, but we may still have data pending
* in the normal buffer.
*/
if (!chn->buf->o)
return;
/* when we're here, we already know that there is no spliced
* data left, and that there are sendable buffered data.
*/
if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) {
/* check if we want to inform the kernel that we're interested in
* sending more data after this call. We want this if :
* - we're about to close after this last send and want to merge
* the ongoing FIN with the last segment.
* - we know we can't send everything at once and must get back
* here because of unaligned data
* - there is still a finite amount of data to forward
* The test is arranged so that the most common case does only 2
* tests.
*/
unsigned int send_flag = 0;
if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) &&
((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) ||
(chn->flags & CF_EXPECT_MORE))) ||
((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW))
send_flag |= CO_SFL_MSG_MORE;
if (chn->flags & CF_STREAMER)
send_flag |= CO_SFL_STREAMER;
ret = conn->xprt->snd_buf(conn, chn->buf, send_flag);
if (ret > 0) {
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->buf->o) {
/* Always clear both flags once everything has been sent, they're one-shot */
chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT);
}
/* if some data remain in the buffer, it's only because the
* system buffers are full, we will try next time.
*/
}
}
return;
}
Commit Message:
CWE ID: CWE-189 | static void si_conn_send(struct connection *conn)
{
struct stream_interface *si = conn->owner;
struct channel *chn = si->ob;
int ret;
if (chn->pipe && conn->xprt->snd_pipe) {
ret = conn->xprt->snd_pipe(conn, chn->pipe);
if (ret > 0)
chn->flags |= CF_WRITE_PARTIAL | CF_WROTE_DATA;
if (!chn->pipe->data) {
put_pipe(chn->pipe);
chn->pipe = NULL;
}
if (conn->flags & CO_FL_ERROR)
return;
}
/* At this point, the pipe is empty, but we may still have data pending
* in the normal buffer.
*/
if (!chn->buf->o)
return;
/* when we're here, we already know that there is no spliced
* data left, and that there are sendable buffered data.
*/
if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) {
/* check if we want to inform the kernel that we're interested in
* sending more data after this call. We want this if :
* - we're about to close after this last send and want to merge
* the ongoing FIN with the last segment.
* - we know we can't send everything at once and must get back
* here because of unaligned data
* - there is still a finite amount of data to forward
* The test is arranged so that the most common case does only 2
* tests.
*/
unsigned int send_flag = 0;
if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) &&
((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) ||
(chn->flags & CF_EXPECT_MORE))) ||
((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW))
send_flag |= CO_SFL_MSG_MORE;
if (chn->flags & CF_STREAMER)
send_flag |= CO_SFL_STREAMER;
ret = conn->xprt->snd_buf(conn, chn->buf, send_flag);
if (ret > 0) {
chn->flags |= CF_WRITE_PARTIAL | CF_WROTE_DATA;
if (!chn->buf->o) {
/* Always clear both flags once everything has been sent, they're one-shot */
chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT);
}
/* if some data remain in the buffer, it's only because the
* system buffers are full, we will try next time.
*/
}
}
return;
}
| 164,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: RLE check for pixel offset less than 0 (heap overflow report from Craig Young).
CWE ID: CWE-119 | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
{
int i, j;
Curves16Data* c16;
c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data));
if (c16 == NULL) return NULL;
c16 ->nCurves = nCurves;
c16 ->nElements = nElements;
c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
if (c16 ->Curves == NULL) return NULL;
for (i=0; i < nCurves; i++) {
c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
if (nElements == 256) {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
}
}
else {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
}
}
}
return c16;
}
Commit Message: Non happy-path fixes
CWE ID: | Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
{
int i, j;
Curves16Data* c16;
c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data));
if (c16 == NULL) return NULL;
c16 ->nCurves = nCurves;
c16 ->nElements = nElements;
c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
if (c16 ->Curves == NULL) return NULL;
for (i=0; i < nCurves; i++) {
c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
if (c16->Curves[i] == NULL) {
for (j=0; j < i; j++) {
_cmsFree(ContextID, c16->Curves[j]);
}
_cmsFree(ContextID, c16->Curves);
_cmsFree(ContextID, c16);
return NULL;
}
if (nElements == 256) {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
}
}
else {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
}
}
}
return c16;
}
| 166,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC)
{
zval** ele_value = NULL;
int i = 0;
int isFirstSubtag = 0;
int max_value = 0;
/* Variant/ Extlang/Private etc. */
if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if( Z_TYPE_PP(ele_value) == IS_STRING ){
add_prefix( loc_name , key_name);
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
} else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) {
HashPosition pos;
HashTable *arr = HASH_OF(*ele_value);
zval **data = NULL;
zend_hash_internal_pointer_reset_ex(arr, &pos);
while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) {
if(Z_TYPE_PP(data) != IS_STRING) {
return FAILURE;
}
if (isFirstSubtag++ == 0){
add_prefix(loc_name , key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data));
zend_hash_move_forward_ex(arr, &pos);
}
return SUCCESS;
} else {
return FAILURE;
}
} else {
char cur_key_name[31];
/* Decide the max_value: the max. no. of elements allowed */
if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){
max_value = MAX_NO_VARIANT;
}
if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){
max_value = MAX_NO_EXTLANG;
}
if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){
max_value = MAX_NO_PRIVATE;
}
/* Multiple variant values as variant0, variant1 ,variant2 */
isFirstSubtag = 0;
for( i=0 ; i< max_value; i++ ){
snprintf( cur_key_name , 30, "%s%d", key_name , i);
if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){
if( Z_TYPE_PP(ele_value)!= IS_STRING ){
/* variant is not a string */
return FAILURE;
}
/* Add the contents */
if (isFirstSubtag++ == 0){
add_prefix(loc_name , cur_key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
}
} /* end of for */
} /* end of else */
return SUCCESS;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC)
{
zval** ele_value = NULL;
int i = 0;
int isFirstSubtag = 0;
int max_value = 0;
/* Variant/ Extlang/Private etc. */
if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if( Z_TYPE_PP(ele_value) == IS_STRING ){
add_prefix( loc_name , key_name);
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
} else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) {
HashPosition pos;
HashTable *arr = HASH_OF(*ele_value);
zval **data = NULL;
zend_hash_internal_pointer_reset_ex(arr, &pos);
while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) {
if(Z_TYPE_PP(data) != IS_STRING) {
return FAILURE;
}
if (isFirstSubtag++ == 0){
add_prefix(loc_name , key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data));
zend_hash_move_forward_ex(arr, &pos);
}
return SUCCESS;
} else {
return FAILURE;
}
} else {
char cur_key_name[31];
/* Decide the max_value: the max. no. of elements allowed */
if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){
max_value = MAX_NO_VARIANT;
}
if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){
max_value = MAX_NO_EXTLANG;
}
if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){
max_value = MAX_NO_PRIVATE;
}
/* Multiple variant values as variant0, variant1 ,variant2 */
isFirstSubtag = 0;
for( i=0 ; i< max_value; i++ ){
snprintf( cur_key_name , 30, "%s%d", key_name , i);
if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){
if( Z_TYPE_PP(ele_value)!= IS_STRING ){
/* variant is not a string */
return FAILURE;
}
/* Add the contents */
if (isFirstSubtag++ == 0){
add_prefix(loc_name , cur_key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
}
} /* end of for */
} /* end of else */
return SUCCESS;
}
| 167,199 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */
{
char *table_copy, *escaped, *token, *tmp;
size_t len;
/* schame.table should be "schame"."table" */
table_copy = estrdup(table);
token = php_strtok_r(table_copy, ".", &tmp);
len = strlen(token);
if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
smart_str_appendl(querystr, token, len);
PGSQLfree(escaped);
}
if (tmp && *tmp) {
len = strlen(tmp);
/* "schema"."table" format */
if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
smart_str_appendc(querystr, '.');
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
}
/* }}} */
Commit Message:
CWE ID: | static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */
{
char *table_copy, *escaped, *token, *tmp;
size_t len;
/* schame.table should be "schame"."table" */
table_copy = estrdup(table);
token = php_strtok_r(table_copy, ".", &tmp);
if (token == NULL) {
token = table;
}
len = strlen(token);
if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
smart_str_appendl(querystr, token, len);
PGSQLfree(escaped);
}
if (tmp && *tmp) {
len = strlen(tmp);
/* "schema"."table" format */
if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
smart_str_appendc(querystr, '.');
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
}
/* }}} */
| 164,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
if (network_state_ != kNetworkLoading)
return;
double time = WTF::CurrentTime();
double timedelta = time - previous_progress_time_;
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
ScheduleEvent(EventTypeNames::progress);
previous_progress_time_ = time;
sent_stalled_event_ = false;
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
} else if (timedelta > 3.0 && !sent_stalled_event_) {
ScheduleEvent(EventTypeNames::stalled);
sent_stalled_event_ = true;
SetShouldDelayLoadEvent(false);
}
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200 | void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
if (network_state_ != kNetworkLoading)
return;
// If this is an cross-origin request, and we haven't discovered whether
// the media is actually playable yet, don't fire any progress events as
// those may let the page know information about the resource that it's
// not supposed to know.
if (MediaShouldBeOpaque())
return;
double time = WTF::CurrentTime();
double timedelta = time - previous_progress_time_;
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
ScheduleEvent(EventTypeNames::progress);
previous_progress_time_ = time;
sent_stalled_event_ = false;
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
} else if (timedelta > 3.0 && !sent_stalled_event_) {
ScheduleEvent(EventTypeNames::stalled);
sent_stalled_event_ = true;
SetShouldDelayLoadEvent(false);
}
}
| 173,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FragmentPaintPropertyTreeBuilder::UpdateOutOfFlowContext() {
if (!object_.IsBoxModelObject() && !properties_)
return;
if (object_.IsLayoutBlock())
context_.paint_offset_for_float = context_.current.paint_offset;
if (object_.CanContainAbsolutePositionObjects()) {
context_.absolute_position = context_.current;
}
if (object_.IsLayoutView()) {
const auto* initial_fixed_transform = context_.fixed_position.transform;
const auto* initial_fixed_scroll = context_.fixed_position.scroll;
context_.fixed_position = context_.current;
context_.fixed_position.fixed_position_children_fixed_to_root = true;
context_.fixed_position.transform = initial_fixed_transform;
context_.fixed_position.scroll = initial_fixed_scroll;
} else if (object_.CanContainFixedPositionObjects()) {
context_.fixed_position = context_.current;
context_.fixed_position.fixed_position_children_fixed_to_root = false;
} else if (properties_ && properties_->CssClip()) {
auto* css_clip = properties_->CssClip();
if (context_.fixed_position.clip == css_clip->Parent()) {
context_.fixed_position.clip = css_clip;
} else {
if (NeedsPaintPropertyUpdate()) {
OnUpdate(properties_->UpdateCssClipFixedPosition(
context_.fixed_position.clip,
ClipPaintPropertyNode::State{css_clip->LocalTransformSpace(),
css_clip->ClipRect()}));
}
if (properties_->CssClipFixedPosition())
context_.fixed_position.clip = properties_->CssClipFixedPosition();
return;
}
}
if (NeedsPaintPropertyUpdate() && properties_)
OnClear(properties_->ClearCssClipFixedPosition());
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void FragmentPaintPropertyTreeBuilder::UpdateOutOfFlowContext() {
if (!object_.IsBoxModelObject() && !properties_)
return;
if (object_.IsLayoutBlock())
context_.paint_offset_for_float = context_.current.paint_offset;
if (object_.CanContainAbsolutePositionObjects()) {
context_.absolute_position = context_.current;
}
if (object_.IsLayoutView()) {
const auto* initial_fixed_transform = context_.fixed_position.transform;
const auto* initial_fixed_scroll = context_.fixed_position.scroll;
context_.fixed_position = context_.current;
context_.fixed_position.fixed_position_children_fixed_to_root = true;
context_.fixed_position.transform = initial_fixed_transform;
context_.fixed_position.scroll = initial_fixed_scroll;
} else if (object_.CanContainFixedPositionObjects()) {
context_.fixed_position = context_.current;
context_.fixed_position.fixed_position_children_fixed_to_root = false;
} else if (properties_ && properties_->CssClip()) {
auto* css_clip = properties_->CssClip();
if (context_.fixed_position.clip == css_clip->Parent()) {
context_.fixed_position.clip = css_clip;
} else {
if (NeedsPaintPropertyUpdate()) {
OnUpdate(properties_->UpdateCssClipFixedPosition(
*context_.fixed_position.clip,
ClipPaintPropertyNode::State{css_clip->LocalTransformSpace(),
css_clip->ClipRect()}));
}
if (properties_->CssClipFixedPosition())
context_.fixed_position.clip = properties_->CssClipFixedPosition();
return;
}
}
if (NeedsPaintPropertyUpdate() && properties_)
OnClear(properties_->ClearCssClipFixedPosition());
}
| 171,799 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Map U+04CF to lowercase L as well.
U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase
I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered
in some fonts.
If a host name contains it, calculate the confusability skeleton
twice, once with the default mapping to 'i' (lowercase I) and the 2nd
time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L)
also gets it treated as similar to digit 1 because the confusability
skeleton of digit 1 is 'l'.
Bug: 817247
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c
Reviewed-on: https://chromium-review.googlesource.com/974165
Commit-Queue: Jungshik Shin <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Reviewed-by: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#551263}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
int i, err = 0;
int free = -1;
mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
mutex_lock(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
if (free < 0 && !table->refs[i]) {
free = i;
continue;
}
if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
/* MAC already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
mlx4_dbg(dev, "Free MAC index is %d\n", free);
if (table->total == table->max) {
/* No free mac entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);
err = mlx4_set_port_mac_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
Commit Message: mlx4_en: Fix out of bounds array access
When searching for a free entry in either mlx4_register_vlan() or
mlx4_register_mac(), and there is no free entry, the loop terminates without
updating the local variable free thus causing out of array bounds access. Fix
this by adding a proper check outside the loop.
Signed-off-by: Eli Cohen <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
int i, err = 0;
int free = -1;
mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
mutex_lock(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
if (free < 0 && !table->refs[i]) {
free = i;
continue;
}
if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
/* MAC already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (free < 0) {
err = -ENOMEM;
goto out;
}
mlx4_dbg(dev, "Free MAC index is %d\n", free);
if (table->total == table->max) {
/* No free mac entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);
err = mlx4_set_port_mac_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
| 169,871 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
op->addr = addr;
r_strbuf_setf (&op->esil, "");
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
Commit Message: Fix oobread in avr
CWE ID: CWE-125 | static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
if (len < 2) {
return NULL;
}
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
op->addr = addr;
r_strbuf_setf (&op->esil, "");
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
| 170,162 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform *this,
transform_display *that)
{
png_modifier *pm = that->pm;
PNG_CONST color_encoding *e = pm->current_encoding;
UNUSED(this)
/* Since we check the encoding this flag must be set: */
pm->test_uses_encoding = 1;
/* If 'e' is not NULL chromaticity information is present and either a cHRM
* or an sRGB chunk will be inserted.
*/
if (e != 0)
{
/* Coefficients come from the encoding, but may need to be normalized to a
* white point Y of 1.0
*/
PNG_CONST double whiteY = e->red.Y + e->green.Y + e->blue.Y;
data.red_coefficient = e->red.Y;
data.green_coefficient = e->green.Y;
data.blue_coefficient = e->blue.Y;
if (whiteY != 1)
{
data.red_coefficient /= whiteY;
data.green_coefficient /= whiteY;
data.blue_coefficient /= whiteY;
}
}
else
{
/* The default (built in) coeffcients, as above: */
data.red_coefficient = 6968 / 32768.;
data.green_coefficient = 23434 / 32768.;
data.blue_coefficient = 2366 / 32768.;
}
data.gamma = pm->current_gamma;
/* If not set then the calculations assume linear encoding (implicitly): */
if (data.gamma == 0)
data.gamma = 1;
/* The arguments to png_set_rgb_to_gray can override the coefficients implied
* by the color space encoding. If doing exhaustive checks do the override
* in each case, otherwise do it randomly.
*/
if (pm->test_exhaustive)
{
/* First time in coefficients_overridden is 0, the following sets it to 1,
* so repeat if it is set. If a test fails this may mean we subsequently
* skip a non-override test, ignore that.
*/
data.coefficients_overridden = !data.coefficients_overridden;
pm->repeat = data.coefficients_overridden != 0;
}
else
data.coefficients_overridden = random_choice();
if (data.coefficients_overridden)
{
/* These values override the color encoding defaults, simply use random
* numbers.
*/
png_uint_32 ru;
double total;
RANDOMIZE(ru);
data.green_coefficient = total = (ru & 0xffff) / 65535.;
ru >>= 16;
data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
total += data.red_coefficient;
data.blue_coefficient = 1 - total;
# ifdef PNG_FLOATING_POINT_SUPPORTED
data.red_to_set = data.red_coefficient;
data.green_to_set = data.green_coefficient;
# else
data.red_to_set = fix(data.red_coefficient);
data.green_to_set = fix(data.green_coefficient);
# endif
/* The following just changes the error messages: */
pm->encoding_ignored = 1;
}
else
{
data.red_to_set = -1;
data.green_to_set = -1;
}
/* Adjust the error limit in the png_modifier because of the larger errors
* produced in the digitization during the gamma handling.
*/
if (data.gamma != 1) /* Use gamma tables */
{
if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
{
/* The computations have the form:
*
* r * rc + g * gc + b * bc
*
* Each component of which is +/-1/65535 from the gamma_to_1 table
* lookup, resulting in a base error of +/-6. The gamma_from_1
* conversion adds another +/-2 in the 16-bit case and
* +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
*/
that->pm->limit += pow(
# if PNG_MAX_GAMMA_8 < 14
(that->this.bit_depth == 16 ? 8. :
6. + (1<<(15-PNG_MAX_GAMMA_8)))
# else
8.
# endif
/65535, data.gamma);
}
else
{
/* Rounding to 8 bits in the linear space causes massive errors which
* will trigger the error check in transform_range_check. Fix that
* here by taking the gamma encoding into account.
*
* When DIGITIZE is set because a pre-1.7 version of libpng is being
* tested allow a bigger slack.
*
* NOTE: this magic number was determined by experiment to be 1.1 (when
* using fixed point arithmetic). There's no great merit to the value
* below, however it only affects the limit used for checking for
* internal calculation errors, not the actual limit imposed by
* pngvalid on the output errors.
*/
that->pm->limit += pow(
# if DIGITIZE
1.1
# else
1.
# endif
/255, data.gamma);
}
}
else
{
/* With no gamma correction a large error comes from the truncation of the
* calculation in the 8 bit case, allow for that here.
*/
if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
that->pm->limit += 4E-3;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform *this,
image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
transform_display *that)
{
png_modifier *pm = that->pm;
const color_encoding *e = pm->current_encoding;
UNUSED(this)
/* Since we check the encoding this flag must be set: */
pm->test_uses_encoding = 1;
/* If 'e' is not NULL chromaticity information is present and either a cHRM
* or an sRGB chunk will be inserted.
*/
if (e != 0)
{
/* Coefficients come from the encoding, but may need to be normalized to a
* white point Y of 1.0
*/
const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
data.red_coefficient = e->red.Y;
data.green_coefficient = e->green.Y;
data.blue_coefficient = e->blue.Y;
if (whiteY != 1)
{
data.red_coefficient /= whiteY;
data.green_coefficient /= whiteY;
data.blue_coefficient /= whiteY;
}
}
else
{
/* The default (built in) coeffcients, as above: */
# if PNG_LIBPNG_VER < 10700
data.red_coefficient = 6968 / 32768.;
data.green_coefficient = 23434 / 32768.;
data.blue_coefficient = 2366 / 32768.;
# else
data.red_coefficient = .2126;
data.green_coefficient = .7152;
data.blue_coefficient = .0722;
# endif
}
data.gamma = pm->current_gamma;
/* If not set then the calculations assume linear encoding (implicitly): */
if (data.gamma == 0)
data.gamma = 1;
/* The arguments to png_set_rgb_to_gray can override the coefficients implied
* by the color space encoding. If doing exhaustive checks do the override
* in each case, otherwise do it randomly.
*/
if (pm->test_exhaustive)
{
/* First time in coefficients_overridden is 0, the following sets it to 1,
* so repeat if it is set. If a test fails this may mean we subsequently
* skip a non-override test, ignore that.
*/
data.coefficients_overridden = !data.coefficients_overridden;
pm->repeat = data.coefficients_overridden != 0;
}
else
data.coefficients_overridden = random_choice();
if (data.coefficients_overridden)
{
/* These values override the color encoding defaults, simply use random
* numbers.
*/
png_uint_32 ru;
double total;
RANDOMIZE(ru);
data.green_coefficient = total = (ru & 0xffff) / 65535.;
ru >>= 16;
data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
total += data.red_coefficient;
data.blue_coefficient = 1 - total;
# ifdef PNG_FLOATING_POINT_SUPPORTED
data.red_to_set = data.red_coefficient;
data.green_to_set = data.green_coefficient;
# else
data.red_to_set = fix(data.red_coefficient);
data.green_to_set = fix(data.green_coefficient);
# endif
/* The following just changes the error messages: */
pm->encoding_ignored = 1;
}
else
{
data.red_to_set = -1;
data.green_to_set = -1;
}
/* Adjust the error limit in the png_modifier because of the larger errors
* produced in the digitization during the gamma handling.
*/
if (data.gamma != 1) /* Use gamma tables */
{
if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
{
/* The computations have the form:
*
* r * rc + g * gc + b * bc
*
* Each component of which is +/-1/65535 from the gamma_to_1 table
* lookup, resulting in a base error of +/-6. The gamma_from_1
* conversion adds another +/-2 in the 16-bit case and
* +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
*/
# if PNG_LIBPNG_VER < 10700
if (that->this.bit_depth < 16)
that->max_gamma_8 = PNG_MAX_GAMMA_8;
# endif
that->pm->limit += pow(
(that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
8. :
6. + (1<<(15-that->max_gamma_8))
)/65535, data.gamma);
}
else
{
/* Rounding to 8 bits in the linear space causes massive errors which
* will trigger the error check in transform_range_check. Fix that
* here by taking the gamma encoding into account.
*
* When DIGITIZE is set because a pre-1.7 version of libpng is being
* tested allow a bigger slack.
*
* NOTE: this magic number was determined by experiment to be about
* 1.263. There's no great merit to the value below, however it only
* affects the limit used for checking for internal calculation errors,
* not the actual limit imposed by pngvalid on the output errors.
*/
that->pm->limit += pow(
# if DIGITIZE
1.3
# else
1.0
# endif
/255, data.gamma);
}
}
else
{
/* With no gamma correction a large error comes from the truncation of the
* calculation in the 8 bit case, allow for that here.
*/
if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
that->pm->limit += 4E-3;
}
}
| 173,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
PanicZ( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name,
face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%s': error 0x%04x", basename,
(FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
sprintf( status.header_buffer, "at %g points, angle = %d",
status.ptsize/64.0, status.angle );
grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
Commit Message:
CWE ID: CWE-119 | write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
PanicZ( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer,
"%.50s %.50s (file `%.100s')", face->family_name,
face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename,
(FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
sprintf( status.header_buffer, "at %g points, angle = %d",
status.ptsize/64.0, status.angle );
grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
| 165,000 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void iriap_getvaluebyclass_indication(struct iriap_cb *self,
struct sk_buff *skb)
{
struct ias_object *obj;
struct ias_attrib *attrib;
int name_len;
int attr_len;
char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */
char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */
__u8 *fp;
int n;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
fp = skb->data;
n = 1;
name_len = fp[n++];
memcpy(name, fp+n, name_len); n+=name_len;
name[name_len] = '\0';
attr_len = fp[n++];
memcpy(attr, fp+n, attr_len); n+=attr_len;
attr[attr_len] = '\0';
IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr);
obj = irias_find_object(name);
if (obj == NULL) {
IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name);
iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN,
&irias_missing);
return;
}
IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id);
attrib = irias_find_attrib(obj, attr);
if (attrib == NULL) {
IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr);
iriap_getvaluebyclass_response(self, obj->id,
IAS_ATTRIB_UNKNOWN,
&irias_missing);
return;
}
/* We have a match; send the value. */
iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS,
attrib->value);
}
Commit Message: irda: validate peer name and attribute lengths
Length fields provided by a peer for names and attributes may be longer
than the destination array sizes. Validate lengths to prevent stack
buffer overflows.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static void iriap_getvaluebyclass_indication(struct iriap_cb *self,
struct sk_buff *skb)
{
struct ias_object *obj;
struct ias_attrib *attrib;
int name_len;
int attr_len;
char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */
char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */
__u8 *fp;
int n;
IRDA_DEBUG(4, "%s()\n", __func__);
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IAS_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
fp = skb->data;
n = 1;
name_len = fp[n++];
IRDA_ASSERT(name_len < IAS_MAX_CLASSNAME + 1, return;);
memcpy(name, fp+n, name_len); n+=name_len;
name[name_len] = '\0';
attr_len = fp[n++];
IRDA_ASSERT(attr_len < IAS_MAX_ATTRIBNAME + 1, return;);
memcpy(attr, fp+n, attr_len); n+=attr_len;
attr[attr_len] = '\0';
IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr);
obj = irias_find_object(name);
if (obj == NULL) {
IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name);
iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN,
&irias_missing);
return;
}
IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id);
attrib = irias_find_attrib(obj, attr);
if (attrib == NULL) {
IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr);
iriap_getvaluebyclass_response(self, obj->id,
IAS_ATTRIB_UNKNOWN,
&irias_missing);
return;
}
/* We have a match; send the value. */
iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS,
attrib->value);
}
| 166,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Include U+0517 in set of Cyrillic/Latin lookalikes.
Cyrillic letter U+0517 (ԗ) looks somewhat similar to the Latin letter p.
This CL adds this character to the set of Cyrillic characters that look
like Latin characters. Domains made up entirely of Cyrillic/Latin
lookalikes are displayed as punycode in URLs.
Bug: 863663
Change-Id: I4340c48d124c9c4cd3d3b5d0f9d3865d709e082d
Reviewed-on: https://chromium-review.googlesource.com/c/1286825
Commit-Queue: Joe DeBlasio <[email protected]>
Commit-Queue: Peter Kasting <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600582}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)
{
if ((ctx->clockid == CLOCK_REALTIME ||
ctx->clockid == CLOCK_REALTIME_ALARM) &&
(flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {
if (!ctx->might_cancel) {
ctx->might_cancel = true;
spin_lock(&cancel_lock);
list_add_rcu(&ctx->clist, &cancel_list);
spin_unlock(&cancel_lock);
}
} else if (ctx->might_cancel) {
timerfd_remove_cancel(ctx);
}
}
Commit Message: timerfd: Protect the might cancel mechanism proper
The handling of the might_cancel queueing is not properly protected, so
parallel operations on the file descriptor can race with each other and
lead to list corruptions or use after free.
Protect the context for these operations with a seperate lock.
The wait queue lock cannot be reused for this because that would create a
lock inversion scenario vs. the cancel lock. Replacing might_cancel with an
atomic (atomic_t or atomic bit) does not help either because it still can
race vs. the actual list operation.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: "[email protected]"
Cc: syzkaller <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos
Signed-off-by: Thomas Gleixner <[email protected]>
CWE ID: CWE-416 | static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)
{
spin_lock(&ctx->cancel_lock);
if ((ctx->clockid == CLOCK_REALTIME ||
ctx->clockid == CLOCK_REALTIME_ALARM) &&
(flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {
if (!ctx->might_cancel) {
ctx->might_cancel = true;
spin_lock(&cancel_lock);
list_add_rcu(&ctx->clist, &cancel_list);
spin_unlock(&cancel_lock);
}
} else {
__timerfd_remove_cancel(ctx);
}
spin_unlock(&ctx->cancel_lock);
}
| 168,068 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
const uint8_t *src, int src_size)
{
int width, height;
int hdr, zsize, npal, tidx = -1, ret;
int i, j;
const uint8_t *src_end = src + src_size;
uint8_t pal[768], transp[3];
uLongf dlen = (c->tile_width + 1) * c->tile_height;
int sub_type;
int nblocks, cblocks, bstride;
int bits, bitbuf, coded;
uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
tile_y * c->tile_height * c->framebuf_stride;
if (src_size < 2)
return AVERROR_INVALIDDATA;
width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width);
height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
hdr = *src++;
sub_type = hdr >> 5;
if (sub_type == 0) {
int j;
memcpy(transp, src, 3);
src += 3;
for (j = 0; j < height; j++, dst += c->framebuf_stride)
for (i = 0; i < width; i++)
memcpy(dst + i * 3, transp, 3);
return 0;
} else if (sub_type == 1) {
return jpg_decode_data(&c->jc, width, height, src, src_end - src,
dst, c->framebuf_stride, NULL, 0, 0, 0);
}
if (sub_type != 2) {
memcpy(transp, src, 3);
src += 3;
}
npal = *src++ + 1;
memcpy(pal, src, npal * 3); src += npal * 3;
if (sub_type != 2) {
for (i = 0; i < npal; i++) {
if (!memcmp(pal + i * 3, transp, 3)) {
tidx = i;
break;
}
}
}
if (src_end - src < 2)
return 0;
zsize = (src[0] << 8) | src[1]; src += 2;
if (src_end - src < zsize)
return AVERROR_INVALIDDATA;
ret = uncompress(c->kempf_buf, &dlen, src, zsize);
if (ret)
return AVERROR_INVALIDDATA;
src += zsize;
if (sub_type == 2) {
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
NULL, 0, width, height, pal, npal, tidx);
return 0;
}
nblocks = *src++ + 1;
cblocks = 0;
bstride = FFALIGN(width, 16) >> 4;
bits = 0;
for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
if (!bits) {
bitbuf = *src++;
bits = 8;
}
coded = bitbuf & 1;
bits--;
bitbuf >>= 1;
cblocks += coded;
if (cblocks > nblocks)
return AVERROR_INVALIDDATA;
c->kempf_flags[j + i * bstride] = coded;
}
}
memset(c->jpeg_tile, 0, c->tile_stride * height);
jpg_decode_data(&c->jc, width, height, src, src_end - src,
c->jpeg_tile, c->tile_stride,
c->kempf_flags, bstride, nblocks, 0);
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
c->jpeg_tile, c->tile_stride,
width, height, pal, npal, tidx);
return 0;
}
Commit Message: avcodec/g2meet: fix src pointer checks in kempf_decode_tile()
Fixes Ticket2842
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
const uint8_t *src, int src_size)
{
int width, height;
int hdr, zsize, npal, tidx = -1, ret;
int i, j;
const uint8_t *src_end = src + src_size;
uint8_t pal[768], transp[3];
uLongf dlen = (c->tile_width + 1) * c->tile_height;
int sub_type;
int nblocks, cblocks, bstride;
int bits, bitbuf, coded;
uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
tile_y * c->tile_height * c->framebuf_stride;
if (src_size < 2)
return AVERROR_INVALIDDATA;
width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width);
height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
hdr = *src++;
sub_type = hdr >> 5;
if (sub_type == 0) {
int j;
memcpy(transp, src, 3);
src += 3;
for (j = 0; j < height; j++, dst += c->framebuf_stride)
for (i = 0; i < width; i++)
memcpy(dst + i * 3, transp, 3);
return 0;
} else if (sub_type == 1) {
return jpg_decode_data(&c->jc, width, height, src, src_end - src,
dst, c->framebuf_stride, NULL, 0, 0, 0);
}
if (sub_type != 2) {
memcpy(transp, src, 3);
src += 3;
}
npal = *src++ + 1;
memcpy(pal, src, npal * 3); src += npal * 3;
if (sub_type != 2) {
for (i = 0; i < npal; i++) {
if (!memcmp(pal + i * 3, transp, 3)) {
tidx = i;
break;
}
}
}
if (src_end - src < 2)
return 0;
zsize = (src[0] << 8) | src[1]; src += 2;
if (src_end - src < zsize + (sub_type != 2))
return AVERROR_INVALIDDATA;
ret = uncompress(c->kempf_buf, &dlen, src, zsize);
if (ret)
return AVERROR_INVALIDDATA;
src += zsize;
if (sub_type == 2) {
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
NULL, 0, width, height, pal, npal, tidx);
return 0;
}
nblocks = *src++ + 1;
cblocks = 0;
bstride = FFALIGN(width, 16) >> 4;
bits = 0;
for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
if (!bits) {
if (src >= src_end)
return AVERROR_INVALIDDATA;
bitbuf = *src++;
bits = 8;
}
coded = bitbuf & 1;
bits--;
bitbuf >>= 1;
cblocks += coded;
if (cblocks > nblocks)
return AVERROR_INVALIDDATA;
c->kempf_flags[j + i * bstride] = coded;
}
}
memset(c->jpeg_tile, 0, c->tile_stride * height);
jpg_decode_data(&c->jc, width, height, src, src_end - src,
c->jpeg_tile, c->tile_stride,
c->kempf_flags, bstride, nblocks, 0);
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
c->jpeg_tile, c->tile_stride,
width, height, pal, npal, tidx);
return 0;
}
| 165,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() {
using api::extension_types::ImageDetails;
EXTENSION_FUNCTION_VALIDATE(args_);
int context_id = extension_misc::kCurrentWindowId;
args_->GetInteger(0, &context_id);
std::unique_ptr<ImageDetails> image_details;
if (args_->GetSize() > 1) {
base::Value* spec = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec);
image_details = ImageDetails::FromValue(*spec);
}
std::string error;
WebContents* contents = GetWebContentsForID(context_id, &error);
const CaptureResult capture_result = CaptureAsync(
contents, image_details.get(),
base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete,
this));
if (capture_result == OK) {
return did_respond() ? AlreadyResponded() : RespondLater();
}
return RespondNow(Error(CaptureResultToErrorMessage(capture_result)));
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20 | ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() {
using api::extension_types::ImageDetails;
EXTENSION_FUNCTION_VALIDATE(args_);
int context_id = extension_misc::kCurrentWindowId;
args_->GetInteger(0, &context_id);
std::unique_ptr<ImageDetails> image_details;
if (args_->GetSize() > 1) {
base::Value* spec = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec);
image_details = ImageDetails::FromValue(*spec);
}
std::string error;
WebContents* contents = GetWebContentsForID(context_id, &error);
if (!contents)
return RespondNow(Error(error));
const CaptureResult capture_result = CaptureAsync(
contents, image_details.get(),
base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete,
this));
if (capture_result == OK) {
return did_respond() ? AlreadyResponded() : RespondLater();
}
return RespondNow(Error(CaptureResultToErrorMessage(capture_result)));
}
| 173,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Segment::DoLoadClusterUnknownSize(
long long& pos,
long& len)
{
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) //determine cluster size
{
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster ID or Cues ID
{
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) //error or underflow
return status;
if (status == 0) //parsed a block
return 2; //continue parsing
assert(status > 0); //nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; //continue parsing
#endif
}
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 Segment::DoLoadClusterUnknownSize(
long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) { //determine cluster size
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) // error or underflow
return status;
if (status == 0) // parsed a block
return 2; // continue parsing
assert(status > 0); // nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; // continue parsing
#endif
}
| 174,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1612
CWE ID: CWE-119 | static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
format,
magick[MaxTextExtent];
const char
*value;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*pixels,
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
max_value=GetQuantumRange(image->depth);
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MaxTextExtent);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,&image->exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MaxTextExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,&image->exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MaxTextExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent);
if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MaxTextExtent);
break;
}
}
if (image->matte != MagickFalse)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n",
type);
(void) WriteBlobString(image,buffer);
}
/*
Convert to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ",
ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)),
ScaleQuantumToChar(GetPixelGreen(p)),
ScaleQuantumToChar(GetPixelBlue(p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)),
ScaleQuantumToShort(GetPixelGreen(p)),
ScaleQuantumToShort(GetPixelBlue(p)));
else
count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)),
ScaleQuantumToLong(GetPixelGreen(p)),
ScaleQuantumToLong(GetPixelBlue(p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p++;
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
else
{
if (image->depth == 32)
pixel=ScaleQuantumToLong(GetPixelRed(p));
else
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned short) pixel,q);
p++;
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(
GetPixelLuma(image,p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelOpacity(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p++;
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p++;
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->matte != MagickFalse)
{
pixel=ScaleQuantumToAny((Quantum) (QuantumRange-
GetPixelOpacity(p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p++;
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
extent=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| 169,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int propagate_one(struct mount *m)
{
struct mount *child;
int type;
/* skip ones added by this propagate_mnt() */
if (IS_MNT_NEW(m))
return 0;
/* skip if mountpoint isn't covered by it */
if (!is_subdir(mp->m_dentry, m->mnt.mnt_root))
return 0;
if (peers(m, last_dest)) {
type = CL_MAKE_SHARED;
} else {
struct mount *n, *p;
bool done;
for (n = m; ; n = p) {
p = n->mnt_master;
if (p == dest_master || IS_MNT_MARKED(p))
break;
}
do {
struct mount *parent = last_source->mnt_parent;
if (last_source == first_source)
break;
done = parent->mnt_master == p;
if (done && peers(n, parent))
break;
last_source = last_source->mnt_master;
} while (!done);
type = CL_SLAVE;
/* beginning of peer group among the slaves? */
if (IS_MNT_SHARED(m))
type |= CL_MAKE_SHARED;
}
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(last_source, last_source->mnt.mnt_root, type);
if (IS_ERR(child))
return PTR_ERR(child);
child->mnt.mnt_flags &= ~MNT_LOCKED;
mnt_set_mountpoint(m, mp, child);
last_dest = m;
last_source = child;
if (m->mnt_master != dest_master) {
read_seqlock_excl(&mount_lock);
SET_MNT_MARK(m->mnt_master);
read_sequnlock_excl(&mount_lock);
}
hlist_add_head(&child->mnt_hash, list);
return 0;
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static int propagate_one(struct mount *m)
{
struct mount *child;
int type;
/* skip ones added by this propagate_mnt() */
if (IS_MNT_NEW(m))
return 0;
/* skip if mountpoint isn't covered by it */
if (!is_subdir(mp->m_dentry, m->mnt.mnt_root))
return 0;
if (peers(m, last_dest)) {
type = CL_MAKE_SHARED;
} else {
struct mount *n, *p;
bool done;
for (n = m; ; n = p) {
p = n->mnt_master;
if (p == dest_master || IS_MNT_MARKED(p))
break;
}
do {
struct mount *parent = last_source->mnt_parent;
if (last_source == first_source)
break;
done = parent->mnt_master == p;
if (done && peers(n, parent))
break;
last_source = last_source->mnt_master;
} while (!done);
type = CL_SLAVE;
/* beginning of peer group among the slaves? */
if (IS_MNT_SHARED(m))
type |= CL_MAKE_SHARED;
}
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(last_source, last_source->mnt.mnt_root, type);
if (IS_ERR(child))
return PTR_ERR(child);
child->mnt.mnt_flags &= ~MNT_LOCKED;
mnt_set_mountpoint(m, mp, child);
last_dest = m;
last_source = child;
if (m->mnt_master != dest_master) {
read_seqlock_excl(&mount_lock);
SET_MNT_MARK(m->mnt_master);
read_sequnlock_excl(&mount_lock);
}
hlist_add_head(&child->mnt_hash, list);
return count_mounts(m->mnt_ns, child);
}
| 167,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
image2 = (Image *) NULL;
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
quantum_info=(QuantumInfo *) NULL;
clone_info=(ImageInfo *) NULL;
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image=ReadMATImageV4(image_info,image,exception);
if (image == NULL)
{
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
return((Image *) NULL);
}
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
{
MATLAB_KO:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
if (filepos != (unsigned int) filepos)
break;
if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
goto MATLAB_KO;
filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4;
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
clone_info=CloneImageInfo(image_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if (MATLAB_HDR.DataType != miMATRIX)
{
clone_info=DestroyImageInfo(clone_info);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (image2 != image)
DeleteImageFromList(&image2);
#endif
continue; /* skip another objects. */
}
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
}
break;
default:
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
{
if ((image2 != (Image*) NULL) && (image2 != image))
{
CloseBlob(image2);
DeleteImageFromList(&image2);
}
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
}
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (((size_t) size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
/* data size */
if (ReadBlob(image2, 4, (unsigned char *) &size) != 4)
goto MATLAB_KO;
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
}
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
image->colors = GetQuantumRange(image->depth);
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image,exception);
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY,
CellType,ldblk,BImgBuff,&quantum_info->minimum,
&quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
if (i != (long) MATLAB_HDR.SizeY)
goto END_OF_READING;
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
if(!EOFBlob(image) && TellBlob(image)<filepos)
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
}
END_OF_READING:
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
if (tmp == image2)
image2=(Image *) NULL;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1554
CWE ID: CWE-416 | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
register Quantum *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
image2 = (Image *) NULL;
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
quantum_info=(QuantumInfo *) NULL;
clone_info=(ImageInfo *) NULL;
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image=ReadMATImageV4(image_info,image,exception);
if (image == NULL)
{
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
return((Image *) NULL);
}
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
{
MATLAB_KO:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(filepos < GetBlobSize(image) && !EOFBlob(image)) /* object parser loop */
{
Frames = 1;
if(filepos > GetBlobSize(image) || filepos < 0)
break;
if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) >= GetBlobSize(image))
goto MATLAB_KO;
filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4;
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
clone_info=CloneImageInfo(image_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if (MATLAB_HDR.DataType != miMATRIX)
{
clone_info=DestroyImageInfo(clone_info);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (image2 != image)
DeleteImageFromList(&image2);
#endif
continue; /* skip another objects. */
}
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
(void) ReadBlobXXXLong(image2);
if(z!=3)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
}
break;
default:
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
{
if ((image2 != (Image*) NULL) && (image2 != image))
{
CloseBlob(image2);
DeleteImageFromList(&image2);
}
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
}
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (((size_t) size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
/* data size */
if (ReadBlob(image2, 4, (unsigned char *) &size) != 4)
goto MATLAB_KO;
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
}
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
image->colors = GetQuantumRange(image->depth);
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image,exception);
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY,
CellType,ldblk,BImgBuff,&quantum_info->minimum,
&quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(image,q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
if (i != (long) MATLAB_HDR.SizeY)
goto END_OF_READING;
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
if(!EOFBlob(image) && TellBlob(image)<filepos)
goto NEXT_FRAME;
}
if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
}
END_OF_READING:
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
if (tmp == image2)
image2=(Image *) NULL;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
return(image);
}
| 169,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void gmc_mmx(uint8_t *dst, uint8_t *src,
int stride, int h, int ox, int oy,
int dxx, int dxy, int dyx, int dyy,
int shift, int r, int width, int height)
{
const int w = 8;
const int ix = ox >> (16 + shift);
const int iy = oy >> (16 + shift);
const int oxs = ox >> 4;
const int oys = oy >> 4;
const int dxxs = dxx >> 4;
const int dxys = dxy >> 4;
const int dyxs = dyx >> 4;
const int dyys = dyy >> 4;
const uint16_t r4[4] = { r, r, r, r };
const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
const uint64_t shift2 = 2 * shift;
#define MAX_STRIDE 4096U
#define MAX_H 8U
uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
int x, y;
const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
const int dxh = dxy * (h - 1);
const int dyw = dyx * (w - 1);
int need_emu = (unsigned) ix >= width - w ||
(unsigned) iy >= height - h;
if ( // non-constant fullpel offset (3% of blocks)
((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
(oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||
(dxx | dxy | dyx | dyy) & 15 ||
(need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
shift, r, width, height);
return;
}
src += ix + iy * stride;
if (need_emu) {
ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);
src = edge_buf;
}
__asm__ volatile (
"movd %0, %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
:: "r" (1 << shift));
for (x = 0; x < w; x += 4) {
uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),
oxs - dxys + dxxs * (x + 1),
oxs - dxys + dxxs * (x + 2),
oxs - dxys + dxxs * (x + 3) };
uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),
oys - dyys + dyxs * (x + 1),
oys - dyys + dyxs * (x + 2),
oys - dyys + dyxs * (x + 3) };
for (y = 0; y < h; y++) {
__asm__ volatile (
"movq %0, %%mm4 \n\t"
"movq %1, %%mm5 \n\t"
"paddw %2, %%mm4 \n\t"
"paddw %3, %%mm5 \n\t"
"movq %%mm4, %0 \n\t"
"movq %%mm5, %1 \n\t"
"psrlw $12, %%mm4 \n\t"
"psrlw $12, %%mm5 \n\t"
: "+m" (*dx4), "+m" (*dy4)
: "m" (*dxy4), "m" (*dyy4));
__asm__ volatile (
"movq %%mm6, %%mm2 \n\t"
"movq %%mm6, %%mm1 \n\t"
"psubw %%mm4, %%mm2 \n\t"
"psubw %%mm5, %%mm1 \n\t"
"movq %%mm2, %%mm0 \n\t"
"movq %%mm4, %%mm3 \n\t"
"pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy)
"pmullw %%mm5, %%mm3 \n\t" // dx * dy
"pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy
"pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy)
"movd %4, %%mm5 \n\t"
"movd %3, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy
"pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy
"movd %2, %%mm5 \n\t"
"movd %1, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy)
"pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy)
"paddw %5, %%mm1 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"psrlw %6, %%mm0 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"movd %%mm0, %0 \n\t"
: "=m" (dst[x + y * stride])
: "m" (src[0]), "m" (src[1]),
"m" (src[stride]), "m" (src[stride + 1]),
"m" (*r4), "m" (shift2));
src += stride;
}
src += 4 - h * stride;
}
}
Commit Message: avcodec/x86/mpegvideodsp: Fix signedness bug in need_emu
Fixes: out of array read
Fixes: 3516/attachment-311488.dat
Found-by: Insu Yun, Georgia Tech.
Tested-by: [email protected]
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static void gmc_mmx(uint8_t *dst, uint8_t *src,
int stride, int h, int ox, int oy,
int dxx, int dxy, int dyx, int dyy,
int shift, int r, int width, int height)
{
const int w = 8;
const int ix = ox >> (16 + shift);
const int iy = oy >> (16 + shift);
const int oxs = ox >> 4;
const int oys = oy >> 4;
const int dxxs = dxx >> 4;
const int dxys = dxy >> 4;
const int dyxs = dyx >> 4;
const int dyys = dyy >> 4;
const uint16_t r4[4] = { r, r, r, r };
const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
const uint64_t shift2 = 2 * shift;
#define MAX_STRIDE 4096U
#define MAX_H 8U
uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
int x, y;
const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
const int dxh = dxy * (h - 1);
const int dyw = dyx * (w - 1);
int need_emu = (unsigned) ix >= width - w || width < w ||
(unsigned) iy >= height - h || height< h
;
if ( // non-constant fullpel offset (3% of blocks)
((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
(oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||
(dxx | dxy | dyx | dyy) & 15 ||
(need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
shift, r, width, height);
return;
}
src += ix + iy * stride;
if (need_emu) {
ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);
src = edge_buf;
}
__asm__ volatile (
"movd %0, %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
:: "r" (1 << shift));
for (x = 0; x < w; x += 4) {
uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),
oxs - dxys + dxxs * (x + 1),
oxs - dxys + dxxs * (x + 2),
oxs - dxys + dxxs * (x + 3) };
uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),
oys - dyys + dyxs * (x + 1),
oys - dyys + dyxs * (x + 2),
oys - dyys + dyxs * (x + 3) };
for (y = 0; y < h; y++) {
__asm__ volatile (
"movq %0, %%mm4 \n\t"
"movq %1, %%mm5 \n\t"
"paddw %2, %%mm4 \n\t"
"paddw %3, %%mm5 \n\t"
"movq %%mm4, %0 \n\t"
"movq %%mm5, %1 \n\t"
"psrlw $12, %%mm4 \n\t"
"psrlw $12, %%mm5 \n\t"
: "+m" (*dx4), "+m" (*dy4)
: "m" (*dxy4), "m" (*dyy4));
__asm__ volatile (
"movq %%mm6, %%mm2 \n\t"
"movq %%mm6, %%mm1 \n\t"
"psubw %%mm4, %%mm2 \n\t"
"psubw %%mm5, %%mm1 \n\t"
"movq %%mm2, %%mm0 \n\t"
"movq %%mm4, %%mm3 \n\t"
"pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy)
"pmullw %%mm5, %%mm3 \n\t" // dx * dy
"pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy
"pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy)
"movd %4, %%mm5 \n\t"
"movd %3, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy
"pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy
"movd %2, %%mm5 \n\t"
"movd %1, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy)
"pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy)
"paddw %5, %%mm1 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"psrlw %6, %%mm0 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"movd %%mm0, %0 \n\t"
: "=m" (dst[x + y * stride])
: "m" (src[0]), "m" (src[1]),
"m" (src[stride]), "m" (src[stride + 1]),
"m" (*r4), "m" (shift2));
src += stride;
}
src += 4 - h * stride;
}
}
| 167,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void alpha_perf_event_irq_handler(unsigned long la_ptr,
struct pt_regs *regs)
{
struct cpu_hw_events *cpuc;
struct perf_sample_data data;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, j;
__get_cpu_var(irq_pmi_count)++;
cpuc = &__get_cpu_var(cpu_hw_events);
/* Completely counting through the PMC's period to trigger a new PMC
* overflow interrupt while in this interrupt routine is utterly
* disastrous! The EV6 and EV67 counters are sufficiently large to
* prevent this but to be really sure disable the PMCs.
*/
wrperfmon(PERFMON_CMD_DISABLE, cpuc->idx_mask);
/* la_ptr is the counter that overflowed. */
if (unlikely(la_ptr >= alpha_pmu->num_pmcs)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: silly index %ld\n", la_ptr);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
idx = la_ptr;
perf_sample_data_init(&data, 0);
for (j = 0; j < cpuc->n_events; j++) {
if (cpuc->current_idx[j] == idx)
break;
}
if (unlikely(j == cpuc->n_events)) {
/* This can occur if the event is disabled right on a PMC overflow. */
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
event = cpuc->event[j];
if (unlikely(!event)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: No event at index %d!\n", idx);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
hwc = &event->hw;
alpha_perf_event_update(event, hwc, idx, alpha_pmu->pmc_max_period[idx]+1);
data.period = event->hw.last_period;
if (alpha_perf_event_set_period(event, hwc, idx)) {
if (perf_event_overflow(event, 1, &data, regs)) {
/* Interrupts coming too quickly; "throttle" the
* counter, i.e., disable it for a little while.
*/
alpha_pmu_stop(event, 0);
}
}
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void alpha_perf_event_irq_handler(unsigned long la_ptr,
struct pt_regs *regs)
{
struct cpu_hw_events *cpuc;
struct perf_sample_data data;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, j;
__get_cpu_var(irq_pmi_count)++;
cpuc = &__get_cpu_var(cpu_hw_events);
/* Completely counting through the PMC's period to trigger a new PMC
* overflow interrupt while in this interrupt routine is utterly
* disastrous! The EV6 and EV67 counters are sufficiently large to
* prevent this but to be really sure disable the PMCs.
*/
wrperfmon(PERFMON_CMD_DISABLE, cpuc->idx_mask);
/* la_ptr is the counter that overflowed. */
if (unlikely(la_ptr >= alpha_pmu->num_pmcs)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: silly index %ld\n", la_ptr);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
idx = la_ptr;
perf_sample_data_init(&data, 0);
for (j = 0; j < cpuc->n_events; j++) {
if (cpuc->current_idx[j] == idx)
break;
}
if (unlikely(j == cpuc->n_events)) {
/* This can occur if the event is disabled right on a PMC overflow. */
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
event = cpuc->event[j];
if (unlikely(!event)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: No event at index %d!\n", idx);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
hwc = &event->hw;
alpha_perf_event_update(event, hwc, idx, alpha_pmu->pmc_max_period[idx]+1);
data.period = event->hw.last_period;
if (alpha_perf_event_set_period(event, hwc, idx)) {
if (perf_event_overflow(event, &data, regs)) {
/* Interrupts coming too quickly; "throttle" the
* counter, i.e., disable it for a little while.
*/
alpha_pmu_stop(event, 0);
}
}
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
| 165,772 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_modify_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_modify_principal((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_modify_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_modify_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_modify_principal((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_modify_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
strcpy(cat_enum.szRad1, fileName);
} else {
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
Commit Message: fix some overflows due to strcpy
fixes #1184, #1186, #1187 among other things
CWE ID: CWE-119 | GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
if (strlen(fileName) >= sizeof(cat_enum.szPath)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
if (strlen(fileName) >= sizeof(cat_enum.szRad1)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad1, fileName);
} else {
if (strlen(sep + 1) >= sizeof(cat_enum.szRad1)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1)));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
if (strlen(sep + 1) >= sizeof(cat_enum.szRad2)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1)));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
if (strlen(sep) >= sizeof(cat_enum.szOpt)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Invalid option: %s.\n", sep));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
| 169,788 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Chapters::Edition::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 == 0x36) // Atom ID
{
status = ParseAtom(pReader, pos, size);
if (status < 0) // error
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Chapters::Edition::Parse(
Segment* const pSegment = pChapters->m_pSegment;
if (pSegment == NULL) // weird
return -1;
const SegmentInfo* const pInfo = pSegment->GetInfo();
if (pInfo == NULL)
return -1;
const long long timecode_scale = pInfo->GetTimeCodeScale();
if (timecode_scale < 1) // weird
return -1;
if (timecode < 0)
return -1;
const long long result = timecode_scale * timecode;
return result;
}
long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos,
long long size) {
if (!ExpandDisplaysArray())
return -1;
Display& d = m_displays[m_displays_count++];
d.Init();
return d.Parse(pReader, pos, size);
}
bool Chapters::Atom::ExpandDisplaysArray() {
if (m_displays_size > m_displays_count)
return true; // nothing else to do
const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size;
Display* const displays = new (std::nothrow) Display[size];
if (displays == NULL)
return false;
for (int idx = 0; idx < m_displays_count; ++idx) {
m_displays[idx].ShallowCopy(displays[idx]);
}
delete[] m_displays;
m_displays = displays;
m_displays_size = size;
return true;
}
Chapters::Display::Display() {}
Chapters::Display::~Display() {}
const char* Chapters::Display::GetString() const { return m_string; }
const char* Chapters::Display::GetLanguage() const { return m_language; }
const char* Chapters::Display::GetCountry() const { return m_country; }
void Chapters::Display::Init() {
m_string = NULL;
m_language = NULL;
m_country = NULL;
}
void Chapters::Display::ShallowCopy(Display& rhs) const {
rhs.m_string = m_string;
rhs.m_language = m_language;
rhs.m_country = m_country;
}
void Chapters::Display::Clear() {
delete[] m_string;
m_string = NULL;
delete[] m_language;
m_language = NULL;
delete[] m_country;
m_country = NULL;
}
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;
}
| 174,401 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ZLIB_INTERNAL inflate_fast(strm, start)
z_streamp strm;
unsigned start; /* inflate()'s starting value for strm->avail_out */
{
struct inflate_state FAR *state;
z_const unsigned char FAR *in; /* local strm->next_in */
z_const unsigned char FAR *last; /* have enough input while in < last */
unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */
code const FAR *lcode; /* local strm->lencode */
code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */
code here; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */
unsigned dist; /* match distance */
unsigned char FAR *from; /* where to copy match from */
/* copy state to local variables */
state = (struct inflate_state FAR *)strm->state;
in = strm->next_in - OFF;
last = in + (strm->avail_in - 5);
out = strm->next_out - OFF;
beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize;
whave = state->whave;
wnext = state->wnext;
window = state->window;
hold = state->hold;
bits = state->bits;
lcode = state->lencode;
dcode = state->distcode;
lmask = (1U << state->lenbits) - 1;
dmask = (1U << state->distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
do {
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op == 0) { /* literal */
Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", here.val));
PUP(out) = (unsigned char)(here.val);
}
else if (op & 16) { /* length base */
len = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
len += (unsigned)hold & ((1U << op) - 1);
hold >>= op;
bits -= op;
}
Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op & 16) { /* distance base */
dist = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
}
dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op;
bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist));
op = (unsigned)(out - beg); /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state->sane) {
strm->msg =
(char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (len <= op - whave) {
do {
PUP(out) = 0;
} while (--len);
continue;
}
len -= op - whave;
do {
PUP(out) = 0;
} while (--op > whave);
if (op == 0) {
from = out - dist;
do {
PUP(out) = PUP(from);
} while (--len);
continue;
}
#endif
}
from = window - OFF;
if (wnext == 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = window - OFF;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
while (len > 2) {
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
}
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
}
else {
from = out - dist; /* copy direct from output */
do { /* minimum length is three */
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
} while (len > 2);
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
}
}
else if ((op & 64) == 0) { /* 2nd level distance code */
here = dcode[here.val + (hold & ((1U << op) - 1))];
goto dodist;
}
else {
strm->msg = (char *)"invalid distance code";
state->mode = BAD;
break;
}
}
else if ((op & 64) == 0) { /* 2nd level length code */
here = lcode[here.val + (hold & ((1U << op) - 1))];
goto dolen;
}
else if (op & 32) { /* end-of-block */
Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE;
break;
}
else {
strm->msg = (char *)"invalid literal/length code";
state->mode = BAD;
break;
}
} while (in < last && out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
in -= len;
bits -= len << 3;
hold &= (1U << bits) - 1;
/* update state and return */
strm->next_in = in + OFF;
strm->next_out = out + OFF;
strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
strm->avail_out = (unsigned)(out < end ?
257 + (end - out) : 257 - (out - end));
state->hold = hold;
state->bits = bits;
return;
}
Commit Message: Use post-increment only in inffast.c.
An old inffast.c optimization turns out to not be optimal anymore
with modern compilers, and furthermore was not compliant with the
C standard, for which decrementing a pointer before its allocated
memory is undefined. Per the recommendation of a security audit of
the zlib code by Trail of Bits and TrustInSoft, in support of the
Mozilla Foundation, this "optimization" was removed, in order to
avoid the possibility of undefined behavior.
CWE ID: CWE-189 | void ZLIB_INTERNAL inflate_fast(strm, start)
z_streamp strm;
unsigned start; /* inflate()'s starting value for strm->avail_out */
{
struct inflate_state FAR *state;
z_const unsigned char FAR *in; /* local strm->next_in */
z_const unsigned char FAR *last; /* have enough input while in < last */
unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */
code const FAR *lcode; /* local strm->lencode */
code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */
code here; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */
unsigned dist; /* match distance */
unsigned char FAR *from; /* where to copy match from */
/* copy state to local variables */
state = (struct inflate_state FAR *)strm->state;
in = strm->next_in;
last = in + (strm->avail_in - 5);
out = strm->next_out;
beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize;
whave = state->whave;
wnext = state->wnext;
window = state->window;
hold = state->hold;
bits = state->bits;
lcode = state->lencode;
dcode = state->distcode;
lmask = (1U << state->lenbits) - 1;
dmask = (1U << state->distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
do {
if (bits < 15) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op == 0) { /* literal */
Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", here.val));
*out++ = (unsigned char)(here.val);
}
else if (op & 16) { /* length base */
len = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
len += (unsigned)hold & ((1U << op) - 1);
hold >>= op;
bits -= op;
}
Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op & 16) { /* distance base */
dist = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
}
dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op;
bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist));
op = (unsigned)(out - beg); /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state->sane) {
strm->msg =
(char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (len <= op - whave) {
do {
*out++ = 0;
} while (--len);
continue;
}
len -= op - whave;
do {
*out++ = 0;
} while (--op > whave);
if (op == 0) {
from = out - dist;
do {
*out++ = *from++;
} while (--len);
continue;
}
#endif
}
from = window;
if (wnext == 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = window;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
while (len > 2) {
*out++ = *from++;
*out++ = *from++;
*out++ = *from++;
len -= 3;
}
if (len) {
*out++ = *from++;
if (len > 1)
*out++ = *from++;
}
}
else {
from = out - dist; /* copy direct from output */
do { /* minimum length is three */
*out++ = *from++;
*out++ = *from++;
*out++ = *from++;
len -= 3;
} while (len > 2);
if (len) {
*out++ = *from++;
if (len > 1)
*out++ = *from++;
}
}
}
else if ((op & 64) == 0) { /* 2nd level distance code */
here = dcode[here.val + (hold & ((1U << op) - 1))];
goto dodist;
}
else {
strm->msg = (char *)"invalid distance code";
state->mode = BAD;
break;
}
}
else if ((op & 64) == 0) { /* 2nd level length code */
here = lcode[here.val + (hold & ((1U << op) - 1))];
goto dolen;
}
else if (op & 32) { /* end-of-block */
Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE;
break;
}
else {
strm->msg = (char *)"invalid literal/length code";
state->mode = BAD;
break;
}
} while (in < last && out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
in -= len;
bits -= len << 3;
hold &= (1U << bits) - 1;
/* update state and return */
strm->next_in = in;
strm->next_out = out;
strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
strm->avail_out = (unsigned)(out < end ?
257 + (end - out) : 257 - (out - end));
state->hold = hold;
state->bits = bits;
return;
}
| 168,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
return image_transform_png_set_expand_add(this, that, colour_type,
bit_depth);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
#if PNG_LIBPNG_VER < 10700
return image_transform_png_set_expand_add(this, that, colour_type,
bit_depth);
#else
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* This should do nothing unless the color type is gray and the bit depth is
* less than 8:
*/
return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
#endif /* 1.7 or later */
}
| 173,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void Sp_search(js_State *J)
{
js_Regexp *re;
const char *text;
Resub m;
text = checkstring(J, 0);
if (js_isregexp(J, 1))
js_copy(J, 1);
else if (js_isundefined(J, 1))
js_newregexp(J, "", 0);
else
js_newregexp(J, js_tostring(J, 1), 0);
re = js_toregexp(J, -1);
if (!js_regexec(re->prog, text, &m, 0))
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
else
js_pushnumber(J, -1);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400 | static void Sp_search(js_State *J)
{
js_Regexp *re;
const char *text;
Resub m;
text = checkstring(J, 0);
if (js_isregexp(J, 1))
js_copy(J, 1);
else if (js_isundefined(J, 1))
js_newregexp(J, "", 0);
else
js_newregexp(J, js_tostring(J, 1), 0);
re = js_toregexp(J, -1);
if (!js_doregexec(J, re->prog, text, &m, 0))
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
else
js_pushnumber(J, -1);
}
| 169,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
MaybeReattachToRenderFrame();
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
agent_ptr_.reset();
render_frame_alive_ = true;
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
session->SetRenderer(frame_host ? frame_host->GetProcess() : nullptr,
frame_host);
}
MaybeReattachToRenderFrame();
}
}
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 RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
MaybeReattachToRenderFrame();
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
agent_ptr_.reset();
render_frame_alive_ = true;
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1,
frame_host);
}
MaybeReattachToRenderFrame();
}
}
| 172,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
PadContext *s = inlink->dst->priv;
AVFrame *out;
int needs_copy = frame_needs_copy(s, in);
if (needs_copy) {
av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
out = ff_get_video_buffer(inlink->dst->outputs[0],
FFMAX(inlink->w, s->w),
FFMAX(inlink->h, s->h));
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
} else {
int i;
out = in;
for (i = 0; i < 4 && out->data[i]; i++) {
int hsub = s->draw.hsub[i];
int vsub = s->draw.vsub[i];
out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +
(s->y >> vsub) * out->linesize[i];
}
}
/* top bar */
if (s->y) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, 0, s->w, s->y);
}
/* bottom bar */
if (s->h > s->y + s->in_h) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);
}
/* left border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
0, s->y, s->x, in->height);
if (needs_copy) {
ff_copy_rectangle2(&s->draw,
out->data, out->linesize, in->data, in->linesize,
s->x, s->y, 0, 0, in->width, in->height);
}
/* right border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
s->x + s->in_w, s->y, s->w - s->x - s->in_w,
in->height);
out->width = s->w;
out->height = s->h;
if (in != out)
av_frame_free(&in);
return ff_filter_frame(inlink->dst->outputs[0], out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
PadContext *s = inlink->dst->priv;
AVFrame *out;
int needs_copy = frame_needs_copy(s, in);
if (needs_copy) {
av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
out = ff_get_video_buffer(inlink->dst->outputs[0],
FFMAX(inlink->w, s->w),
FFMAX(inlink->h, s->h));
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
} else {
int i;
out = in;
for (i = 0; i < 4 && out->data[i] && out->linesize[i]; i++) {
int hsub = s->draw.hsub[i];
int vsub = s->draw.vsub[i];
out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +
(s->y >> vsub) * out->linesize[i];
}
}
/* top bar */
if (s->y) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, 0, s->w, s->y);
}
/* bottom bar */
if (s->h > s->y + s->in_h) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);
}
/* left border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
0, s->y, s->x, in->height);
if (needs_copy) {
ff_copy_rectangle2(&s->draw,
out->data, out->linesize, in->data, in->linesize,
s->x, s->y, 0, 0, in->width, in->height);
}
/* right border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
s->x + s->in_w, s->y, s->w - s->x - s->in_w,
in->height);
out->width = s->w;
out->height = s->h;
if (in != out)
av_frame_free(&in);
return ff_filter_frame(inlink->dst->outputs[0], out);
}
| 166,005 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_video::empty_this_buffer_proxy(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
(void)hComp;
OMX_U8 *pmem_data_buf = NULL;
int push_cnt = 0;
unsigned nBufIndex = 0;
OMX_ERRORTYPE ret = OMX_ErrorNone;
encoder_media_buffer_type *media_buffer = NULL;
#ifdef _MSM8974_
int fd = 0;
#endif
DEBUG_PRINT_LOW("ETBProxy: buffer->pBuffer[%p]", buffer->pBuffer);
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid buffer[%p]", buffer);
return OMX_ErrorBadParameter;
}
if (meta_mode_enable && !mUsesColorConversion) {
bool met_error = false;
nBufIndex = buffer - meta_buffer_hdr;
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid meta-bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
media_buffer = (encoder_media_buffer_type *)meta_buffer_hdr[nBufIndex].pBuffer;
if (media_buffer) {
if (media_buffer->buffer_type != kMetadataBufferTypeCameraSource &&
media_buffer->buffer_type != kMetadataBufferTypeGrallocSource) {
met_error = true;
} else {
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
if (media_buffer->meta_handle == NULL)
met_error = true;
else if ((media_buffer->meta_handle->numFds != 1 &&
media_buffer->meta_handle->numInts != 2))
met_error = true;
}
}
} else
met_error = true;
if (met_error) {
DEBUG_PRINT_ERROR("ERROR: Unkown source/metahandle in ETB call");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else {
nBufIndex = buffer - ((OMX_BUFFERHEADERTYPE *)m_inp_mem_ptr);
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
}
pending_input_buffers++;
if (input_flush_progress == true) {
post_event ((unsigned long)buffer,0,
OMX_COMPONENT_GENERATE_EBD);
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Input flush in progress");
return OMX_ErrorNone;
}
#ifdef _MSM8974_
if (!meta_mode_enable) {
fd = m_pInput_pmem[nBufIndex].fd;
}
#endif
#ifdef _ANDROID_ICS_
if (meta_mode_enable && !mUseProxyColorFormat) {
struct pmem Input_pmem_info;
if (!media_buffer) {
DEBUG_PRINT_ERROR("%s: invalid media_buffer",__FUNCTION__);
return OMX_ErrorBadParameter;
}
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = media_buffer->meta_handle->data[0];
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = media_buffer->meta_handle->data[1];
Input_pmem_info.size = media_buffer->meta_handle->data[2];
DEBUG_PRINT_LOW("ETB (meta-Camera) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
} else {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = handle->fd;
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = 0;
Input_pmem_info.size = handle->size;
DEBUG_PRINT_LOW("ETB (meta-gralloc) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
}
if (dev_use_buf(&Input_pmem_info,PORT_INDEX_IN,0) != true) {
DEBUG_PRINT_ERROR("ERROR: in dev_use_buf");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (meta_mode_enable && !mUsesColorConversion) {
if (media_buffer->buffer_type == kMetadataBufferTypeGrallocSource) {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
fd = handle->fd;
DEBUG_PRINT_LOW("ETB (opaque-gralloc) fd = %d, size = %d",
fd, handle->size);
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid bufferType for buffer with Opaque"
" color format");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (input_use_buffer && !m_use_input_pmem)
#else
if (input_use_buffer && !m_use_input_pmem)
#endif
{
DEBUG_PRINT_LOW("Heap UseBuffer case, so memcpy the data");
pmem_data_buf = (OMX_U8 *)m_pInput_pmem[nBufIndex].buffer;
memcpy (pmem_data_buf, (buffer->pBuffer + buffer->nOffset),
buffer->nFilledLen);
DEBUG_PRINT_LOW("memcpy() done in ETBProxy for i/p Heap UseBuf");
} else if (mUseProxyColorFormat) {
fd = m_pInput_pmem[nBufIndex].fd;
DEBUG_PRINT_LOW("ETB (color-converted) fd = %d, size = %u",
fd, (unsigned int)buffer->nFilledLen);
} else if (m_sInPortDef.format.video.eColorFormat ==
OMX_COLOR_FormatYUV420SemiPlanar) {
if (!dev_color_align(buffer, m_sInPortDef.format.video.nFrameWidth,
m_sInPortDef.format.video.nFrameHeight)) {
DEBUG_PRINT_ERROR("Failed to adjust buffer color");
post_event((unsigned long)buffer, 0, OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorUndefined;
}
}
#ifdef _MSM8974_
if (dev_empty_buf(buffer, pmem_data_buf,nBufIndex,fd) != true)
#else
if (dev_empty_buf(buffer, pmem_data_buf,0,0) != true)
#endif
{
DEBUG_PRINT_ERROR("ERROR: ETBProxy: dev_empty_buf failed");
#ifdef _ANDROID_ICS_
omx_release_meta_buffer(buffer);
#endif
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
/*Generate an async error and move to invalid state*/
pending_input_buffers--;
if (hw_overload) {
return OMX_ErrorInsufficientResources;
}
return OMX_ErrorBadParameter;
}
return ret;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27903498
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVenc problem #3)
CRs-Fixed: 1010088
Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3
CWE ID: | OMX_ERRORTYPE omx_video::empty_this_buffer_proxy(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
(void)hComp;
OMX_U8 *pmem_data_buf = NULL;
int push_cnt = 0;
unsigned nBufIndex = 0;
OMX_ERRORTYPE ret = OMX_ErrorNone;
encoder_media_buffer_type *media_buffer = NULL;
#ifdef _MSM8974_
int fd = 0;
#endif
DEBUG_PRINT_LOW("ETBProxy: buffer->pBuffer[%p]", buffer->pBuffer);
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid buffer[%p]", buffer);
return OMX_ErrorBadParameter;
}
if (meta_mode_enable && !mUsesColorConversion) {
bool met_error = false;
nBufIndex = buffer - meta_buffer_hdr;
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid meta-bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
media_buffer = (encoder_media_buffer_type *)meta_buffer_hdr[nBufIndex].pBuffer;
if (media_buffer) {
if (media_buffer->buffer_type != kMetadataBufferTypeCameraSource &&
media_buffer->buffer_type != kMetadataBufferTypeGrallocSource) {
met_error = true;
} else {
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
if (media_buffer->meta_handle == NULL)
met_error = true;
else if ((media_buffer->meta_handle->numFds != 1 &&
media_buffer->meta_handle->numInts != 2))
met_error = true;
}
}
} else
met_error = true;
if (met_error) {
DEBUG_PRINT_ERROR("ERROR: Unkown source/metahandle in ETB call");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else {
nBufIndex = buffer - ((OMX_BUFFERHEADERTYPE *)m_inp_mem_ptr);
if (nBufIndex >= m_sInPortDef.nBufferCountActual) {
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Invalid bufIndex = %u", nBufIndex);
return OMX_ErrorBadParameter;
}
}
pending_input_buffers++;
if (input_flush_progress == true) {
post_event ((unsigned long)buffer,0,
OMX_COMPONENT_GENERATE_EBD);
DEBUG_PRINT_ERROR("ERROR: ETBProxy: Input flush in progress");
return OMX_ErrorNone;
}
#ifdef _MSM8974_
if (!meta_mode_enable) {
fd = m_pInput_pmem[nBufIndex].fd;
}
#endif
#ifdef _ANDROID_ICS_
if (meta_mode_enable && !mUseProxyColorFormat) {
struct pmem Input_pmem_info;
if (!media_buffer) {
DEBUG_PRINT_ERROR("%s: invalid media_buffer",__FUNCTION__);
return OMX_ErrorBadParameter;
}
if (media_buffer->buffer_type == kMetadataBufferTypeCameraSource) {
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = media_buffer->meta_handle->data[0];
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = media_buffer->meta_handle->data[1];
Input_pmem_info.size = media_buffer->meta_handle->data[2];
DEBUG_PRINT_LOW("ETB (meta-Camera) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
} else {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
Input_pmem_info.buffer = media_buffer;
Input_pmem_info.fd = handle->fd;
#ifdef _MSM8974_
fd = Input_pmem_info.fd;
#endif
Input_pmem_info.offset = 0;
Input_pmem_info.size = handle->size;
DEBUG_PRINT_LOW("ETB (meta-gralloc) fd = %d, offset = %d, size = %d",
Input_pmem_info.fd, Input_pmem_info.offset,
Input_pmem_info.size);
}
if (dev_use_buf(&Input_pmem_info,PORT_INDEX_IN,0) != true) {
DEBUG_PRINT_ERROR("ERROR: in dev_use_buf");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (meta_mode_enable && !mUsesColorConversion) {
if (media_buffer->buffer_type == kMetadataBufferTypeGrallocSource) {
private_handle_t *handle = (private_handle_t *)media_buffer->meta_handle;
fd = handle->fd;
DEBUG_PRINT_LOW("ETB (opaque-gralloc) fd = %d, size = %d",
fd, handle->size);
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid bufferType for buffer with Opaque"
" color format");
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorBadParameter;
}
} else if (input_use_buffer && !m_use_input_pmem)
#else
if (input_use_buffer && !m_use_input_pmem)
#endif
{
DEBUG_PRINT_LOW("Heap UseBuffer case, so memcpy the data");
auto_lock l(m_lock);
pmem_data_buf = (OMX_U8 *)m_pInput_pmem[nBufIndex].buffer;
if (pmem_data_buf) {
memcpy (pmem_data_buf, (buffer->pBuffer + buffer->nOffset),
buffer->nFilledLen);
}
DEBUG_PRINT_LOW("memcpy() done in ETBProxy for i/p Heap UseBuf");
} else if (mUseProxyColorFormat) {
fd = m_pInput_pmem[nBufIndex].fd;
DEBUG_PRINT_LOW("ETB (color-converted) fd = %d, size = %u",
fd, (unsigned int)buffer->nFilledLen);
} else if (m_sInPortDef.format.video.eColorFormat ==
OMX_COLOR_FormatYUV420SemiPlanar) {
if (!dev_color_align(buffer, m_sInPortDef.format.video.nFrameWidth,
m_sInPortDef.format.video.nFrameHeight)) {
DEBUG_PRINT_ERROR("Failed to adjust buffer color");
post_event((unsigned long)buffer, 0, OMX_COMPONENT_GENERATE_EBD);
return OMX_ErrorUndefined;
}
}
#ifdef _MSM8974_
if (dev_empty_buf(buffer, pmem_data_buf,nBufIndex,fd) != true)
#else
if (dev_empty_buf(buffer, pmem_data_buf,0,0) != true)
#endif
{
DEBUG_PRINT_ERROR("ERROR: ETBProxy: dev_empty_buf failed");
#ifdef _ANDROID_ICS_
omx_release_meta_buffer(buffer);
#endif
post_event ((unsigned long)buffer,0,OMX_COMPONENT_GENERATE_EBD);
/*Generate an async error and move to invalid state*/
pending_input_buffers--;
if (hw_overload) {
return OMX_ErrorInsufficientResources;
}
return OMX_ErrorBadParameter;
}
return ret;
}
| 173,746 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
asocket* s;
asocket* result = NULL;
adb_mutex_lock(&socket_list_lock);
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->id != local_id) {
continue;
}
if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
result = s;
}
break;
}
adb_mutex_unlock(&socket_list_lock);
return result;
}
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 | asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
asocket* s;
asocket* result = NULL;
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->id != local_id) {
continue;
}
if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
result = s;
}
break;
}
return result;
}
| 174,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static double ipow( double n, int exp )
{
double r;
if ( exp < 0 )
return 1.0 / ipow( n, -exp );
r = 1;
while ( exp > 0 ) {
if ( exp & 1 )
r *= n;
exp >>= 1;
n *= n;
}
return r;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static double ipow( double n, int exp )
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
if (*num=='-') sign=-1,num++; /* Has sign? */
if (*num=='0') num++; /* is zero */
if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
if (*num=='e' || *num=='E') /* Exponent? */
{ num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
}
| 167,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void serveloop(GArray* servers) {
struct sockaddr_storage addrin;
socklen_t addrinlen=sizeof(addrin);
int i;
int max;
fd_set mset;
fd_set rset;
/*
* Set up the master fd_set. The set of descriptors we need
* to select() for never changes anyway and it buys us a *lot*
* of time to only build this once. However, if we ever choose
* to not fork() for clients anymore, we may have to revisit
* this.
*/
max=0;
FD_ZERO(&mset);
for(i=0;i<servers->len;i++) {
int sock;
if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) {
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
}
for(i=0;i<modernsocks->len;i++) {
int sock = g_array_index(modernsocks, int, i);
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
for(;;) {
/* SIGHUP causes the root server process to reconfigure
* itself and add new export servers for each newly
* found export configuration group, i.e. spawn new
* server processes for each previously non-existent
* export. This does not alter old runtime configuration
* but just appends new exports. */
if (is_sighup_caught) {
int n;
GError *gerror = NULL;
msg(LOG_INFO, "reconfiguration request received");
is_sighup_caught = 0; /* Reset to allow catching
* it again. */
n = append_new_servers(servers, &gerror);
if (n == -1)
msg(LOG_ERR, "failed to append new servers: %s",
gerror->message);
for (i = servers->len - n; i < servers->len; ++i) {
const SERVER server = g_array_index(servers,
SERVER, i);
if (server.socket >= 0) {
FD_SET(server.socket, &mset);
max = server.socket > max ? server.socket : max;
}
msg(LOG_INFO, "reconfigured new server: %s",
server.servename);
}
}
memcpy(&rset, &mset, sizeof(fd_set));
if(select(max+1, &rset, NULL, NULL, NULL)>0) {
int net;
DEBUG("accept, ");
for(i=0; i < modernsocks->len; i++) {
int sock = g_array_index(modernsocks, int, i);
if(!FD_ISSET(sock, &rset)) {
continue;
}
CLIENT *client;
if((net=accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
err_nonfatal("accept: %m");
continue;
}
client = negotiate(net, NULL, servers, NEG_INIT | NEG_MODERN);
if(!client) {
close(net);
continue;
}
handle_connection(servers, net, client->server, client);
}
for(i=0; i < servers->len; i++) {
SERVER *serve;
serve=&(g_array_index(servers, SERVER, i));
if(serve->socket < 0) {
continue;
}
if(FD_ISSET(serve->socket, &rset)) {
if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
err_nonfatal("accept: %m");
continue;
}
handle_connection(servers, net, serve, NULL);
}
}
}
}
}
Commit Message: nbd-server: handle modern-style negotiation in a child process
Previously, the modern style negotiation was carried out in the root
server (listener) process before forking the actual client handler. This
made it possible for a malfunctioning or evil client to terminate the
root process simply by querying a non-existent export or aborting in the
middle of the negotation process (caused SIGPIPE in the server).
This commit moves the negotiation process to the child to keep the root
process up and running no matter what happens during the negotiation.
See http://sourceforge.net/mailarchive/message.php?msg_id=30410146
Signed-off-by: Tuomas Räsänen <[email protected]>
CWE ID: CWE-399 | void serveloop(GArray* servers) {
struct sockaddr_storage addrin;
socklen_t addrinlen=sizeof(addrin);
int i;
int max;
fd_set mset;
fd_set rset;
/*
* Set up the master fd_set. The set of descriptors we need
* to select() for never changes anyway and it buys us a *lot*
* of time to only build this once. However, if we ever choose
* to not fork() for clients anymore, we may have to revisit
* this.
*/
max=0;
FD_ZERO(&mset);
for(i=0;i<servers->len;i++) {
int sock;
if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) {
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
}
for(i=0;i<modernsocks->len;i++) {
int sock = g_array_index(modernsocks, int, i);
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
for(;;) {
/* SIGHUP causes the root server process to reconfigure
* itself and add new export servers for each newly
* found export configuration group, i.e. spawn new
* server processes for each previously non-existent
* export. This does not alter old runtime configuration
* but just appends new exports. */
if (is_sighup_caught) {
int n;
GError *gerror = NULL;
msg(LOG_INFO, "reconfiguration request received");
is_sighup_caught = 0; /* Reset to allow catching
* it again. */
n = append_new_servers(servers, &gerror);
if (n == -1)
msg(LOG_ERR, "failed to append new servers: %s",
gerror->message);
for (i = servers->len - n; i < servers->len; ++i) {
const SERVER server = g_array_index(servers,
SERVER, i);
if (server.socket >= 0) {
FD_SET(server.socket, &mset);
max = server.socket > max ? server.socket : max;
}
msg(LOG_INFO, "reconfigured new server: %s",
server.servename);
}
}
memcpy(&rset, &mset, sizeof(fd_set));
if(select(max+1, &rset, NULL, NULL, NULL)>0) {
DEBUG("accept, ");
for(i=0; i < modernsocks->len; i++) {
int sock = g_array_index(modernsocks, int, i);
if(!FD_ISSET(sock, &rset)) {
continue;
}
handle_modern_connection(servers, sock);
}
for(i=0; i < servers->len; i++) {
int net;
SERVER *serve;
serve=&(g_array_index(servers, SERVER, i));
if(serve->socket < 0) {
continue;
}
if(FD_ISSET(serve->socket, &rset)) {
if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
err_nonfatal("accept: %m");
continue;
}
handle_connection(servers, net, serve, NULL);
}
}
}
}
}
| 166,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
}
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416 | static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
seqf->private = NULL;
}
}
| 166,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SocketStream::Connect() {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
if (context_.get()) {
context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
proxy_ssl_config_ = server_ssl_config_;
}
CheckPrivacyMode();
DCHECK_EQ(next_state_, STATE_NONE);
AddRef(); // Released in Finish()
next_state_ = STATE_BEFORE_CONNECT;
net_log_.BeginEvent(
NetLog::TYPE_SOCKET_STREAM_CONNECT,
NetLog::StringCallback("url", &url_.possibly_invalid_spec()));
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void SocketStream::Connect() {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
if (context_) {
context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
proxy_ssl_config_ = server_ssl_config_;
}
CheckPrivacyMode();
DCHECK_EQ(next_state_, STATE_NONE);
AddRef(); // Released in Finish()
next_state_ = STATE_BEFORE_CONNECT;
net_log_.BeginEvent(
NetLog::TYPE_SOCKET_STREAM_CONNECT,
NetLog::StringCallback("url", &url_.possibly_invalid_spec()));
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
}
| 171,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
u64 value;
u8 freg;
int flag;
struct fpustate *f = FPUSTATE;
if (tstate & TSTATE_PRIV)
die_if_kernel("stdfmna from kernel", regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
int asi = decode_asi(insn, regs);
freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
value = 0;
flag = (freg < 32) ? FPRS_DL : FPRS_DU;
if ((asi > ASI_SNFL) ||
(asi < ASI_P))
goto daex;
save_and_clear_fpu();
if (current_thread_info()->fpsaved[0] & flag)
value = *(u64 *)&f->regs[freg];
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
value = __swab64p(&value); break;
default: goto daex;
}
if (put_user (value >> 32, (u32 __user *) sfar) ||
__put_user ((u32)value, (u32 __user *)(sfar + 4)))
goto daex;
} else {
daex:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, sfar, sfsr);
else
spitfire_data_access_exception(regs, sfsr, sfar);
return;
}
advance(regs);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | void handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
u64 value;
u8 freg;
int flag;
struct fpustate *f = FPUSTATE;
if (tstate & TSTATE_PRIV)
die_if_kernel("stdfmna from kernel", regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, sfar);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
int asi = decode_asi(insn, regs);
freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
value = 0;
flag = (freg < 32) ? FPRS_DL : FPRS_DU;
if ((asi > ASI_SNFL) ||
(asi < ASI_P))
goto daex;
save_and_clear_fpu();
if (current_thread_info()->fpsaved[0] & flag)
value = *(u64 *)&f->regs[freg];
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
value = __swab64p(&value); break;
default: goto daex;
}
if (put_user (value >> 32, (u32 __user *) sfar) ||
__put_user ((u32)value, (u32 __user *)(sfar + 4)))
goto daex;
} else {
daex:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, sfar, sfsr);
else
spitfire_data_access_exception(regs, sfsr, sfar);
return;
}
advance(regs);
}
| 165,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SimpleBlock::SimpleBlock(
Cluster* pCluster,
long idx,
long long start,
long long size) :
BlockEntry(pCluster, idx),
m_block(start, size, 0)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | SimpleBlock::SimpleBlock(
| 174,444 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateTrue( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_True;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateTrue( void )
| 167,280 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190 | void CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
data_use_measurement::DataUseUserData::AttachToFetcher(
url_fetcher_.get(),
data_use_measurement::DataUseUserData::CAPTIVE_PORTAL);
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
| 172,017 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
int ystart, int xend, int yend)
{
jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart,
jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend)
{
jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
}
| 168,707 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ReadUserLogState::SetState( const ReadUserLog::FileState &state )
{
const ReadUserLogFileState::FileState *istate;
if ( !convertState(state, istate) ) {
return false;
}
if ( strcmp( istate->m_signature, FileStateSignature ) ) {
m_init_error = true;
return false;
}
if ( istate->m_version != FILESTATE_VERSION ) {
m_init_error = true;
return false;
}
m_base_path = istate->m_base_path;
m_max_rotations = istate->m_max_rotations;
Rotation( istate->m_rotation, false, true );
m_log_type = istate->m_log_type;
m_uniq_id = istate->m_uniq_id;
m_sequence = istate->m_sequence;
m_stat_buf.st_ino = istate->m_inode;
m_stat_buf.st_ctime = istate->m_ctime;
m_stat_buf.st_size = istate->m_size.asint;
m_stat_valid = true;
m_offset = istate->m_offset.asint;
m_event_num = istate->m_event_num.asint;
m_log_position = istate->m_log_position.asint;
m_log_record = istate->m_log_record.asint;
m_update_time = istate->m_update_time;
m_initialized = true;
MyString str;
GetStateString( str, "Restored reader state" );
dprintf( D_FULLDEBUG, str.Value() );
return true;
}
Commit Message:
CWE ID: CWE-134 | ReadUserLogState::SetState( const ReadUserLog::FileState &state )
{
const ReadUserLogFileState::FileState *istate;
if ( !convertState(state, istate) ) {
return false;
}
if ( strcmp( istate->m_signature, FileStateSignature ) ) {
m_init_error = true;
return false;
}
if ( istate->m_version != FILESTATE_VERSION ) {
m_init_error = true;
return false;
}
m_base_path = istate->m_base_path;
m_max_rotations = istate->m_max_rotations;
Rotation( istate->m_rotation, false, true );
m_log_type = istate->m_log_type;
m_uniq_id = istate->m_uniq_id;
m_sequence = istate->m_sequence;
m_stat_buf.st_ino = istate->m_inode;
m_stat_buf.st_ctime = istate->m_ctime;
m_stat_buf.st_size = istate->m_size.asint;
m_stat_valid = true;
m_offset = istate->m_offset.asint;
m_event_num = istate->m_event_num.asint;
m_log_position = istate->m_log_position.asint;
m_log_record = istate->m_log_record.asint;
m_update_time = istate->m_update_time;
m_initialized = true;
MyString str;
GetStateString( str, "Restored reader state" );
dprintf( D_FULLDEBUG, "%s", str.Value() );
return true;
}
| 165,387 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ResourceDispatcherHostImpl::AcceptAuthRequest(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info))
return false;
if (!auth_info->is_proxy) {
HttpAuthResourceType resource_type =
HttpAuthResourceTypeOf(loader->request());
UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource",
resource_type,
HTTP_AUTH_RESOURCE_LAST);
if (resource_type == HTTP_AUTH_RESOURCE_BLOCKED_CROSS)
return false;
}
return true;
}
Commit Message: Revert cross-origin auth prompt blocking.
BUG=174129
Review URL: https://chromiumcodereview.appspot.com/12183030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ResourceDispatcherHostImpl::AcceptAuthRequest(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info))
return false;
if (!auth_info->is_proxy) {
HttpAuthResourceType resource_type =
HttpAuthResourceTypeOf(loader->request());
UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource",
resource_type,
HTTP_AUTH_RESOURCE_LAST);
// TODO(tsepez): Return false on HTTP_AUTH_RESOURCE_BLOCKED_CROSS.
// The code once did this, but was changed due to http://crbug.com/174129.
// http://crbug.com/174179 has been filed to track this issue.
}
return true;
}
| 171,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void uipc_read_task(void *arg)
{
int ch_id;
int result;
UNUSED(arg);
prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0);
raise_priority_a2dp(TASK_UIPC_READ);
while (uipc_main.running)
{
uipc_main.read_set = uipc_main.active_set;
result = select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL);
if (result == 0)
{
BTIF_TRACE_EVENT("select timeout");
continue;
}
else if (result < 0)
{
BTIF_TRACE_EVENT("select failed %s", strerror(errno));
continue;
}
UIPC_LOCK();
/* clear any wakeup interrupt */
uipc_check_interrupt_locked();
/* check pending task events */
uipc_check_task_flags_locked();
/* make sure we service audio channel first */
uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO);
/* check for other connections */
for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++)
{
if (ch_id != UIPC_CH_ID_AV_AUDIO)
uipc_check_fd_locked(ch_id);
}
UIPC_UNLOCK();
}
BTIF_TRACE_EVENT("UIPC READ THREAD EXITING");
uipc_main_cleanup();
uipc_main.tid = 0;
BTIF_TRACE_EVENT("UIPC READ THREAD DONE");
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void uipc_read_task(void *arg)
{
int ch_id;
int result;
UNUSED(arg);
prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0);
raise_priority_a2dp(TASK_UIPC_READ);
while (uipc_main.running)
{
uipc_main.read_set = uipc_main.active_set;
result = TEMP_FAILURE_RETRY(select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL));
if (result == 0)
{
BTIF_TRACE_EVENT("select timeout");
continue;
}
else if (result < 0)
{
BTIF_TRACE_EVENT("select failed %s", strerror(errno));
continue;
}
UIPC_LOCK();
/* clear any wakeup interrupt */
uipc_check_interrupt_locked();
/* check pending task events */
uipc_check_task_flags_locked();
/* make sure we service audio channel first */
uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO);
/* check for other connections */
for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++)
{
if (ch_id != UIPC_CH_ID_AV_AUDIO)
uipc_check_fd_locked(ch_id);
}
UIPC_UNLOCK();
}
BTIF_TRACE_EVENT("UIPC READ THREAD EXITING");
uipc_main_cleanup();
uipc_main.tid = 0;
BTIF_TRACE_EVENT("UIPC READ THREAD DONE");
}
| 173,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
| 167,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid
&& !(tsk->flags & PF_SIGNALED)
&& atomic_read(&mm->mm_users) > 1) {
u32 __user * tidptr = tsk->clear_child_tid;
tsk->clear_child_tid = NULL;
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tidptr);
sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);
}
}
Commit Message: Move "exit_robust_list" into mm_release()
We don't want to get rid of the futexes just at exit() time, we want to
drop them when doing an execve() too, since that gets rid of the
previous VM image too.
Doing it at mm_release() time means that we automatically always do it
when we disassociate a VM map from the task.
Reported-by: [email protected]
Cc: Andrew Morton <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: Alex Efros <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any futexes when releasing the mm */
#ifdef CONFIG_FUTEX
if (unlikely(tsk->robust_list))
exit_robust_list(tsk);
#ifdef CONFIG_COMPAT
if (unlikely(tsk->compat_robust_list))
compat_exit_robust_list(tsk);
#endif
#endif
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid
&& !(tsk->flags & PF_SIGNALED)
&& atomic_read(&mm->mm_users) > 1) {
u32 __user * tidptr = tsk->clear_child_tid;
tsk->clear_child_tid = NULL;
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tidptr);
sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);
}
}
| 165,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: yyparse (void *yyscanner, YR_COMPILER* compiler)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, yyscanner, compiler);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 8:
#line 230 "grammar.y" /* yacc.c:1646 */
{
int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF(result != ERROR_SUCCESS);
}
#line 1661 "grammar.c" /* yacc.c:1646 */
break;
case 9:
#line 242 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1(
yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string));
ERROR_IF(rule == NULL);
(yyval.rule) = rule;
}
#line 1674 "grammar.c" /* yacc.c:1646 */
break;
case 10:
#line 251 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = (yyvsp[-4].rule); // rule created in phase 1
rule->tags = (yyvsp[-3].c_string);
rule->metas = (yyvsp[-1].meta);
rule->strings = (yyvsp[0].string);
}
#line 1686 "grammar.c" /* yacc.c:1646 */
break;
case 11:
#line 259 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = (yyvsp[-7].rule); // rule created in phase 1
compiler->last_result = yr_parser_reduce_rule_declaration_phase_2(
yyscanner, rule);
yr_free((yyvsp[-8].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 1701 "grammar.c" /* yacc.c:1646 */
break;
case 12:
#line 274 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = NULL;
}
#line 1709 "grammar.c" /* yacc.c:1646 */
break;
case 13:
#line 278 "grammar.y" /* yacc.c:1646 */
{
YR_META null_meta;
memset(&null_meta, 0xFF, sizeof(YR_META));
null_meta.type = META_TYPE_NULL;
compiler->last_result = yr_arena_write_data(
compiler->metas_arena,
&null_meta,
sizeof(YR_META),
NULL);
(yyval.meta) = (yyvsp[0].meta);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 1736 "grammar.c" /* yacc.c:1646 */
break;
case 14:
#line 305 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = NULL;
}
#line 1744 "grammar.c" /* yacc.c:1646 */
break;
case 15:
#line 309 "grammar.y" /* yacc.c:1646 */
{
YR_STRING null_string;
memset(&null_string, 0xFF, sizeof(YR_STRING));
null_string.g_flags = STRING_GFLAGS_NULL;
compiler->last_result = yr_arena_write_data(
compiler->strings_arena,
&null_string,
sizeof(YR_STRING),
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.string) = (yyvsp[0].string);
}
#line 1771 "grammar.c" /* yacc.c:1646 */
break;
case 17:
#line 340 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = 0; }
#line 1777 "grammar.c" /* yacc.c:1646 */
break;
case 18:
#line 341 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); }
#line 1783 "grammar.c" /* yacc.c:1646 */
break;
case 19:
#line 346 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = RULE_GFLAGS_PRIVATE; }
#line 1789 "grammar.c" /* yacc.c:1646 */
break;
case 20:
#line 347 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = RULE_GFLAGS_GLOBAL; }
#line 1795 "grammar.c" /* yacc.c:1646 */
break;
case 21:
#line 353 "grammar.y" /* yacc.c:1646 */
{
(yyval.c_string) = NULL;
}
#line 1803 "grammar.c" /* yacc.c:1646 */
break;
case 22:
#line 357 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, "", NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[0].c_string);
}
#line 1821 "grammar.c" /* yacc.c:1646 */
break;
case 23:
#line 375 "grammar.y" /* yacc.c:1646 */
{
char* identifier;
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = identifier;
}
#line 1838 "grammar.c" /* yacc.c:1646 */
break;
case 24:
#line 388 "grammar.y" /* yacc.c:1646 */
{
char* tag_name = (yyvsp[-1].c_string);
size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0;
while (tag_length > 0)
{
if (strcmp(tag_name, (yyvsp[0].c_string)) == 0)
{
yr_compiler_set_error_extra_info(compiler, tag_name);
compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER;
break;
}
tag_name = (char*) yr_arena_next_address(
yyget_extra(yyscanner)->sz_arena,
tag_name,
tag_length + 1);
tag_length = tag_name != NULL ? strlen(tag_name) : 0;
}
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[-1].c_string);
}
#line 1874 "grammar.c" /* yacc.c:1646 */
break;
case 25:
#line 424 "grammar.y" /* yacc.c:1646 */
{ (yyval.meta) = (yyvsp[0].meta); }
#line 1880 "grammar.c" /* yacc.c:1646 */
break;
case 26:
#line 425 "grammar.y" /* yacc.c:1646 */
{ (yyval.meta) = (yyvsp[-1].meta); }
#line 1886 "grammar.c" /* yacc.c:1646 */
break;
case 27:
#line 431 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string = (yyvsp[0].sized_string);
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_STRING,
(yyvsp[-2].c_string),
sized_string->c_string,
0);
yr_free((yyvsp[-2].c_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1906 "grammar.c" /* yacc.c:1646 */
break;
case 28:
#line 447 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_INTEGER,
(yyvsp[-2].c_string),
NULL,
(yyvsp[0].integer));
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1923 "grammar.c" /* yacc.c:1646 */
break;
case 29:
#line 460 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_INTEGER,
(yyvsp[-3].c_string),
NULL,
-(yyvsp[0].integer));
yr_free((yyvsp[-3].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1940 "grammar.c" /* yacc.c:1646 */
break;
case 30:
#line 473 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_BOOLEAN,
(yyvsp[-2].c_string),
NULL,
TRUE);
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1957 "grammar.c" /* yacc.c:1646 */
break;
case 31:
#line 486 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_BOOLEAN,
(yyvsp[-2].c_string),
NULL,
FALSE);
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1974 "grammar.c" /* yacc.c:1646 */
break;
case 32:
#line 502 "grammar.y" /* yacc.c:1646 */
{ (yyval.string) = (yyvsp[0].string); }
#line 1980 "grammar.c" /* yacc.c:1646 */
break;
case 33:
#line 503 "grammar.y" /* yacc.c:1646 */
{ (yyval.string) = (yyvsp[-1].string); }
#line 1986 "grammar.c" /* yacc.c:1646 */
break;
case 34:
#line 509 "grammar.y" /* yacc.c:1646 */
{
compiler->error_line = yyget_lineno(yyscanner);
}
#line 1994 "grammar.c" /* yacc.c:1646 */
break;
case 35:
#line 513 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string));
yr_free((yyvsp[-4].c_string));
yr_free((yyvsp[-1].sized_string));
ERROR_IF((yyval.string) == NULL);
compiler->error_line = 0;
}
#line 2009 "grammar.c" /* yacc.c:1646 */
break;
case 36:
#line 524 "grammar.y" /* yacc.c:1646 */
{
compiler->error_line = yyget_lineno(yyscanner);
}
#line 2017 "grammar.c" /* yacc.c:1646 */
break;
case 37:
#line 528 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string));
yr_free((yyvsp[-4].c_string));
yr_free((yyvsp[-1].sized_string));
ERROR_IF((yyval.string) == NULL);
compiler->error_line = 0;
}
#line 2033 "grammar.c" /* yacc.c:1646 */
break;
case 38:
#line 540 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string));
yr_free((yyvsp[-2].c_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF((yyval.string) == NULL);
}
#line 2047 "grammar.c" /* yacc.c:1646 */
break;
case 39:
#line 553 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = 0; }
#line 2053 "grammar.c" /* yacc.c:1646 */
break;
case 40:
#line 554 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); }
#line 2059 "grammar.c" /* yacc.c:1646 */
break;
case 41:
#line 559 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_WIDE; }
#line 2065 "grammar.c" /* yacc.c:1646 */
break;
case 42:
#line 560 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_ASCII; }
#line 2071 "grammar.c" /* yacc.c:1646 */
break;
case 43:
#line 561 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_NO_CASE; }
#line 2077 "grammar.c" /* yacc.c:1646 */
break;
case 44:
#line 562 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_FULL_WORD; }
#line 2083 "grammar.c" /* yacc.c:1646 */
break;
case 45:
#line 568 "grammar.y" /* yacc.c:1646 */
{
int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string));
if (var_index >= 0)
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner,
OP_PUSH_M,
LOOP_LOCAL_VARS * var_index,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
(yyval.expression).identifier = compiler->loop_identifier[var_index];
}
else
{
YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup(
compiler->objects_table, (yyvsp[0].c_string), NULL);
if (object == NULL)
{
char* ns = compiler->current_namespace->name;
object = (YR_OBJECT*) yr_hash_table_lookup(
compiler->objects_table, (yyvsp[0].c_string), ns);
}
if (object != NULL)
{
char* id;
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[0].c_string), &id);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_OBJ_LOAD,
id,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = object;
(yyval.expression).identifier = object->identifier;
}
else
{
YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup(
compiler->rules_table,
(yyvsp[0].c_string),
compiler->current_namespace->name);
if (rule != NULL)
{
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH_RULE,
rule,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
(yyval.expression).value.integer = UNDEFINED;
(yyval.expression).identifier = rule->identifier;
}
else
{
yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string));
compiler->last_result = ERROR_UNDEFINED_IDENTIFIER;
}
}
}
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2172 "grammar.c" /* yacc.c:1646 */
break;
case 46:
#line 653 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT* field = NULL;
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE)
{
field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string));
if (field != NULL)
{
char* ident;
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[0].c_string), &ident);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_OBJ_FIELD,
ident,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = field;
(yyval.expression).identifier = field->identifier;
}
else
{
yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string));
compiler->last_result = ERROR_INVALID_FIELD_NAME;
}
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-2].expression).identifier);
compiler->last_result = ERROR_NOT_A_STRUCTURE;
}
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2222 "grammar.c" /* yacc.c:1646 */
break;
case 47:
#line 699 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT_ARRAY* array;
YR_OBJECT_DICTIONARY* dict;
if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY)
{
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "array indexes must be of integer type");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(
yyscanner, OP_INDEX_ARRAY, NULL);
array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = array->prototype_item;
(yyval.expression).identifier = array->identifier;
}
else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY)
{
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING)
{
yr_compiler_set_error_extra_info(
compiler, "dictionary keys must be of string type");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(
yyscanner, OP_LOOKUP_DICT, NULL);
dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = dict->prototype_item;
(yyval.expression).identifier = dict->identifier;
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-3].expression).identifier);
compiler->last_result = ERROR_NOT_INDEXABLE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2283 "grammar.c" /* yacc.c:1646 */
break;
case 48:
#line 757 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT_FUNCTION* function;
char* args_fmt;
if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION)
{
compiler->last_result = yr_parser_check_types(
compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string));
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_CALL,
args_fmt,
NULL,
NULL);
function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = function->return_obj;
(yyval.expression).identifier = function->identifier;
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-3].expression).identifier);
compiler->last_result = ERROR_NOT_A_FUNCTION;
}
yr_free((yyvsp[-1].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2328 "grammar.c" /* yacc.c:1646 */
break;
case 49:
#line 801 "grammar.y" /* yacc.c:1646 */
{ (yyval.c_string) = yr_strdup(""); }
#line 2334 "grammar.c" /* yacc.c:1646 */
break;
case 50:
#line 802 "grammar.y" /* yacc.c:1646 */
{ (yyval.c_string) = (yyvsp[0].c_string); }
#line 2340 "grammar.c" /* yacc.c:1646 */
break;
case 51:
#line 807 "grammar.y" /* yacc.c:1646 */
{
(yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1);
switch((yyvsp[0].expression).type)
{
case EXPRESSION_TYPE_INTEGER:
strlcpy((yyval.c_string), "i", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_FLOAT:
strlcpy((yyval.c_string), "f", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_BOOLEAN:
strlcpy((yyval.c_string), "b", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_STRING:
strlcpy((yyval.c_string), "s", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_REGEXP:
strlcpy((yyval.c_string), "r", MAX_FUNCTION_ARGS);
break;
}
ERROR_IF((yyval.c_string) == NULL);
}
#line 2369 "grammar.c" /* yacc.c:1646 */
break;
case 52:
#line 832 "grammar.y" /* yacc.c:1646 */
{
if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS)
{
compiler->last_result = ERROR_TOO_MANY_ARGUMENTS;
}
else
{
switch((yyvsp[0].expression).type)
{
case EXPRESSION_TYPE_INTEGER:
strlcat((yyvsp[-2].c_string), "i", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_FLOAT:
strlcat((yyvsp[-2].c_string), "f", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_BOOLEAN:
strlcat((yyvsp[-2].c_string), "b", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_STRING:
strlcat((yyvsp[-2].c_string), "s", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_REGEXP:
strlcat((yyvsp[-2].c_string), "r", MAX_FUNCTION_ARGS);
break;
}
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[-2].c_string);
}
#line 2405 "grammar.c" /* yacc.c:1646 */
break;
case 53:
#line 868 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string = (yyvsp[0].sized_string);
RE* re;
RE_ERROR error;
int re_flags = 0;
if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE)
re_flags |= RE_FLAGS_NO_CASE;
if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL)
re_flags |= RE_FLAGS_DOT_ALL;
compiler->last_result = yr_re_compile(
sized_string->c_string,
re_flags,
compiler->re_code_arena,
&re,
&error);
yr_free((yyvsp[0].sized_string));
if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION)
yr_compiler_set_error_extra_info(compiler, error.message);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
re->root_node->forward_code,
NULL,
NULL);
yr_re_destroy(re);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_REGEXP;
}
#line 2451 "grammar.c" /* yacc.c:1646 */
break;
case 54:
#line 914 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING)
{
if ((yyvsp[0].expression).value.sized_string != NULL)
{
yywarning(yyscanner,
"Using literal string \"%s\" in a boolean operation.",
(yyvsp[0].expression).value.sized_string->c_string);
}
compiler->last_result = yr_parser_emit(
yyscanner, OP_STR_TO_BOOL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2474 "grammar.c" /* yacc.c:1646 */
break;
case 55:
#line 936 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2487 "grammar.c" /* yacc.c:1646 */
break;
case 56:
#line 945 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 0, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2500 "grammar.c" /* yacc.c:1646 */
break;
case 57:
#line 954 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "matches");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, "matches");
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit(
yyscanner,
OP_MATCHES,
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2519 "grammar.c" /* yacc.c:1646 */
break;
case 58:
#line 969 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "contains");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, "contains");
compiler->last_result = yr_parser_emit(
yyscanner, OP_CONTAINS, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2535 "grammar.c" /* yacc.c:1646 */
break;
case 59:
#line 981 "grammar.y" /* yacc.c:1646 */
{
int result = yr_parser_reduce_string_identifier(
yyscanner,
(yyvsp[0].c_string),
OP_FOUND,
UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2553 "grammar.c" /* yacc.c:1646 */
break;
case 60:
#line 995 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "at");
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer);
yr_free((yyvsp[-2].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2570 "grammar.c" /* yacc.c:1646 */
break;
case 61:
#line 1008 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED);
yr_free((yyvsp[-2].c_string));
ERROR_IF(compiler->last_result!= ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2585 "grammar.c" /* yacc.c:1646 */
break;
case 62:
#line 1019 "grammar.y" /* yacc.c:1646 */
{
int var_index;
if (compiler->loop_depth == MAX_LOOP_NESTING)
compiler->last_result = \
ERROR_LOOP_NESTING_LIMIT_EXCEEDED;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
var_index = yr_parser_lookup_loop_variable(
yyscanner, (yyvsp[-1].c_string));
if (var_index >= 0)
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-1].c_string));
compiler->last_result = \
ERROR_DUPLICATED_LOOP_IDENTIFIER;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2619 "grammar.c" /* yacc.c:1646 */
break;
case 63:
#line 1049 "grammar.y" /* yacc.c:1646 */
{
int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
uint8_t* addr;
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);
if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION)
{
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, &addr, NULL);
}
else // INTEGER_SET_RANGE
{
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, NULL, NULL);
}
compiler->loop_address[compiler->loop_depth] = addr;
compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string);
compiler->loop_depth++;
}
#line 2658 "grammar.c" /* yacc.c:1646 */
break;
case 64:
#line 1084 "grammar.y" /* yacc.c:1646 */
{
int mem_offset;
compiler->loop_depth--;
mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
yr_parser_emit_with_arg(
yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);
if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION)
{
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JNUNDEF,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
}
else // INTEGER_SET_RANGE
{
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL);
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JLE,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
}
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);
yr_parser_emit(yyscanner, OP_INT_LE, NULL);
compiler->loop_identifier[compiler->loop_depth] = NULL;
yr_free((yyvsp[-8].c_string));
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2741 "grammar.c" /* yacc.c:1646 */
break;
case 65:
#line 1163 "grammar.y" /* yacc.c:1646 */
{
int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
uint8_t* addr;
if (compiler->loop_depth == MAX_LOOP_NESTING)
compiler->last_result = \
ERROR_LOOP_NESTING_LIMIT_EXCEEDED;
if (compiler->loop_for_of_mem_offset != -1)
compiler->last_result = \
ERROR_NESTED_FOR_OF_LOOP;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, &addr, NULL);
compiler->loop_for_of_mem_offset = mem_offset;
compiler->loop_address[compiler->loop_depth] = addr;
compiler->loop_identifier[compiler->loop_depth] = NULL;
compiler->loop_depth++;
}
#line 2775 "grammar.c" /* yacc.c:1646 */
break;
case 66:
#line 1193 "grammar.y" /* yacc.c:1646 */
{
int mem_offset;
compiler->loop_depth--;
compiler->loop_for_of_mem_offset = -1;
mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
yr_parser_emit_with_arg(
yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JNUNDEF,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);
yr_parser_emit(yyscanner, OP_INT_LE, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2828 "grammar.c" /* yacc.c:1646 */
break;
case 67:
#line 1242 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_OF, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2838 "grammar.c" /* yacc.c:1646 */
break;
case 68:
#line 1248 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_NOT, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2848 "grammar.c" /* yacc.c:1646 */
break;
case 69:
#line 1254 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
void* jmp_destination_addr;
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JFALSE,
0, // still don't know the jump destination
NULL,
&jmp_destination_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));
if (fixup == NULL)
compiler->last_error = ERROR_INSUFFICIENT_MEMORY;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup->address = jmp_destination_addr;
fixup->next = compiler->fixup_stack_head;
compiler->fixup_stack_head = fixup;
}
#line 2878 "grammar.c" /* yacc.c:1646 */
break;
case 70:
#line 1280 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
uint8_t* and_addr;
compiler->last_result = yr_arena_reserve_memory(
compiler->code_arena, 2);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = compiler->fixup_stack_head;
*(void**)(fixup->address) = (void*)(and_addr + 1);
compiler->fixup_stack_head = fixup->next;
yr_free(fixup);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2918 "grammar.c" /* yacc.c:1646 */
break;
case 71:
#line 1316 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
void* jmp_destination_addr;
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JTRUE,
0, // still don't know the jump destination
NULL,
&jmp_destination_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));
if (fixup == NULL)
compiler->last_error = ERROR_INSUFFICIENT_MEMORY;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup->address = jmp_destination_addr;
fixup->next = compiler->fixup_stack_head;
compiler->fixup_stack_head = fixup;
}
#line 2947 "grammar.c" /* yacc.c:1646 */
break;
case 72:
#line 1341 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
uint8_t* or_addr;
compiler->last_result = yr_arena_reserve_memory(
compiler->code_arena, 2);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = compiler->fixup_stack_head;
*(void**)(fixup->address) = (void*)(or_addr + 1);
compiler->fixup_stack_head = fixup->next;
yr_free(fixup);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2987 "grammar.c" /* yacc.c:1646 */
break;
case 73:
#line 1377 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "<", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3000 "grammar.c" /* yacc.c:1646 */
break;
case 74:
#line 1386 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, ">", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3013 "grammar.c" /* yacc.c:1646 */
break;
case 75:
#line 1395 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "<=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3026 "grammar.c" /* yacc.c:1646 */
break;
case 76:
#line 1404 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, ">=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3039 "grammar.c" /* yacc.c:1646 */
break;
case 77:
#line 1413 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "==", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3052 "grammar.c" /* yacc.c:1646 */
break;
case 78:
#line 1422 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "!=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3065 "grammar.c" /* yacc.c:1646 */
break;
case 79:
#line 1431 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3073 "grammar.c" /* yacc.c:1646 */
break;
case 80:
#line 1435 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3081 "grammar.c" /* yacc.c:1646 */
break;
case 81:
#line 1442 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_ENUMERATION; }
#line 3087 "grammar.c" /* yacc.c:1646 */
break;
case 82:
#line 1443 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_RANGE; }
#line 3093 "grammar.c" /* yacc.c:1646 */
break;
case 83:
#line 1449 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for range's lower bound");
compiler->last_result = ERROR_WRONG_TYPE;
}
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for range's upper bound");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3115 "grammar.c" /* yacc.c:1646 */
break;
case 84:
#line 1471 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for enumeration item");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3131 "grammar.c" /* yacc.c:1646 */
break;
case 85:
#line 1483 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for enumeration item");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3146 "grammar.c" /* yacc.c:1646 */
break;
case 86:
#line 1498 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3155 "grammar.c" /* yacc.c:1646 */
break;
case 88:
#line 1504 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
yr_parser_emit_pushes_for_strings(yyscanner, "$*");
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3166 "grammar.c" /* yacc.c:1646 */
break;
case 91:
#line 1521 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string));
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3177 "grammar.c" /* yacc.c:1646 */
break;
case 92:
#line 1528 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string));
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3188 "grammar.c" /* yacc.c:1646 */
break;
case 94:
#line 1540 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3196 "grammar.c" /* yacc.c:1646 */
break;
case 95:
#line 1544 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL);
}
#line 3204 "grammar.c" /* yacc.c:1646 */
break;
case 96:
#line 1552 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3212 "grammar.c" /* yacc.c:1646 */
break;
case 97:
#line 1556 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit(
yyscanner, OP_FILESIZE, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3226 "grammar.c" /* yacc.c:1646 */
break;
case 98:
#line 1566 "grammar.y" /* yacc.c:1646 */
{
yywarning(yyscanner,
"Using deprecated \"entrypoint\" keyword. Use the \"entry_point\" "
"function from PE module instead.");
compiler->last_result = yr_parser_emit(
yyscanner, OP_ENTRYPOINT, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3244 "grammar.c" /* yacc.c:1646 */
break;
case 99:
#line 1580 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, "intXXXX or uintXXXX");
compiler->last_result = yr_parser_emit(
yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3264 "grammar.c" /* yacc.c:1646 */
break;
case 100:
#line 1596 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = (yyvsp[0].integer);
}
#line 3278 "grammar.c" /* yacc.c:1646 */
break;
case 101:
#line 1606 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg_double(
yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
#line 3291 "grammar.c" /* yacc.c:1646 */
break;
case 102:
#line 1615 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string;
compiler->last_result = yr_arena_write_data(
compiler->sz_arena,
(yyvsp[0].sized_string),
(yyvsp[0].sized_string)->length + sizeof(SIZED_STRING),
(void**) &sized_string);
yr_free((yyvsp[0].sized_string));
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
sized_string,
NULL,
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_STRING;
(yyval.expression).value.sized_string = sized_string;
}
#line 3320 "grammar.c" /* yacc.c:1646 */
break;
case 103:
#line 1640 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3336 "grammar.c" /* yacc.c:1646 */
break;
case 104:
#line 1652 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED);
yr_free((yyvsp[-3].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3352 "grammar.c" /* yacc.c:1646 */
break;
case 105:
#line 1664 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3372 "grammar.c" /* yacc.c:1646 */
break;
case 106:
#line 1680 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED);
yr_free((yyvsp[-3].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3388 "grammar.c" /* yacc.c:1646 */
break;
case 107:
#line 1692 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3408 "grammar.c" /* yacc.c:1646 */
break;
case 108:
#line 1708 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) // loop identifier
{
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) // rule identifier
{
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
(yyval.expression).value.integer = UNDEFINED;
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT)
{
compiler->last_result = yr_parser_emit(
yyscanner, OP_OBJ_VALUE, NULL);
switch((yyvsp[0].expression).value.object->type)
{
case OBJECT_TYPE_INTEGER:
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
break;
case OBJECT_TYPE_FLOAT:
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
break;
case OBJECT_TYPE_STRING:
(yyval.expression).type = EXPRESSION_TYPE_STRING;
(yyval.expression).value.sized_string = NULL;
break;
default:
yr_compiler_set_error_extra_info_fmt(
compiler,
"wrong usage of identifier \"%s\"",
(yyvsp[0].expression).identifier);
compiler->last_result = ERROR_WRONG_TYPE;
}
}
else
{
assert(FALSE);
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3457 "grammar.c" /* yacc.c:1646 */
break;
case 109:
#line 1753 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, "-");
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ?
UNDEFINED : -((yyvsp[0].expression).value.integer);
compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL);
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT)
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL);
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3480 "grammar.c" /* yacc.c:1646 */
break;
case 110:
#line 1772 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "+", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3502 "grammar.c" /* yacc.c:1646 */
break;
case 111:
#line 1790 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "-", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3524 "grammar.c" /* yacc.c:1646 */
break;
case 112:
#line 1808 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "*", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3546 "grammar.c" /* yacc.c:1646 */
break;
case 113:
#line 1826 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "\\", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
if ((yyvsp[0].expression).value.integer != 0)
{
(yyval.expression).value.integer = OPERATION(/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
compiler->last_result = ERROR_DIVISION_BY_ZERO;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3576 "grammar.c" /* yacc.c:1646 */
break;
case 114:
#line 1852 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "%");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "%");
yr_parser_emit(yyscanner, OP_MOD, NULL);
if ((yyvsp[0].expression).value.integer != 0)
{
(yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
compiler->last_result = ERROR_DIVISION_BY_ZERO;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
}
#line 3598 "grammar.c" /* yacc.c:1646 */
break;
case 115:
#line 1870 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^");
yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3612 "grammar.c" /* yacc.c:1646 */
break;
case 116:
#line 1880 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^");
yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3626 "grammar.c" /* yacc.c:1646 */
break;
case 117:
#line 1890 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "|");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "|");
yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3640 "grammar.c" /* yacc.c:1646 */
break;
case 118:
#line 1900 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "~");
yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ?
UNDEFINED : ~((yyvsp[0].expression).value.integer);
}
#line 3654 "grammar.c" /* yacc.c:1646 */
break;
case 119:
#line 1910 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "<<");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "<<");
yr_parser_emit(yyscanner, OP_SHL, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3668 "grammar.c" /* yacc.c:1646 */
break;
case 120:
#line 1920 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, ">>");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, ">>");
yr_parser_emit(yyscanner, OP_SHR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3682 "grammar.c" /* yacc.c:1646 */
break;
case 121:
#line 1930 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3690 "grammar.c" /* yacc.c:1646 */
break;
#line 3694 "grammar.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (yyscanner, compiler, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yyscanner, compiler, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, yyscanner, compiler);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, yyscanner, compiler);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (yyscanner, compiler, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, yyscanner, compiler);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, yyscanner, compiler);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
Commit Message: Fix issue #575
CWE ID: CWE-416 | yyparse (void *yyscanner, YR_COMPILER* compiler)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, yyscanner, compiler);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 8:
#line 230 "grammar.y" /* yacc.c:1646 */
{
int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF(result != ERROR_SUCCESS);
}
#line 1661 "grammar.c" /* yacc.c:1646 */
break;
case 9:
#line 242 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1(
yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string));
ERROR_IF(rule == NULL);
(yyval.rule) = rule;
}
#line 1674 "grammar.c" /* yacc.c:1646 */
break;
case 10:
#line 251 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = (yyvsp[-4].rule); // rule created in phase 1
rule->tags = (yyvsp[-3].c_string);
rule->metas = (yyvsp[-1].meta);
rule->strings = (yyvsp[0].string);
}
#line 1686 "grammar.c" /* yacc.c:1646 */
break;
case 11:
#line 259 "grammar.y" /* yacc.c:1646 */
{
YR_RULE* rule = (yyvsp[-7].rule); // rule created in phase 1
compiler->last_result = yr_parser_reduce_rule_declaration_phase_2(
yyscanner, rule);
yr_free((yyvsp[-8].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 1701 "grammar.c" /* yacc.c:1646 */
break;
case 12:
#line 274 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = NULL;
}
#line 1709 "grammar.c" /* yacc.c:1646 */
break;
case 13:
#line 278 "grammar.y" /* yacc.c:1646 */
{
YR_META null_meta;
memset(&null_meta, 0xFF, sizeof(YR_META));
null_meta.type = META_TYPE_NULL;
compiler->last_result = yr_arena_write_data(
compiler->metas_arena,
&null_meta,
sizeof(YR_META),
NULL);
(yyval.meta) = (yyvsp[0].meta);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 1736 "grammar.c" /* yacc.c:1646 */
break;
case 14:
#line 305 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = NULL;
}
#line 1744 "grammar.c" /* yacc.c:1646 */
break;
case 15:
#line 309 "grammar.y" /* yacc.c:1646 */
{
YR_STRING null_string;
memset(&null_string, 0xFF, sizeof(YR_STRING));
null_string.g_flags = STRING_GFLAGS_NULL;
compiler->last_result = yr_arena_write_data(
compiler->strings_arena,
&null_string,
sizeof(YR_STRING),
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.string) = (yyvsp[0].string);
}
#line 1771 "grammar.c" /* yacc.c:1646 */
break;
case 17:
#line 340 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = 0; }
#line 1777 "grammar.c" /* yacc.c:1646 */
break;
case 18:
#line 341 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); }
#line 1783 "grammar.c" /* yacc.c:1646 */
break;
case 19:
#line 346 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = RULE_GFLAGS_PRIVATE; }
#line 1789 "grammar.c" /* yacc.c:1646 */
break;
case 20:
#line 347 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = RULE_GFLAGS_GLOBAL; }
#line 1795 "grammar.c" /* yacc.c:1646 */
break;
case 21:
#line 353 "grammar.y" /* yacc.c:1646 */
{
(yyval.c_string) = NULL;
}
#line 1803 "grammar.c" /* yacc.c:1646 */
break;
case 22:
#line 357 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, "", NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[0].c_string);
}
#line 1821 "grammar.c" /* yacc.c:1646 */
break;
case 23:
#line 375 "grammar.y" /* yacc.c:1646 */
{
char* identifier;
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = identifier;
}
#line 1838 "grammar.c" /* yacc.c:1646 */
break;
case 24:
#line 388 "grammar.y" /* yacc.c:1646 */
{
char* tag_name = (yyvsp[-1].c_string);
size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0;
while (tag_length > 0)
{
if (strcmp(tag_name, (yyvsp[0].c_string)) == 0)
{
yr_compiler_set_error_extra_info(compiler, tag_name);
compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER;
break;
}
tag_name = (char*) yr_arena_next_address(
yyget_extra(yyscanner)->sz_arena,
tag_name,
tag_length + 1);
tag_length = tag_name != NULL ? strlen(tag_name) : 0;
}
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_arena_write_string(
yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[-1].c_string);
}
#line 1874 "grammar.c" /* yacc.c:1646 */
break;
case 25:
#line 424 "grammar.y" /* yacc.c:1646 */
{ (yyval.meta) = (yyvsp[0].meta); }
#line 1880 "grammar.c" /* yacc.c:1646 */
break;
case 26:
#line 425 "grammar.y" /* yacc.c:1646 */
{ (yyval.meta) = (yyvsp[-1].meta); }
#line 1886 "grammar.c" /* yacc.c:1646 */
break;
case 27:
#line 431 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string = (yyvsp[0].sized_string);
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_STRING,
(yyvsp[-2].c_string),
sized_string->c_string,
0);
yr_free((yyvsp[-2].c_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1906 "grammar.c" /* yacc.c:1646 */
break;
case 28:
#line 447 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_INTEGER,
(yyvsp[-2].c_string),
NULL,
(yyvsp[0].integer));
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1923 "grammar.c" /* yacc.c:1646 */
break;
case 29:
#line 460 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_INTEGER,
(yyvsp[-3].c_string),
NULL,
-(yyvsp[0].integer));
yr_free((yyvsp[-3].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1940 "grammar.c" /* yacc.c:1646 */
break;
case 30:
#line 473 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_BOOLEAN,
(yyvsp[-2].c_string),
NULL,
TRUE);
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1957 "grammar.c" /* yacc.c:1646 */
break;
case 31:
#line 486 "grammar.y" /* yacc.c:1646 */
{
(yyval.meta) = yr_parser_reduce_meta_declaration(
yyscanner,
META_TYPE_BOOLEAN,
(yyvsp[-2].c_string),
NULL,
FALSE);
yr_free((yyvsp[-2].c_string));
ERROR_IF((yyval.meta) == NULL);
}
#line 1974 "grammar.c" /* yacc.c:1646 */
break;
case 32:
#line 502 "grammar.y" /* yacc.c:1646 */
{ (yyval.string) = (yyvsp[0].string); }
#line 1980 "grammar.c" /* yacc.c:1646 */
break;
case 33:
#line 503 "grammar.y" /* yacc.c:1646 */
{ (yyval.string) = (yyvsp[-1].string); }
#line 1986 "grammar.c" /* yacc.c:1646 */
break;
case 34:
#line 509 "grammar.y" /* yacc.c:1646 */
{
compiler->error_line = yyget_lineno(yyscanner);
}
#line 1994 "grammar.c" /* yacc.c:1646 */
break;
case 35:
#line 513 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string));
yr_free((yyvsp[-4].c_string));
yr_free((yyvsp[-1].sized_string));
ERROR_IF((yyval.string) == NULL);
compiler->error_line = 0;
}
#line 2009 "grammar.c" /* yacc.c:1646 */
break;
case 36:
#line 524 "grammar.y" /* yacc.c:1646 */
{
compiler->error_line = yyget_lineno(yyscanner);
}
#line 2017 "grammar.c" /* yacc.c:1646 */
break;
case 37:
#line 528 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string));
yr_free((yyvsp[-4].c_string));
yr_free((yyvsp[-1].sized_string));
ERROR_IF((yyval.string) == NULL);
compiler->error_line = 0;
}
#line 2033 "grammar.c" /* yacc.c:1646 */
break;
case 38:
#line 540 "grammar.y" /* yacc.c:1646 */
{
(yyval.string) = yr_parser_reduce_string_declaration(
yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string));
yr_free((yyvsp[-2].c_string));
yr_free((yyvsp[0].sized_string));
ERROR_IF((yyval.string) == NULL);
}
#line 2047 "grammar.c" /* yacc.c:1646 */
break;
case 39:
#line 553 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = 0; }
#line 2053 "grammar.c" /* yacc.c:1646 */
break;
case 40:
#line 554 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); }
#line 2059 "grammar.c" /* yacc.c:1646 */
break;
case 41:
#line 559 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_WIDE; }
#line 2065 "grammar.c" /* yacc.c:1646 */
break;
case 42:
#line 560 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_ASCII; }
#line 2071 "grammar.c" /* yacc.c:1646 */
break;
case 43:
#line 561 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_NO_CASE; }
#line 2077 "grammar.c" /* yacc.c:1646 */
break;
case 44:
#line 562 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = STRING_GFLAGS_FULL_WORD; }
#line 2083 "grammar.c" /* yacc.c:1646 */
break;
case 45:
#line 568 "grammar.y" /* yacc.c:1646 */
{
int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string));
if (var_index >= 0)
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner,
OP_PUSH_M,
LOOP_LOCAL_VARS * var_index,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
(yyval.expression).identifier = compiler->loop_identifier[var_index];
}
else
{
YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup(
compiler->objects_table, (yyvsp[0].c_string), NULL);
if (object == NULL)
{
char* ns = compiler->current_namespace->name;
object = (YR_OBJECT*) yr_hash_table_lookup(
compiler->objects_table, (yyvsp[0].c_string), ns);
}
if (object != NULL)
{
char* id;
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[0].c_string), &id);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_OBJ_LOAD,
id,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = object;
(yyval.expression).identifier = object->identifier;
}
else
{
YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup(
compiler->rules_table,
(yyvsp[0].c_string),
compiler->current_namespace->name);
if (rule != NULL)
{
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH_RULE,
rule,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
(yyval.expression).value.integer = UNDEFINED;
(yyval.expression).identifier = rule->identifier;
}
else
{
yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string));
compiler->last_result = ERROR_UNDEFINED_IDENTIFIER;
}
}
}
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2172 "grammar.c" /* yacc.c:1646 */
break;
case 46:
#line 653 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT* field = NULL;
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE)
{
field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string));
if (field != NULL)
{
char* ident;
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[0].c_string), &ident);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_OBJ_FIELD,
ident,
NULL,
NULL);
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = field;
(yyval.expression).identifier = field->identifier;
}
else
{
yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string));
compiler->last_result = ERROR_INVALID_FIELD_NAME;
}
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-2].expression).identifier);
compiler->last_result = ERROR_NOT_A_STRUCTURE;
}
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2222 "grammar.c" /* yacc.c:1646 */
break;
case 47:
#line 699 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT_ARRAY* array;
YR_OBJECT_DICTIONARY* dict;
if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY)
{
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "array indexes must be of integer type");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(
yyscanner, OP_INDEX_ARRAY, NULL);
array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = array->prototype_item;
(yyval.expression).identifier = array->identifier;
}
else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY)
{
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING)
{
yr_compiler_set_error_extra_info(
compiler, "dictionary keys must be of string type");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(
yyscanner, OP_LOOKUP_DICT, NULL);
dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = dict->prototype_item;
(yyval.expression).identifier = dict->identifier;
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-3].expression).identifier);
compiler->last_result = ERROR_NOT_INDEXABLE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2283 "grammar.c" /* yacc.c:1646 */
break;
case 48:
#line 757 "grammar.y" /* yacc.c:1646 */
{
YR_OBJECT_FUNCTION* function;
char* args_fmt;
if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT &&
(yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION)
{
compiler->last_result = yr_parser_check_types(
compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string));
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_arena_write_string(
compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_CALL,
args_fmt,
NULL,
NULL);
function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object;
(yyval.expression).type = EXPRESSION_TYPE_OBJECT;
(yyval.expression).value.object = function->return_obj;
(yyval.expression).identifier = function->identifier;
}
else
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-3].expression).identifier);
compiler->last_result = ERROR_NOT_A_FUNCTION;
}
yr_free((yyvsp[-1].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2328 "grammar.c" /* yacc.c:1646 */
break;
case 49:
#line 801 "grammar.y" /* yacc.c:1646 */
{ (yyval.c_string) = yr_strdup(""); }
#line 2334 "grammar.c" /* yacc.c:1646 */
break;
case 50:
#line 802 "grammar.y" /* yacc.c:1646 */
{ (yyval.c_string) = (yyvsp[0].c_string); }
#line 2340 "grammar.c" /* yacc.c:1646 */
break;
case 51:
#line 807 "grammar.y" /* yacc.c:1646 */
{
(yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1);
switch((yyvsp[0].expression).type)
{
case EXPRESSION_TYPE_INTEGER:
strlcpy((yyval.c_string), "i", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_FLOAT:
strlcpy((yyval.c_string), "f", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_BOOLEAN:
strlcpy((yyval.c_string), "b", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_STRING:
strlcpy((yyval.c_string), "s", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_REGEXP:
strlcpy((yyval.c_string), "r", MAX_FUNCTION_ARGS);
break;
}
ERROR_IF((yyval.c_string) == NULL);
}
#line 2369 "grammar.c" /* yacc.c:1646 */
break;
case 52:
#line 832 "grammar.y" /* yacc.c:1646 */
{
if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS)
{
compiler->last_result = ERROR_TOO_MANY_ARGUMENTS;
}
else
{
switch((yyvsp[0].expression).type)
{
case EXPRESSION_TYPE_INTEGER:
strlcat((yyvsp[-2].c_string), "i", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_FLOAT:
strlcat((yyvsp[-2].c_string), "f", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_BOOLEAN:
strlcat((yyvsp[-2].c_string), "b", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_STRING:
strlcat((yyvsp[-2].c_string), "s", MAX_FUNCTION_ARGS);
break;
case EXPRESSION_TYPE_REGEXP:
strlcat((yyvsp[-2].c_string), "r", MAX_FUNCTION_ARGS);
break;
}
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.c_string) = (yyvsp[-2].c_string);
}
#line 2405 "grammar.c" /* yacc.c:1646 */
break;
case 53:
#line 868 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string = (yyvsp[0].sized_string);
RE* re;
RE_ERROR error;
int re_flags = 0;
if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE)
re_flags |= RE_FLAGS_NO_CASE;
if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL)
re_flags |= RE_FLAGS_DOT_ALL;
compiler->last_result = yr_re_compile(
sized_string->c_string,
re_flags,
compiler->re_code_arena,
&re,
&error);
yr_free((yyvsp[0].sized_string));
if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION)
yr_compiler_set_error_extra_info(compiler, error.message);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
re->root_node->forward_code,
NULL,
NULL);
yr_re_destroy(re);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_REGEXP;
}
#line 2451 "grammar.c" /* yacc.c:1646 */
break;
case 54:
#line 914 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING)
{
if ((yyvsp[0].expression).value.sized_string != NULL)
{
yywarning(yyscanner,
"Using literal string \"%s\" in a boolean operation.",
(yyvsp[0].expression).value.sized_string->c_string);
}
compiler->last_result = yr_parser_emit(
yyscanner, OP_STR_TO_BOOL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2474 "grammar.c" /* yacc.c:1646 */
break;
case 55:
#line 936 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2487 "grammar.c" /* yacc.c:1646 */
break;
case 56:
#line 945 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 0, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2500 "grammar.c" /* yacc.c:1646 */
break;
case 57:
#line 954 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "matches");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, "matches");
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit(
yyscanner,
OP_MATCHES,
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2519 "grammar.c" /* yacc.c:1646 */
break;
case 58:
#line 969 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "contains");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, "contains");
compiler->last_result = yr_parser_emit(
yyscanner, OP_CONTAINS, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2535 "grammar.c" /* yacc.c:1646 */
break;
case 59:
#line 981 "grammar.y" /* yacc.c:1646 */
{
int result = yr_parser_reduce_string_identifier(
yyscanner,
(yyvsp[0].c_string),
OP_FOUND,
UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2553 "grammar.c" /* yacc.c:1646 */
break;
case 60:
#line 995 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "at");
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer);
yr_free((yyvsp[-2].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2570 "grammar.c" /* yacc.c:1646 */
break;
case 61:
#line 1008 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED);
yr_free((yyvsp[-2].c_string));
ERROR_IF(compiler->last_result!= ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2585 "grammar.c" /* yacc.c:1646 */
break;
case 62:
#line 1019 "grammar.y" /* yacc.c:1646 */
{
compiler->loop_depth--;
compiler->loop_identifier[compiler->loop_depth] = NULL;
}
#line 2594 "grammar.c" /* yacc.c:1646 */
break;
case 63:
#line 1024 "grammar.y" /* yacc.c:1646 */
{
int var_index;
if (compiler->loop_depth == MAX_LOOP_NESTING)
compiler->last_result = \
ERROR_LOOP_NESTING_LIMIT_EXCEEDED;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
var_index = yr_parser_lookup_loop_variable(
yyscanner, (yyvsp[-1].c_string));
if (var_index >= 0)
{
yr_compiler_set_error_extra_info(
compiler, (yyvsp[-1].c_string));
compiler->last_result = \
ERROR_DUPLICATED_LOOP_IDENTIFIER;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 2628 "grammar.c" /* yacc.c:1646 */
break;
case 64:
#line 1054 "grammar.y" /* yacc.c:1646 */
{
int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
uint8_t* addr;
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);
if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION)
{
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, &addr, NULL);
}
else // INTEGER_SET_RANGE
{
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, NULL, NULL);
}
compiler->loop_address[compiler->loop_depth] = addr;
compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string);
compiler->loop_depth++;
}
#line 2667 "grammar.c" /* yacc.c:1646 */
break;
case 65:
#line 1089 "grammar.y" /* yacc.c:1646 */
{
int mem_offset;
compiler->loop_depth--;
mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
yr_parser_emit_with_arg(
yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);
if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION)
{
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JNUNDEF,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
}
else // INTEGER_SET_RANGE
{
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL);
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JLE,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
}
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);
yr_parser_emit(yyscanner, OP_INT_LE, NULL);
compiler->loop_identifier[compiler->loop_depth] = NULL;
yr_free((yyvsp[-8].c_string));
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2750 "grammar.c" /* yacc.c:1646 */
break;
case 66:
#line 1168 "grammar.y" /* yacc.c:1646 */
{
int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
uint8_t* addr;
if (compiler->loop_depth == MAX_LOOP_NESTING)
compiler->last_result = \
ERROR_LOOP_NESTING_LIMIT_EXCEEDED;
if (compiler->loop_for_of_mem_offset != -1)
compiler->last_result = \
ERROR_NESTED_FOR_OF_LOOP;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_POP_M, mem_offset, &addr, NULL);
compiler->loop_for_of_mem_offset = mem_offset;
compiler->loop_address[compiler->loop_depth] = addr;
compiler->loop_identifier[compiler->loop_depth] = NULL;
compiler->loop_depth++;
}
#line 2784 "grammar.c" /* yacc.c:1646 */
break;
case 67:
#line 1198 "grammar.y" /* yacc.c:1646 */
{
int mem_offset;
compiler->loop_depth--;
compiler->loop_for_of_mem_offset = -1;
mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;
yr_parser_emit_with_arg(
yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JNUNDEF,
compiler->loop_address[compiler->loop_depth],
NULL,
NULL);
yr_parser_emit(yyscanner, OP_POP, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);
yr_parser_emit_with_arg(
yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);
yr_parser_emit(yyscanner, OP_INT_LE, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2837 "grammar.c" /* yacc.c:1646 */
break;
case 68:
#line 1247 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_OF, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2847 "grammar.c" /* yacc.c:1646 */
break;
case 69:
#line 1253 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_NOT, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2857 "grammar.c" /* yacc.c:1646 */
break;
case 70:
#line 1259 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
void* jmp_destination_addr;
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JFALSE,
0, // still don't know the jump destination
NULL,
&jmp_destination_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));
if (fixup == NULL)
compiler->last_error = ERROR_INSUFFICIENT_MEMORY;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup->address = jmp_destination_addr;
fixup->next = compiler->fixup_stack_head;
compiler->fixup_stack_head = fixup;
}
#line 2887 "grammar.c" /* yacc.c:1646 */
break;
case 71:
#line 1285 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
uint8_t* and_addr;
compiler->last_result = yr_arena_reserve_memory(
compiler->code_arena, 2);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = compiler->fixup_stack_head;
*(void**)(fixup->address) = (void*)(and_addr + 1);
compiler->fixup_stack_head = fixup->next;
yr_free(fixup);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2927 "grammar.c" /* yacc.c:1646 */
break;
case 72:
#line 1321 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
void* jmp_destination_addr;
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_JTRUE,
0, // still don't know the jump destination
NULL,
&jmp_destination_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));
if (fixup == NULL)
compiler->last_error = ERROR_INSUFFICIENT_MEMORY;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup->address = jmp_destination_addr;
fixup->next = compiler->fixup_stack_head;
compiler->fixup_stack_head = fixup;
}
#line 2956 "grammar.c" /* yacc.c:1646 */
break;
case 73:
#line 1346 "grammar.y" /* yacc.c:1646 */
{
YR_FIXUP* fixup;
uint8_t* or_addr;
compiler->last_result = yr_arena_reserve_memory(
compiler->code_arena, 2);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
fixup = compiler->fixup_stack_head;
*(void**)(fixup->address) = (void*)(or_addr + 1);
compiler->fixup_stack_head = fixup->next;
yr_free(fixup);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2996 "grammar.c" /* yacc.c:1646 */
break;
case 74:
#line 1382 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "<", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3009 "grammar.c" /* yacc.c:1646 */
break;
case 75:
#line 1391 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, ">", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3022 "grammar.c" /* yacc.c:1646 */
break;
case 76:
#line 1400 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "<=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3035 "grammar.c" /* yacc.c:1646 */
break;
case 77:
#line 1409 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, ">=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3048 "grammar.c" /* yacc.c:1646 */
break;
case 78:
#line 1418 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "==", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3061 "grammar.c" /* yacc.c:1646 */
break;
case 79:
#line 1427 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "!=", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 3074 "grammar.c" /* yacc.c:1646 */
break;
case 80:
#line 1436 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3082 "grammar.c" /* yacc.c:1646 */
break;
case 81:
#line 1440 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3090 "grammar.c" /* yacc.c:1646 */
break;
case 82:
#line 1447 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_ENUMERATION; }
#line 3096 "grammar.c" /* yacc.c:1646 */
break;
case 83:
#line 1448 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_RANGE; }
#line 3102 "grammar.c" /* yacc.c:1646 */
break;
case 84:
#line 1454 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for range's lower bound");
compiler->last_result = ERROR_WRONG_TYPE;
}
if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for range's upper bound");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3124 "grammar.c" /* yacc.c:1646 */
break;
case 85:
#line 1476 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for enumeration item");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3140 "grammar.c" /* yacc.c:1646 */
break;
case 86:
#line 1488 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER)
{
yr_compiler_set_error_extra_info(
compiler, "wrong type for enumeration item");
compiler->last_result = ERROR_WRONG_TYPE;
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3155 "grammar.c" /* yacc.c:1646 */
break;
case 87:
#line 1503 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3164 "grammar.c" /* yacc.c:1646 */
break;
case 89:
#line 1509 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
yr_parser_emit_pushes_for_strings(yyscanner, "$*");
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3175 "grammar.c" /* yacc.c:1646 */
break;
case 92:
#line 1526 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string));
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3186 "grammar.c" /* yacc.c:1646 */
break;
case 93:
#line 1533 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string));
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3197 "grammar.c" /* yacc.c:1646 */
break;
case 95:
#line 1545 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3205 "grammar.c" /* yacc.c:1646 */
break;
case 96:
#line 1549 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL);
}
#line 3213 "grammar.c" /* yacc.c:1646 */
break;
case 97:
#line 1557 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3221 "grammar.c" /* yacc.c:1646 */
break;
case 98:
#line 1561 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit(
yyscanner, OP_FILESIZE, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3235 "grammar.c" /* yacc.c:1646 */
break;
case 99:
#line 1571 "grammar.y" /* yacc.c:1646 */
{
yywarning(yyscanner,
"Using deprecated \"entrypoint\" keyword. Use the \"entry_point\" "
"function from PE module instead.");
compiler->last_result = yr_parser_emit(
yyscanner, OP_ENTRYPOINT, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3253 "grammar.c" /* yacc.c:1646 */
break;
case 100:
#line 1585 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, "intXXXX or uintXXXX");
compiler->last_result = yr_parser_emit(
yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3273 "grammar.c" /* yacc.c:1646 */
break;
case 101:
#line 1601 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = (yyvsp[0].integer);
}
#line 3287 "grammar.c" /* yacc.c:1646 */
break;
case 102:
#line 1611 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg_double(
yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
#line 3300 "grammar.c" /* yacc.c:1646 */
break;
case 103:
#line 1620 "grammar.y" /* yacc.c:1646 */
{
SIZED_STRING* sized_string;
compiler->last_result = yr_arena_write_data(
compiler->sz_arena,
(yyvsp[0].sized_string),
(yyvsp[0].sized_string)->length + sizeof(SIZED_STRING),
(void**) &sized_string);
yr_free((yyvsp[0].sized_string));
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
sized_string,
NULL,
NULL);
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_STRING;
(yyval.expression).value.sized_string = sized_string;
}
#line 3329 "grammar.c" /* yacc.c:1646 */
break;
case 104:
#line 1645 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3345 "grammar.c" /* yacc.c:1646 */
break;
case 105:
#line 1657 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED);
yr_free((yyvsp[-3].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3361 "grammar.c" /* yacc.c:1646 */
break;
case 106:
#line 1669 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3381 "grammar.c" /* yacc.c:1646 */
break;
case 107:
#line 1685 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED);
yr_free((yyvsp[-3].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3397 "grammar.c" /* yacc.c:1646 */
break;
case 108:
#line 1697 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_emit_with_arg(
yyscanner, OP_PUSH, 1, NULL, NULL);
if (compiler->last_result == ERROR_SUCCESS)
compiler->last_result = yr_parser_reduce_string_identifier(
yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED);
yr_free((yyvsp[0].c_string));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
#line 3417 "grammar.c" /* yacc.c:1646 */
break;
case 109:
#line 1713 "grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) // loop identifier
{
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) // rule identifier
{
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
(yyval.expression).value.integer = UNDEFINED;
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT)
{
compiler->last_result = yr_parser_emit(
yyscanner, OP_OBJ_VALUE, NULL);
switch((yyvsp[0].expression).value.object->type)
{
case OBJECT_TYPE_INTEGER:
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = UNDEFINED;
break;
case OBJECT_TYPE_FLOAT:
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
break;
case OBJECT_TYPE_STRING:
(yyval.expression).type = EXPRESSION_TYPE_STRING;
(yyval.expression).value.sized_string = NULL;
break;
default:
yr_compiler_set_error_extra_info_fmt(
compiler,
"wrong usage of identifier \"%s\"",
(yyvsp[0].expression).identifier);
compiler->last_result = ERROR_WRONG_TYPE;
}
}
else
{
assert(FALSE);
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3466 "grammar.c" /* yacc.c:1646 */
break;
case 110:
#line 1758 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, "-");
if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ?
UNDEFINED : -((yyvsp[0].expression).value.integer);
compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL);
}
else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT)
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL);
}
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
#line 3489 "grammar.c" /* yacc.c:1646 */
break;
case 111:
#line 1777 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "+", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3511 "grammar.c" /* yacc.c:1646 */
break;
case 112:
#line 1795 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "-", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3533 "grammar.c" /* yacc.c:1646 */
break;
case 113:
#line 1813 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "*", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
(yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3555 "grammar.c" /* yacc.c:1646 */
break;
case 114:
#line 1831 "grammar.y" /* yacc.c:1646 */
{
compiler->last_result = yr_parser_reduce_operation(
yyscanner, "\\", (yyvsp[-2].expression), (yyvsp[0].expression));
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER &&
(yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER)
{
if ((yyvsp[0].expression).value.integer != 0)
{
(yyval.expression).value.integer = OPERATION(/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
compiler->last_result = ERROR_DIVISION_BY_ZERO;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
}
else
{
(yyval.expression).type = EXPRESSION_TYPE_FLOAT;
}
}
#line 3585 "grammar.c" /* yacc.c:1646 */
break;
case 115:
#line 1857 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "%");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "%");
yr_parser_emit(yyscanner, OP_MOD, NULL);
if ((yyvsp[0].expression).value.integer != 0)
{
(yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
}
else
{
compiler->last_result = ERROR_DIVISION_BY_ZERO;
ERROR_IF(compiler->last_result != ERROR_SUCCESS);
}
}
#line 3607 "grammar.c" /* yacc.c:1646 */
break;
case 116:
#line 1875 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^");
yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3621 "grammar.c" /* yacc.c:1646 */
break;
case 117:
#line 1885 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^");
yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3635 "grammar.c" /* yacc.c:1646 */
break;
case 118:
#line 1895 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "|");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "|");
yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3649 "grammar.c" /* yacc.c:1646 */
break;
case 119:
#line 1905 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "~");
yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ?
UNDEFINED : ~((yyvsp[0].expression).value.integer);
}
#line 3663 "grammar.c" /* yacc.c:1646 */
break;
case 120:
#line 1915 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "<<");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "<<");
yr_parser_emit(yyscanner, OP_SHL, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3677 "grammar.c" /* yacc.c:1646 */
break;
case 121:
#line 1925 "grammar.y" /* yacc.c:1646 */
{
CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, ">>");
CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, ">>");
yr_parser_emit(yyscanner, OP_SHR, NULL);
(yyval.expression).type = EXPRESSION_TYPE_INTEGER;
(yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer);
}
#line 3691 "grammar.c" /* yacc.c:1646 */
break;
case 122:
#line 1935 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3699 "grammar.c" /* yacc.c:1646 */
break;
#line 3703 "grammar.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (yyscanner, compiler, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yyscanner, compiler, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, yyscanner, compiler);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, yyscanner, compiler);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (yyscanner, compiler, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, yyscanner, compiler);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, yyscanner, compiler);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
| 168,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
url_util::AddStandardScheme("tabcontentstest");
old_browser_client_ = content::GetContentClient()->browser();
content::GetContentClient()->set_browser(&browser_client_);
RenderViewHostTestHarness::SetUp();
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | virtual void SetUp() {
url_util::AddStandardScheme("tabcontentstest");
old_client_ = content::GetContentClient();
content::SetContentClient(&client_);
old_browser_client_ = content::GetContentClient()->browser();
content::GetContentClient()->set_browser(&browser_client_);
RenderViewHostTestHarness::SetUp();
}
| 171,014 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage", "test",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
| 172,255 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Tracks* Segment::GetTracks() const
{
return m_pTracks;
}
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 | const Tracks* Segment::GetTracks() const
const SegmentInfo* Segment::GetInfo() const { return m_pInfo; }
const Cues* Segment::GetCues() const { return m_pCues; }
const Chapters* Segment::GetChapters() const { return m_pChapters; }
const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; }
long long Segment::GetDuration() const {
assert(m_pInfo);
return m_pInfo->GetDuration();
}
| 174,373 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forceUpdate)
{
if (forceUpdate || biquadProcessor()->filterCoefficientsDirty()) {
double value1;
double value2;
double gain;
double detune; // in Cents
if (biquadProcessor()->hasSampleAccurateValues()) {
value1 = biquadProcessor()->parameter1()->finalValue();
value2 = biquadProcessor()->parameter2()->finalValue();
gain = biquadProcessor()->parameter3()->finalValue();
detune = biquadProcessor()->parameter4()->finalValue();
} else if (useSmoothing) {
value1 = biquadProcessor()->parameter1()->smoothedValue();
value2 = biquadProcessor()->parameter2()->smoothedValue();
gain = biquadProcessor()->parameter3()->smoothedValue();
detune = biquadProcessor()->parameter4()->smoothedValue();
} else {
value1 = biquadProcessor()->parameter1()->value();
value2 = biquadProcessor()->parameter2()->value();
gain = biquadProcessor()->parameter3()->value();
detune = biquadProcessor()->parameter4()->value();
}
double nyquist = this->nyquist();
double normalizedFrequency = value1 / nyquist;
if (detune)
normalizedFrequency *= pow(2, detune / 1200);
switch (biquadProcessor()->type()) {
case BiquadProcessor::LowPass:
m_biquad.setLowpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::HighPass:
m_biquad.setHighpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::BandPass:
m_biquad.setBandpassParams(normalizedFrequency, value2);
break;
case BiquadProcessor::LowShelf:
m_biquad.setLowShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::HighShelf:
m_biquad.setHighShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::Peaking:
m_biquad.setPeakingParams(normalizedFrequency, value2, gain);
break;
case BiquadProcessor::Notch:
m_biquad.setNotchParams(normalizedFrequency, value2);
break;
case BiquadProcessor::Allpass:
m_biquad.setAllpassParams(normalizedFrequency, value2);
break;
}
}
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forceUpdate)
void BiquadDSPKernel::updateCoefficientsIfNecessary()
{
if (biquadProcessor()->filterCoefficientsDirty()) {
double cutoffFrequency;
double Q;
double gain;
double detune; // in Cents
if (biquadProcessor()->hasSampleAccurateValues()) {
cutoffFrequency = biquadProcessor()->parameter1()->finalValue();
Q = biquadProcessor()->parameter2()->finalValue();
gain = biquadProcessor()->parameter3()->finalValue();
detune = biquadProcessor()->parameter4()->finalValue();
} else {
cutoffFrequency = biquadProcessor()->parameter1()->smoothedValue();
Q = biquadProcessor()->parameter2()->smoothedValue();
gain = biquadProcessor()->parameter3()->smoothedValue();
detune = biquadProcessor()->parameter4()->smoothedValue();
}
updateCoefficients(cutoffFrequency, Q, gain, detune);
}
}
void BiquadDSPKernel::updateCoefficients(double cutoffFrequency, double Q, double gain, double detune)
{
// Convert from Hertz to normalized frequency 0 -> 1.
double nyquist = this->nyquist();
double normalizedFrequency = cutoffFrequency / nyquist;
// Offset frequency by detune.
if (detune)
normalizedFrequency *= pow(2, detune / 1200);
// Configure the biquad with the new filter parameters for the appropriate type of filter.
switch (biquadProcessor()->type()) {
case BiquadProcessor::LowPass:
m_biquad.setLowpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::HighPass:
m_biquad.setHighpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::BandPass:
m_biquad.setBandpassParams(normalizedFrequency, Q);
break;
case BiquadProcessor::LowShelf:
m_biquad.setLowShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::HighShelf:
m_biquad.setHighShelfParams(normalizedFrequency, gain);
break;
case BiquadProcessor::Peaking:
m_biquad.setPeakingParams(normalizedFrequency, Q, gain);
break;
case BiquadProcessor::Notch:
m_biquad.setNotchParams(normalizedFrequency, Q);
break;
case BiquadProcessor::Allpass:
m_biquad.setAllpassParams(normalizedFrequency, Q);
break;
}
}
| 171,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXFixesSelectCursorInput(ClientPtr client)
{
REQUEST(xXFixesSelectCursorInputReq);
swaps(&stuff->length);
swapl(&stuff->window);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
Commit Message:
CWE ID: CWE-20 | SProcXFixesSelectCursorInput(ClientPtr client)
{
REQUEST(xXFixesSelectCursorInputReq);
REQUEST_SIZE_MATCH(xXFixesSelectCursorInputReq);
swaps(&stuff->length);
swapl(&stuff->window);
return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
}
| 165,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cg_opendir(const char *path, struct fuse_file_info *fi)
{
struct fuse_context *fc = fuse_get_context();
const char *cgroup;
struct file_info *dir_info;
char *controller = NULL;
if (!fc)
return -EIO;
if (strcmp(path, "/cgroup") == 0) {
cgroup = NULL;
controller = NULL;
} else {
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup) {
/* this is just /cgroup/controller, return its contents */
cgroup = "/";
}
}
if (cgroup && !fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) {
return -EACCES;
}
/* we'll free this at cg_releasedir */
dir_info = malloc(sizeof(*dir_info));
if (!dir_info)
return -ENOMEM;
dir_info->controller = must_copy_string(controller);
dir_info->cgroup = must_copy_string(cgroup);
dir_info->type = LXC_TYPE_CGDIR;
dir_info->buf = NULL;
dir_info->file = NULL;
dir_info->buflen = 0;
fi->fh = (unsigned long)dir_info;
return 0;
}
Commit Message: Fix checking of parent directories
Taken from the justification in the launchpad bug:
To a task in freezer cgroup /a/b/c/d, it should appear that there are no
cgroups other than its descendents. Since this is a filesystem, we must have
the parent directories, but each parent cgroup should only contain the child
which the task can see.
So, when this task looks at /a/b, it should see only directory 'c' and no
files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already
exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x
exists or not. Opening /a/b/tasks should result in -ENOENT.
The caller_may_see_dir checks specifically whether a task may see a cgroup
directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing
opendir('/a/b/c/d').
caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at
/a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the
task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only)
directory which he can see in the path - 'c'.
Beyond this, regular DAC permissions should apply, with the
root-in-user-namespace privilege over its mapped uids being respected. The
fc_may_access check does this check for both directories and files.
This is CVE-2015-1342 (LP: #1508481)
Signed-off-by: Serge Hallyn <[email protected]>
CWE ID: CWE-264 | static int cg_opendir(const char *path, struct fuse_file_info *fi)
{
struct fuse_context *fc = fuse_get_context();
const char *cgroup;
struct file_info *dir_info;
char *controller = NULL;
if (!fc)
return -EIO;
if (strcmp(path, "/cgroup") == 0) {
cgroup = NULL;
controller = NULL;
} else {
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup) {
/* this is just /cgroup/controller, return its contents */
cgroup = "/";
}
}
if (cgroup) {
if (!caller_may_see_dir(fc->pid, controller, cgroup))
return -ENOENT;
if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY))
return -EACCES;
}
/* we'll free this at cg_releasedir */
dir_info = malloc(sizeof(*dir_info));
if (!dir_info)
return -ENOMEM;
dir_info->controller = must_copy_string(controller);
dir_info->cgroup = must_copy_string(cgroup);
dir_info->type = LXC_TYPE_CGDIR;
dir_info->buf = NULL;
dir_info->file = NULL;
dir_info->buflen = 0;
fi->fh = (unsigned long)dir_info;
return 0;
}
| 166,707 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_unwrap_iov (minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int * conf_state;
gss_qop_t *qop_state;
gss_iov_buffer_desc * iov;
int iov_count;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_unwrap_iov_args(minor_status, context_handle,
conf_state, qop_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_unwrap_iov) {
status = mech->gss_unwrap_iov(
minor_status,
ctx->internal_ctx_id,
conf_state,
qop_state,
iov,
iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_unwrap_iov (minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int * conf_state;
gss_qop_t *qop_state;
gss_iov_buffer_desc * iov;
int iov_count;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_unwrap_iov_args(minor_status, context_handle,
conf_state, qop_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_unwrap_iov) {
status = mech->gss_unwrap_iov(
minor_status,
ctx->internal_ctx_id,
conf_state,
qop_state,
iov,
iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
| 168,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void set_task_blockstep(struct task_struct *task, bool on)
{
unsigned long debugctl;
/*
* Ensure irq/preemption can't change debugctl in between.
* Note also that both TIF_BLOCKSTEP and debugctl should
* be changed atomically wrt preemption.
* FIXME: this means that set/clear TIF_BLOCKSTEP is simply
* wrong if task != current, SIGKILL can wakeup the stopped
* tracee and set/clear can play with the running task, this
* can confuse the next __switch_to_xtra().
*/
local_irq_disable();
debugctl = get_debugctlmsr();
if (on) {
debugctl |= DEBUGCTLMSR_BTF;
set_tsk_thread_flag(task, TIF_BLOCKSTEP);
} else {
debugctl &= ~DEBUGCTLMSR_BTF;
clear_tsk_thread_flag(task, TIF_BLOCKSTEP);
}
if (task == current)
update_debugctlmsr(debugctl);
local_irq_enable();
}
Commit Message: ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL
putreg() assumes that the tracee is not running and pt_regs_access() can
safely play with its stack. However a killed tracee can return from
ptrace_stop() to the low-level asm code and do RESTORE_REST, this means
that debugger can actually read/modify the kernel stack until the tracee
does SAVE_REST again.
set_task_blockstep() can race with SIGKILL too and in some sense this
race is even worse, the very fact the tracee can be woken up breaks the
logic.
As Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()
call, this ensures that nobody can ever wakeup the tracee while the
debugger looks at it. Not only this fixes the mentioned problems, we
can do some cleanups/simplifications in arch_ptrace() paths.
Probably ptrace_unfreeze_traced() needs more callers, for example it
makes sense to make the tracee killable for oom-killer before
access_process_vm().
While at it, add the comment into may_ptrace_stop() to explain why
ptrace_stop() still can't rely on SIGKILL and signal_pending_state().
Reported-by: Salman Qazi <[email protected]>
Reported-by: Suleiman Souhlal <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | void set_task_blockstep(struct task_struct *task, bool on)
{
unsigned long debugctl;
/*
* Ensure irq/preemption can't change debugctl in between.
* Note also that both TIF_BLOCKSTEP and debugctl should
* be changed atomically wrt preemption.
*
* NOTE: this means that set/clear TIF_BLOCKSTEP is only safe if
* task is current or it can't be running, otherwise we can race
* with __switch_to_xtra(). We rely on ptrace_freeze_traced() but
* PTRACE_KILL is not safe.
*/
local_irq_disable();
debugctl = get_debugctlmsr();
if (on) {
debugctl |= DEBUGCTLMSR_BTF;
set_tsk_thread_flag(task, TIF_BLOCKSTEP);
} else {
debugctl &= ~DEBUGCTLMSR_BTF;
clear_tsk_thread_flag(task, TIF_BLOCKSTEP);
}
if (task == current)
update_debugctlmsr(debugctl);
local_irq_enable();
}
| 166,135 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Initialized(mojo::ScopedSharedBufferHandle shared_buffer,
mojo::ScopedHandle socket_handle,
bool initially_muted) {
ASSERT_TRUE(shared_buffer.is_valid());
ASSERT_TRUE(socket_handle.is_valid());
base::PlatformFile fd;
mojo::UnwrapPlatformFile(std::move(socket_handle), &fd);
socket_ = std::make_unique<base::CancelableSyncSocket>(fd);
EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle);
size_t memory_length;
base::SharedMemoryHandle shmem_handle;
bool read_only;
EXPECT_EQ(
mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle,
&memory_length, &read_only),
MOJO_RESULT_OK);
EXPECT_TRUE(read_only);
buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only);
GotNotification(initially_muted);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | void Initialized(mojo::ScopedSharedBufferHandle shared_buffer,
mojo::ScopedHandle socket_handle,
bool initially_muted) {
ASSERT_TRUE(shared_buffer.is_valid());
ASSERT_TRUE(socket_handle.is_valid());
base::PlatformFile fd;
mojo::UnwrapPlatformFile(std::move(socket_handle), &fd);
socket_ = std::make_unique<base::CancelableSyncSocket>(fd);
EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle);
size_t memory_length;
base::SharedMemoryHandle shmem_handle;
mojo::UnwrappedSharedMemoryHandleProtection protection;
EXPECT_EQ(
mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle,
&memory_length, &protection),
MOJO_RESULT_OK);
EXPECT_EQ(protection,
mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly);
buffer_ = std::make_unique<base::SharedMemory>(shmem_handle,
true /* read_only */);
GotNotification(initially_muted);
}
| 172,878 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
if (external_popup_menu_ == NULL)
return;
blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItem(selected_index);
external_popup_menu_.reset();
}
Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s)
ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl.
We need to reset external_popup_menu_ before calling it.
Bug: 912211
Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc
Reviewed-on: https://chromium-review.googlesource.com/c/1381325
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618026}
CWE ID: CWE-416 | void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
if (external_popup_menu_ == NULL)
return;
blink::WebScopedUserGesture gesture(frame_);
// We need to reset |external_popup_menu_| before calling DidSelectItem(),
// which might delete |this|.
// See ExternalPopupMenuRemoveTest.RemoveFrameOnChange
std::unique_ptr<ExternalPopupMenu> popup;
popup.swap(external_popup_menu_);
popup->DidSelectItem(selected_index);
}
| 173,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
{
struct smb_rqst rqst;
struct smb2_negotiate_req *req;
struct smb2_negotiate_rsp *rsp;
struct kvec iov[1];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct TCP_Server_Info *server = ses->server;
int blob_offset, blob_length;
char *security_blob;
int flags = CIFS_NEG_OP;
unsigned int total_len;
cifs_dbg(FYI, "Negotiate protocol\n");
if (!server) {
WARN(1, "%s: server is NULL!\n", __func__);
return -EIO;
}
rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
if (rc)
return rc;
req->sync_hdr.SessionId = 0;
memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
req->DialectCount = cpu_to_le16(2);
total_len += 4;
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
req->DialectCount = cpu_to_le16(4);
total_len += 8;
} else {
/* otherwise send specific dialect */
req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
req->DialectCount = cpu_to_le16(1);
total_len += 2;
}
/* only one of SMB2 signing flags may be set in SMB2 request */
if (ses->sign)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
else if (global_secflags & CIFSSEC_MAY_SIGN)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
else
req->SecurityMode = 0;
req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
/* ClientGUID must be zero for SMB2.02 dialect */
if (ses->server->vals->protocol_id == SMB20_PROT_ID)
memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
else {
memcpy(req->ClientGUID, server->client_guid,
SMB2_CLIENT_GUID_SIZE);
if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
(strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0))
assemble_neg_contexts(req, &total_len);
}
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
/*
* No tcon so can't do
* cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
*/
if (rc == -EOPNOTSUPP) {
cifs_dbg(VFS, "Dialect not supported by server. Consider "
"specifying vers=1.0 or vers=2.0 on mount for accessing"
" older servers\n");
goto neg_exit;
} else if (rc != 0)
goto neg_exit;
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
cifs_dbg(VFS,
"SMB2.1 dialect returned but not requested\n");
return -EIO;
}
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
/* ops set to 3.0 by default for default so update */
ses->server->ops = &smb21_operations;
} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
ses->server->ops = &smb311_operations;
} else if (le16_to_cpu(rsp->DialectRevision) !=
ses->server->vals->protocol_id) {
/* if requested single dialect ensure returned dialect matched */
cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
le16_to_cpu(rsp->DialectRevision));
return -EIO;
}
cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
else {
cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
le16_to_cpu(rsp->DialectRevision));
rc = -EIO;
goto neg_exit;
}
server->dialect = le16_to_cpu(rsp->DialectRevision);
/*
* Keep a copy of the hash after negprot. This hash will be
* the starting hash value for all sessions made from this
* server.
*/
memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
SMB2_PREAUTH_HASH_SIZE);
/* SMB2 only has an extended negflavor */
server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
/* set it to the maximum buffer size value we can send with 1 credit */
server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
SMB2_MAX_BUFFER_SIZE);
server->max_read = le32_to_cpu(rsp->MaxReadSize);
server->max_write = le32_to_cpu(rsp->MaxWriteSize);
server->sec_mode = le16_to_cpu(rsp->SecurityMode);
if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
server->sec_mode);
server->capabilities = le32_to_cpu(rsp->Capabilities);
/* Internal types */
server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
(struct smb2_sync_hdr *)rsp);
/*
* See MS-SMB2 section 2.2.4: if no blob, client picks default which
* for us will be
* ses->sectype = RawNTLMSSP;
* but for time being this is our only auth choice so doesn't matter.
* We just found a server which sets blob length to zero expecting raw.
*/
if (blob_length == 0) {
cifs_dbg(FYI, "missing security blob on negprot\n");
server->sec_ntlmssp = true;
}
rc = cifs_enable_signing(server, ses->sign);
if (rc)
goto neg_exit;
if (blob_length) {
rc = decode_negTokenInit(security_blob, blob_length, server);
if (rc == 1)
rc = 0;
else if (rc == 0)
rc = -EIO;
}
if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
if (rsp->NegotiateContextCount)
rc = smb311_decode_neg_context(rsp, server,
rsp_iov.iov_len);
else
cifs_dbg(VFS, "Missing expected negotiate contexts\n");
}
neg_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
Commit Message: cifs: Fix lease buffer length error
There is a KASAN slab-out-of-bounds:
BUG: KASAN: slab-out-of-bounds in _copy_from_iter_full+0x783/0xaa0
Read of size 80 at addr ffff88810c35e180 by task mount.cifs/539
CPU: 1 PID: 539 Comm: mount.cifs Not tainted 4.19 #10
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
rel-1.12.0-0-ga698c8995f-prebuilt.qemu.org 04/01/2014
Call Trace:
dump_stack+0xdd/0x12a
print_address_description+0xa7/0x540
kasan_report+0x1ff/0x550
check_memory_region+0x2f1/0x310
memcpy+0x2f/0x80
_copy_from_iter_full+0x783/0xaa0
tcp_sendmsg_locked+0x1840/0x4140
tcp_sendmsg+0x37/0x60
inet_sendmsg+0x18c/0x490
sock_sendmsg+0xae/0x130
smb_send_kvec+0x29c/0x520
__smb_send_rqst+0x3ef/0xc60
smb_send_rqst+0x25a/0x2e0
compound_send_recv+0x9e8/0x2af0
cifs_send_recv+0x24/0x30
SMB2_open+0x35e/0x1620
open_shroot+0x27b/0x490
smb2_open_op_close+0x4e1/0x590
smb2_query_path_info+0x2ac/0x650
cifs_get_inode_info+0x1058/0x28f0
cifs_root_iget+0x3bb/0xf80
cifs_smb3_do_mount+0xe00/0x14c0
cifs_do_mount+0x15/0x20
mount_fs+0x5e/0x290
vfs_kern_mount+0x88/0x460
do_mount+0x398/0x31e0
ksys_mount+0xc6/0x150
__x64_sys_mount+0xea/0x190
do_syscall_64+0x122/0x590
entry_SYSCALL_64_after_hwframe+0x44/0xa9
It can be reproduced by the following step:
1. samba configured with: server max protocol = SMB2_10
2. mount -o vers=default
When parse the mount version parameter, the 'ops' and 'vals'
was setted to smb30, if negotiate result is smb21, just
update the 'ops' to smb21, but the 'vals' is still smb30.
When add lease context, the iov_base is allocated with smb21
ops, but the iov_len is initiallited with the smb30. Because
the iov_len is longer than iov_base, when send the message,
copy array out of bounds.
we need to keep the 'ops' and 'vals' consistent.
Fixes: 9764c02fcbad ("SMB3: Add support for multidialect negotiate (SMB2.1 and later)")
Fixes: d5c7076b772a ("smb3: add smb3.1.1 to default dialect list")
Signed-off-by: ZhangXiaoxu <[email protected]>
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]>
Reviewed-by: Pavel Shilovsky <[email protected]>
CWE ID: CWE-125 | SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
{
struct smb_rqst rqst;
struct smb2_negotiate_req *req;
struct smb2_negotiate_rsp *rsp;
struct kvec iov[1];
struct kvec rsp_iov;
int rc = 0;
int resp_buftype;
struct TCP_Server_Info *server = ses->server;
int blob_offset, blob_length;
char *security_blob;
int flags = CIFS_NEG_OP;
unsigned int total_len;
cifs_dbg(FYI, "Negotiate protocol\n");
if (!server) {
WARN(1, "%s: server is NULL!\n", __func__);
return -EIO;
}
rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
if (rc)
return rc;
req->sync_hdr.SessionId = 0;
memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
req->DialectCount = cpu_to_le16(2);
total_len += 4;
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
req->DialectCount = cpu_to_le16(4);
total_len += 8;
} else {
/* otherwise send specific dialect */
req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
req->DialectCount = cpu_to_le16(1);
total_len += 2;
}
/* only one of SMB2 signing flags may be set in SMB2 request */
if (ses->sign)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
else if (global_secflags & CIFSSEC_MAY_SIGN)
req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
else
req->SecurityMode = 0;
req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
/* ClientGUID must be zero for SMB2.02 dialect */
if (ses->server->vals->protocol_id == SMB20_PROT_ID)
memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
else {
memcpy(req->ClientGUID, server->client_guid,
SMB2_CLIENT_GUID_SIZE);
if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
(strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0))
assemble_neg_contexts(req, &total_len);
}
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
/*
* No tcon so can't do
* cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
*/
if (rc == -EOPNOTSUPP) {
cifs_dbg(VFS, "Dialect not supported by server. Consider "
"specifying vers=1.0 or vers=2.0 on mount for accessing"
" older servers\n");
goto neg_exit;
} else if (rc != 0)
goto neg_exit;
if (strcmp(ses->server->vals->version_string,
SMB3ANY_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
cifs_dbg(VFS,
"SMB2.1 dialect returned but not requested\n");
return -EIO;
}
} else if (strcmp(ses->server->vals->version_string,
SMBDEFAULT_VERSION_STRING) == 0) {
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
cifs_dbg(VFS,
"SMB2 dialect returned but not requested\n");
return -EIO;
} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
/* ops set to 3.0 by default for default so update */
ses->server->ops = &smb21_operations;
ses->server->vals = &smb21_values;
} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
ses->server->ops = &smb311_operations;
ses->server->vals = &smb311_values;
}
} else if (le16_to_cpu(rsp->DialectRevision) !=
ses->server->vals->protocol_id) {
/* if requested single dialect ensure returned dialect matched */
cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
le16_to_cpu(rsp->DialectRevision));
return -EIO;
}
cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
else {
cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
le16_to_cpu(rsp->DialectRevision));
rc = -EIO;
goto neg_exit;
}
server->dialect = le16_to_cpu(rsp->DialectRevision);
/*
* Keep a copy of the hash after negprot. This hash will be
* the starting hash value for all sessions made from this
* server.
*/
memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
SMB2_PREAUTH_HASH_SIZE);
/* SMB2 only has an extended negflavor */
server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
/* set it to the maximum buffer size value we can send with 1 credit */
server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
SMB2_MAX_BUFFER_SIZE);
server->max_read = le32_to_cpu(rsp->MaxReadSize);
server->max_write = le32_to_cpu(rsp->MaxWriteSize);
server->sec_mode = le16_to_cpu(rsp->SecurityMode);
if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
server->sec_mode);
server->capabilities = le32_to_cpu(rsp->Capabilities);
/* Internal types */
server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
(struct smb2_sync_hdr *)rsp);
/*
* See MS-SMB2 section 2.2.4: if no blob, client picks default which
* for us will be
* ses->sectype = RawNTLMSSP;
* but for time being this is our only auth choice so doesn't matter.
* We just found a server which sets blob length to zero expecting raw.
*/
if (blob_length == 0) {
cifs_dbg(FYI, "missing security blob on negprot\n");
server->sec_ntlmssp = true;
}
rc = cifs_enable_signing(server, ses->sign);
if (rc)
goto neg_exit;
if (blob_length) {
rc = decode_negTokenInit(security_blob, blob_length, server);
if (rc == 1)
rc = 0;
else if (rc == 0)
rc = -EIO;
}
if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
if (rsp->NegotiateContextCount)
rc = smb311_decode_neg_context(rsp, server,
rsp_iov.iov_len);
else
cifs_dbg(VFS, "Missing expected negotiate contexts\n");
}
neg_exit:
free_rsp_buf(resp_buftype, rsp);
return rc;
}
| 169,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
int free_query_string = 0;
int exit_status = SUCCESS;
int cgi = 0, c, i, len;
zend_file_handle file_handle;
char *s;
/* temporary locals */
int behavior = PHP_MODE_STANDARD;
int no_headers = 0;
int orig_optind = php_optind;
char *orig_optarg = php_optarg;
char *script_file = NULL;
int ini_entries_len = 0;
/* end of temporary locals */
#ifdef ZTS
void ***tsrm_ls;
#endif
int max_requests = 500;
int requests = 0;
int fastcgi;
char *bindpath = NULL;
int fcgi_fd = 0;
fcgi_request *request = NULL;
int repeats = 1;
int benchmark = 0;
#if HAVE_GETTIMEOFDAY
struct timeval start, end;
#else
time_t start, end;
#endif
#ifndef PHP_WIN32
int status = 0;
#endif
char *query_string;
char *decoded_query_string;
int skip_getopt = 0;
#if 0 && defined(PHP_DEBUG)
/* IIS is always making things more difficult. This allows
* us to stop PHP and attach a debugger before much gets started */
{
char szMessage [256];
wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
}
#endif
#ifdef HAVE_SIGNAL_H
#if defined(SIGPIPE) && defined(SIG_IGN)
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
that sockets created via fsockopen()
don't kill PHP if the remote site
closes it. in apache|apxs mode apache
does that for us! [email protected]
20000419 */
#endif
#endif
#ifdef ZTS
tsrm_startup(1, 1, 0, NULL);
tsrm_ls = ts_resource(0);
#endif
sapi_startup(&cgi_sapi_module);
fastcgi = fcgi_is_fastcgi();
cgi_sapi_module.php_ini_path_override = NULL;
#ifdef PHP_WIN32
_fmode = _O_BINARY; /* sets default for file streams to binary */
setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
#endif
if (!fastcgi) {
/* Make sure we detect we are a cgi - a bit redundancy here,
* but the default case is that we have to check only the first one. */
if (getenv("SERVER_SOFTWARE") ||
getenv("SERVER_NAME") ||
getenv("GATEWAY_INTERFACE") ||
getenv("REQUEST_METHOD")
) {
cgi = 1;
}
}
if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
/* we've got query string that has no = - apache CGI will pass it to command line */
unsigned char *p;
decoded_query_string = strdup(query_string);
php_url_decode(decoded_query_string, strlen(decoded_query_string));
for (p = decoded_query_string; *p && *p <= ' '; p++) {
/* skip all leading spaces */
}
if(*p == '-') {
skip_getopt = 1;
}
free(decoded_query_string);
}
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'c':
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
break;
case 'n':
cgi_sapi_module.php_ini_ignore = 1;
break;
case 'd': {
/* define ini entries on command line */
int len = strlen(php_optarg);
char *val;
if ((val = strchr(php_optarg, '='))) {
val++;
if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
ini_entries_len += (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
ini_entries_len++;
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
ini_entries_len += len - (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
ini_entries_len += sizeof("\n\0\"") - 2;
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
ini_entries_len += len + sizeof("\n\0") - 2;
}
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
ini_entries_len += len + sizeof("=1\n\0") - 2;
}
break;
}
/* if we're started on command line, check to see if
* we are being started as an 'external' fastcgi
* server by accepting a bindpath parameter. */
case 'b':
if (!fastcgi) {
bindpath = strdup(php_optarg);
}
break;
case 's': /* generate highlighted HTML from source */
behavior = PHP_MODE_HIGHLIGHT;
break;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
if (fastcgi || bindpath) {
/* Override SAPI callbacks */
cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
cgi_sapi_module.flush = sapi_fcgi_flush;
cgi_sapi_module.read_post = sapi_fcgi_read_post;
cgi_sapi_module.getenv = sapi_fcgi_getenv;
cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
}
#ifdef ZTS
SG(request_info).path_translated = NULL;
#endif
cgi_sapi_module.executable_location = argv[0];
if (!cgi && !fastcgi && !bindpath) {
cgi_sapi_module.additional_functions = additional_functions;
}
/* startup after we get the above ini override se we get things right */
if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
/* check force_cgi after startup, so we have proper output */
if (cgi && CGIG(force_redirect)) {
/* Apache will generate REDIRECT_STATUS,
* Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
* redirect.so and installation instructions available from
* http://www.koehntopp.de/php.
* -- [email protected]
*/
if (!getenv("REDIRECT_STATUS") &&
!getenv ("HTTP_REDIRECT_STATUS") &&
/* this is to allow a different env var to be configured
* in case some server does something different than above */
(!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
) {
zend_try {
SG(sapi_headers).http_response_code = 400;
PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
<p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
set, e.g. via an Apache Action directive.</p>\n\
<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
manual page for CGI security</a>.</p>\n\
<p>For more information about changing this behaviour or re-enabling this webserver,\n\
consult the installation file that came with this distribution, or visit \n\
<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
} zend_catch {
} zend_end_try();
#if defined(ZTS) && !defined(PHP_DEBUG)
/* XXX we're crashing here in msvc6 debug builds at
* php_message_handler_for_zend:839 because
* SG(request_info).path_translated is an invalid pointer.
* It still happens even though I set it to null, so something
* weird is going on.
*/
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (bindpath) {
fcgi_fd = fcgi_listen(bindpath, 128);
if (fcgi_fd < 0) {
fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
fastcgi = fcgi_is_fastcgi();
}
if (fastcgi) {
/* How many times to run PHP scripts before dying */
if (getenv("PHP_FCGI_MAX_REQUESTS")) {
max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
if (max_requests < 0) {
fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
return FAILURE;
}
}
/* make php call us to get _ENV vars */
php_php_import_environment_variables = php_import_environment_variables;
php_import_environment_variables = cgi_php_import_environment_variables;
/* library is already initialized, now init our request */
request = fcgi_init_request(fcgi_fd);
#ifndef PHP_WIN32
/* Pre-fork, if required */
if (getenv("PHP_FCGI_CHILDREN")) {
char * children_str = getenv("PHP_FCGI_CHILDREN");
children = atoi(children_str);
if (children < 0) {
fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
return FAILURE;
}
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
/* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
} else {
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
}
if (children) {
int running = 0;
pid_t pid;
/* Create a process group for ourself & children */
setsid();
pgroup = getpgrp();
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Process group %d\n", pgroup);
#endif
/* Set up handler to kill children upon exit */
act.sa_flags = 0;
act.sa_handler = fastcgi_cleanup;
if (sigaction(SIGTERM, &act, &old_term) ||
sigaction(SIGINT, &act, &old_int) ||
sigaction(SIGQUIT, &act, &old_quit)
) {
perror("Can't set signals");
exit(1);
}
if (fcgi_in_shutdown()) {
goto parent_out;
}
while (parent) {
do {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Forking, %d running\n", running);
#endif
pid = fork();
switch (pid) {
case 0:
/* One of the children.
* Make sure we don't go round the
* fork loop any more
*/
parent = 0;
/* don't catch our signals */
sigaction(SIGTERM, &old_term, 0);
sigaction(SIGQUIT, &old_quit, 0);
sigaction(SIGINT, &old_int, 0);
break;
case -1:
perror("php (pre-forking)");
exit(1);
break;
default:
/* Fine */
running++;
break;
}
} while (parent && (running < children));
if (parent) {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Wait for kids, pid %d\n", getpid());
#endif
parent_waiting = 1;
while (1) {
if (wait(&status) >= 0) {
running--;
break;
} else if (exit_signal) {
break;
}
}
if (exit_signal) {
#if 0
while (running > 0) {
while (wait(&status) < 0) {
}
running--;
}
#endif
goto parent_out;
}
}
}
} else {
parent = 0;
}
#endif /* WIN32 */
}
zend_first_try {
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
switch (c) {
case 'T':
benchmark = 1;
repeats = atoi(php_optarg);
#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&start, NULL);
#else
time(&start);
#endif
break;
case 'h':
case '?':
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
no_headers = 1;
SG(headers_sent) = 1;
php_cgi_usage(argv[0]);
php_output_end_all(TSRMLS_C);
exit_status = 0;
goto out;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
/* start of FAST CGI loop */
/* Initialise FastCGI request structure */
#ifdef PHP_WIN32
/* attempt to set security impersonation for fastcgi
* will only happen on NT based OS, others will ignore it. */
if (fastcgi && CGIG(impersonate)) {
fcgi_impersonate();
}
#endif
while (!fastcgi || fcgi_accept_request(request) >= 0) {
SG(server_context) = fastcgi ? (void *) request : (void *) 1;
init_request_info(request TSRMLS_CC);
CG(interactive) = 0;
if (!cgi && !fastcgi) {
while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'a': /* interactive mode */
printf("Interactive mode enabled\n\n");
CG(interactive) = 1;
break;
case 'C': /* don't chdir to the script directory */
SG(options) |= SAPI_OPTION_NO_CHDIR;
break;
case 'e': /* enable extended info output */
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
break;
case 'f': /* parse file */
if (script_file) {
efree(script_file);
}
script_file = estrdup(php_optarg);
no_headers = 1;
break;
case 'i': /* php info & quit */
if (script_file) {
efree(script_file);
}
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
php_print_info(0xFFFFFFFF TSRMLS_CC);
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'l': /* syntax check mode */
no_headers = 1;
behavior = PHP_MODE_LINT;
break;
case 'm': /* list compiled in modules */
if (script_file) {
efree(script_file);
}
SG(headers_sent) = 1;
php_printf("[PHP Modules]\n");
print_modules(TSRMLS_C);
php_printf("\n[Zend Modules]\n");
print_extensions(TSRMLS_C);
php_printf("\n");
php_output_end_all(TSRMLS_C);
fcgi_shutdown();
exit_status = 0;
goto out;
#if 0 /* not yet operational, see also below ... */
case '': /* generate indented source mode*/
behavior=PHP_MODE_INDENT;
break;
#endif
case 'q': /* do not generate HTTP headers */
no_headers = 1;
break;
case 'v': /* show php version & quit */
if (script_file) {
efree(script_file);
}
no_headers = 1;
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
#if ZEND_DEBUG
php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#else
php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#endif
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'w':
behavior = PHP_MODE_STRIP;
break;
case 'z': /* load extension file */
zend_load_extension(php_optarg);
break;
default:
break;
}
}
if (script_file) {
/* override path_translated if -f on command line */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = script_file;
/* before registering argv to module exchange the *new* argv[0] */
/* we can achieve this without allocating more memory */
SG(request_info).argc = argc - (php_optind - 1);
SG(request_info).argv = &argv[php_optind - 1];
SG(request_info).argv[0] = script_file;
} else if (argc > php_optind) {
/* file is on command line, but not in -f opt */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = estrdup(argv[php_optind]);
/* arguments after the file are considered script args */
SG(request_info).argc = argc - php_optind;
SG(request_info).argv = &argv[php_optind];
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/* all remaining arguments are part of the query string
* this section of code concatenates all remaining arguments
* into a single string, seperating args with a &
* this allows command lines like:
*
* test.php v1=test v2=hello+world!
* test.php "v1=test&v2=hello world!"
* test.php v1=test "v2=hello world!"
*/
if (!SG(request_info).query_string && argc > php_optind) {
int slen = strlen(PG(arg_separator).input);
len = 0;
for (i = php_optind; i < argc; i++) {
if (i < (argc - 1)) {
len += strlen(argv[i]) + slen;
} else {
len += strlen(argv[i]);
}
}
len += 2;
s = malloc(len);
*s = '\0'; /* we are pretending it came from the environment */
for (i = php_optind; i < argc; i++) {
strlcat(s, argv[i], len);
if (i < (argc - 1)) {
strlcat(s, PG(arg_separator).input, len);
}
}
SG(request_info).query_string = s;
free_query_string = 1;
}
} /* end !cgi && !fastcgi */
/*
we never take stdin if we're (f)cgi, always
rely on the web server giving us the info
we need in the environment.
*/
if (SG(request_info).path_translated || cgi || fastcgi) {
file_handle.type = ZEND_HANDLE_FILENAME;
file_handle.filename = SG(request_info).path_translated;
file_handle.handle.fp = NULL;
} else {
file_handle.filename = "-";
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = stdin;
}
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* request startup only after we've done all we can to
* get path_translated */
if (php_request_startup(TSRMLS_C) == FAILURE) {
if (fastcgi) {
fcgi_finish_request(request, 1);
}
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/*
at this point path_translated will be set if:
1. we are running from shell and got filename was there
2. we are running as cgi or fastcgi
*/
if (cgi || fastcgi || SG(request_info).path_translated) {
if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
zend_try {
if (errno == EACCES) {
SG(sapi_headers).http_response_code = 403;
PUTS("Access denied.\n");
} else {
SG(sapi_headers).http_response_code = 404;
PUTS("No input file specified.\n");
}
} zend_catch {
} zend_end_try();
/* we want to serve more requests if this is fastcgi
* so cleanup and continue, request shutdown is
* handled later */
if (fastcgi) {
goto fastcgi_request_done;
}
STR_FREE(SG(request_info).path_translated);
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
php_request_shutdown((void *) 0);
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (CGIG(check_shebang_line)) {
/* #!php support */
switch (file_handle.type) {
case ZEND_HANDLE_FD:
if (file_handle.handle.fd < 0) {
break;
}
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
/* break missing intentionally */
case ZEND_HANDLE_FP:
if (!file_handle.handle.fp ||
(file_handle.handle.fp == stdin)) {
break;
}
c = fgetc(file_handle.handle.fp);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = fgetc(file_handle.handle.fp); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (fgetc(file_handle.handle.fp) != '\n') {
long pos = ftell(file_handle.handle.fp);
fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
rewind(file_handle.handle.fp);
}
break;
case ZEND_HANDLE_STREAM:
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
}
break;
case ZEND_HANDLE_MAPPED:
if (file_handle.handle.stream.mmap.buf[0] == '#') {
int i = 1;
c = file_handle.handle.stream.mmap.buf[i++];
while (c != '\n' && c != '\r' && c != EOF) {
c = file_handle.handle.stream.mmap.buf[i++];
}
if (c == '\r') {
if (file_handle.handle.stream.mmap.buf[i] == '\n') {
i++;
}
}
file_handle.handle.stream.mmap.buf += i;
file_handle.handle.stream.mmap.len -= i;
}
}
}
switch (behavior) {
case PHP_MODE_STANDARD:
php_execute_script(&file_handle TSRMLS_CC);
break;
case PHP_MODE_LINT:
PG(during_request_startup) = 0;
exit_status = php_lint_script(&file_handle TSRMLS_CC);
if (exit_status == SUCCESS) {
zend_printf("No syntax errors detected in %s\n", file_handle.filename);
} else {
zend_printf("Errors parsing %s\n", file_handle.filename);
}
break;
case PHP_MODE_STRIP:
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
zend_strip(TSRMLS_C);
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
break;
case PHP_MODE_HIGHLIGHT:
{
zend_syntax_highlighter_ini syntax_highlighter_ini;
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
php_get_highlight_struct(&syntax_highlighter_ini);
zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
if (fastcgi) {
goto fastcgi_request_done;
}
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
}
break;
#if 0
/* Zeev might want to do something with this one day */
case PHP_MODE_INDENT:
open_file_for_scanning(&file_handle TSRMLS_CC);
zend_indent();
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
return SUCCESS;
break;
#endif
}
fastcgi_request_done:
{
STR_FREE(SG(request_info).path_translated);
php_request_shutdown((void *) 0);
if (exit_status == 0) {
exit_status = EG(exit_status);
}
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
}
if (!fastcgi) {
if (benchmark) {
repeats--;
if (repeats > 0) {
script_file = NULL;
php_optind = orig_optind;
php_optarg = orig_optarg;
continue;
}
}
break;
}
/* only fastcgi will get here */
requests++;
if (max_requests && (requests == max_requests)) {
fcgi_finish_request(request, 1);
if (bindpath) {
free(bindpath);
}
if (max_requests != 1) {
/* no need to return exit_status of the last request */
exit_status = 0;
}
break;
}
/* end of fastcgi loop */
}
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
if (cgi_sapi_module.ini_entries) {
free(cgi_sapi_module.ini_entries);
}
} zend_catch {
exit_status = 255;
} zend_end_try();
out:
if (benchmark) {
int sec;
#ifdef HAVE_GETTIMEOFDAY
int usec;
gettimeofday(&end, NULL);
sec = (int)(end.tv_sec - start.tv_sec);
if (end.tv_usec >= start.tv_usec) {
usec = (int)(end.tv_usec - start.tv_usec);
} else {
sec -= 1;
usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
}
fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
#else
time(&end);
sec = (int)(end - start);
fprintf(stderr, "\nElapsed time: %d sec\n", sec);
#endif
}
#ifndef PHP_WIN32
parent_out:
#endif
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
#if defined(PHP_WIN32) && ZEND_DEBUG && 0
_CrtDumpMemoryLeaks();
#endif
return exit_status;
}
Commit Message:
CWE ID: CWE-119 | int main(int argc, char *argv[])
{
int free_query_string = 0;
int exit_status = SUCCESS;
int cgi = 0, c, i, len;
zend_file_handle file_handle;
char *s;
/* temporary locals */
int behavior = PHP_MODE_STANDARD;
int no_headers = 0;
int orig_optind = php_optind;
char *orig_optarg = php_optarg;
char *script_file = NULL;
int ini_entries_len = 0;
/* end of temporary locals */
#ifdef ZTS
void ***tsrm_ls;
#endif
int max_requests = 500;
int requests = 0;
int fastcgi;
char *bindpath = NULL;
int fcgi_fd = 0;
fcgi_request *request = NULL;
int repeats = 1;
int benchmark = 0;
#if HAVE_GETTIMEOFDAY
struct timeval start, end;
#else
time_t start, end;
#endif
#ifndef PHP_WIN32
int status = 0;
#endif
char *query_string;
char *decoded_query_string;
int skip_getopt = 0;
#if 0 && defined(PHP_DEBUG)
/* IIS is always making things more difficult. This allows
* us to stop PHP and attach a debugger before much gets started */
{
char szMessage [256];
wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
}
#endif
#ifdef HAVE_SIGNAL_H
#if defined(SIGPIPE) && defined(SIG_IGN)
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
that sockets created via fsockopen()
don't kill PHP if the remote site
closes it. in apache|apxs mode apache
does that for us! [email protected]
20000419 */
#endif
#endif
#ifdef ZTS
tsrm_startup(1, 1, 0, NULL);
tsrm_ls = ts_resource(0);
#endif
sapi_startup(&cgi_sapi_module);
fastcgi = fcgi_is_fastcgi();
cgi_sapi_module.php_ini_path_override = NULL;
#ifdef PHP_WIN32
_fmode = _O_BINARY; /* sets default for file streams to binary */
setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
#endif
if (!fastcgi) {
/* Make sure we detect we are a cgi - a bit redundancy here,
* but the default case is that we have to check only the first one. */
if (getenv("SERVER_SOFTWARE") ||
getenv("SERVER_NAME") ||
getenv("GATEWAY_INTERFACE") ||
getenv("REQUEST_METHOD")
) {
cgi = 1;
}
}
if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
/* we've got query string that has no = - apache CGI will pass it to command line */
unsigned char *p;
decoded_query_string = strdup(query_string);
php_url_decode(decoded_query_string, strlen(decoded_query_string));
for (p = decoded_query_string; *p && *p <= ' '; p++) {
/* skip all leading spaces */
}
if(*p == '-') {
skip_getopt = 1;
}
free(decoded_query_string);
}
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'c':
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
break;
case 'n':
cgi_sapi_module.php_ini_ignore = 1;
break;
case 'd': {
/* define ini entries on command line */
int len = strlen(php_optarg);
char *val;
if ((val = strchr(php_optarg, '='))) {
val++;
if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
ini_entries_len += (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
ini_entries_len++;
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
ini_entries_len += len - (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
ini_entries_len += sizeof("\n\0\"") - 2;
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
ini_entries_len += len + sizeof("\n\0") - 2;
}
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
ini_entries_len += len + sizeof("=1\n\0") - 2;
}
break;
}
/* if we're started on command line, check to see if
* we are being started as an 'external' fastcgi
* server by accepting a bindpath parameter. */
case 'b':
if (!fastcgi) {
bindpath = strdup(php_optarg);
}
break;
case 's': /* generate highlighted HTML from source */
behavior = PHP_MODE_HIGHLIGHT;
break;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
if (fastcgi || bindpath) {
/* Override SAPI callbacks */
cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
cgi_sapi_module.flush = sapi_fcgi_flush;
cgi_sapi_module.read_post = sapi_fcgi_read_post;
cgi_sapi_module.getenv = sapi_fcgi_getenv;
cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
}
#ifdef ZTS
SG(request_info).path_translated = NULL;
#endif
cgi_sapi_module.executable_location = argv[0];
if (!cgi && !fastcgi && !bindpath) {
cgi_sapi_module.additional_functions = additional_functions;
}
/* startup after we get the above ini override se we get things right */
if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
/* check force_cgi after startup, so we have proper output */
if (cgi && CGIG(force_redirect)) {
/* Apache will generate REDIRECT_STATUS,
* Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
* redirect.so and installation instructions available from
* http://www.koehntopp.de/php.
* -- [email protected]
*/
if (!getenv("REDIRECT_STATUS") &&
!getenv ("HTTP_REDIRECT_STATUS") &&
/* this is to allow a different env var to be configured
* in case some server does something different than above */
(!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
) {
zend_try {
SG(sapi_headers).http_response_code = 400;
PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
<p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
set, e.g. via an Apache Action directive.</p>\n\
<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
manual page for CGI security</a>.</p>\n\
<p>For more information about changing this behaviour or re-enabling this webserver,\n\
consult the installation file that came with this distribution, or visit \n\
<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
} zend_catch {
} zend_end_try();
#if defined(ZTS) && !defined(PHP_DEBUG)
/* XXX we're crashing here in msvc6 debug builds at
* php_message_handler_for_zend:839 because
* SG(request_info).path_translated is an invalid pointer.
* It still happens even though I set it to null, so something
* weird is going on.
*/
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (bindpath) {
fcgi_fd = fcgi_listen(bindpath, 128);
if (fcgi_fd < 0) {
fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
fastcgi = fcgi_is_fastcgi();
}
if (fastcgi) {
/* How many times to run PHP scripts before dying */
if (getenv("PHP_FCGI_MAX_REQUESTS")) {
max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
if (max_requests < 0) {
fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
return FAILURE;
}
}
/* make php call us to get _ENV vars */
php_php_import_environment_variables = php_import_environment_variables;
php_import_environment_variables = cgi_php_import_environment_variables;
/* library is already initialized, now init our request */
request = fcgi_init_request(fcgi_fd);
#ifndef PHP_WIN32
/* Pre-fork, if required */
if (getenv("PHP_FCGI_CHILDREN")) {
char * children_str = getenv("PHP_FCGI_CHILDREN");
children = atoi(children_str);
if (children < 0) {
fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
return FAILURE;
}
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
/* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
} else {
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
}
if (children) {
int running = 0;
pid_t pid;
/* Create a process group for ourself & children */
setsid();
pgroup = getpgrp();
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Process group %d\n", pgroup);
#endif
/* Set up handler to kill children upon exit */
act.sa_flags = 0;
act.sa_handler = fastcgi_cleanup;
if (sigaction(SIGTERM, &act, &old_term) ||
sigaction(SIGINT, &act, &old_int) ||
sigaction(SIGQUIT, &act, &old_quit)
) {
perror("Can't set signals");
exit(1);
}
if (fcgi_in_shutdown()) {
goto parent_out;
}
while (parent) {
do {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Forking, %d running\n", running);
#endif
pid = fork();
switch (pid) {
case 0:
/* One of the children.
* Make sure we don't go round the
* fork loop any more
*/
parent = 0;
/* don't catch our signals */
sigaction(SIGTERM, &old_term, 0);
sigaction(SIGQUIT, &old_quit, 0);
sigaction(SIGINT, &old_int, 0);
break;
case -1:
perror("php (pre-forking)");
exit(1);
break;
default:
/* Fine */
running++;
break;
}
} while (parent && (running < children));
if (parent) {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Wait for kids, pid %d\n", getpid());
#endif
parent_waiting = 1;
while (1) {
if (wait(&status) >= 0) {
running--;
break;
} else if (exit_signal) {
break;
}
}
if (exit_signal) {
#if 0
while (running > 0) {
while (wait(&status) < 0) {
}
running--;
}
#endif
goto parent_out;
}
}
}
} else {
parent = 0;
}
#endif /* WIN32 */
}
zend_first_try {
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
switch (c) {
case 'T':
benchmark = 1;
repeats = atoi(php_optarg);
#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&start, NULL);
#else
time(&start);
#endif
break;
case 'h':
case '?':
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
no_headers = 1;
SG(headers_sent) = 1;
php_cgi_usage(argv[0]);
php_output_end_all(TSRMLS_C);
exit_status = 0;
goto out;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
/* start of FAST CGI loop */
/* Initialise FastCGI request structure */
#ifdef PHP_WIN32
/* attempt to set security impersonation for fastcgi
* will only happen on NT based OS, others will ignore it. */
if (fastcgi && CGIG(impersonate)) {
fcgi_impersonate();
}
#endif
while (!fastcgi || fcgi_accept_request(request) >= 0) {
SG(server_context) = fastcgi ? (void *) request : (void *) 1;
init_request_info(request TSRMLS_CC);
CG(interactive) = 0;
if (!cgi && !fastcgi) {
while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'a': /* interactive mode */
printf("Interactive mode enabled\n\n");
CG(interactive) = 1;
break;
case 'C': /* don't chdir to the script directory */
SG(options) |= SAPI_OPTION_NO_CHDIR;
break;
case 'e': /* enable extended info output */
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
break;
case 'f': /* parse file */
if (script_file) {
efree(script_file);
}
script_file = estrdup(php_optarg);
no_headers = 1;
break;
case 'i': /* php info & quit */
if (script_file) {
efree(script_file);
}
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
php_print_info(0xFFFFFFFF TSRMLS_CC);
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'l': /* syntax check mode */
no_headers = 1;
behavior = PHP_MODE_LINT;
break;
case 'm': /* list compiled in modules */
if (script_file) {
efree(script_file);
}
SG(headers_sent) = 1;
php_printf("[PHP Modules]\n");
print_modules(TSRMLS_C);
php_printf("\n[Zend Modules]\n");
print_extensions(TSRMLS_C);
php_printf("\n");
php_output_end_all(TSRMLS_C);
fcgi_shutdown();
exit_status = 0;
goto out;
#if 0 /* not yet operational, see also below ... */
case '': /* generate indented source mode*/
behavior=PHP_MODE_INDENT;
break;
#endif
case 'q': /* do not generate HTTP headers */
no_headers = 1;
break;
case 'v': /* show php version & quit */
if (script_file) {
efree(script_file);
}
no_headers = 1;
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
#if ZEND_DEBUG
php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#else
php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#endif
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'w':
behavior = PHP_MODE_STRIP;
break;
case 'z': /* load extension file */
zend_load_extension(php_optarg);
break;
default:
break;
}
}
if (script_file) {
/* override path_translated if -f on command line */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = script_file;
/* before registering argv to module exchange the *new* argv[0] */
/* we can achieve this without allocating more memory */
SG(request_info).argc = argc - (php_optind - 1);
SG(request_info).argv = &argv[php_optind - 1];
SG(request_info).argv[0] = script_file;
} else if (argc > php_optind) {
/* file is on command line, but not in -f opt */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = estrdup(argv[php_optind]);
/* arguments after the file are considered script args */
SG(request_info).argc = argc - php_optind;
SG(request_info).argv = &argv[php_optind];
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/* all remaining arguments are part of the query string
* this section of code concatenates all remaining arguments
* into a single string, seperating args with a &
* this allows command lines like:
*
* test.php v1=test v2=hello+world!
* test.php "v1=test&v2=hello world!"
* test.php v1=test "v2=hello world!"
*/
if (!SG(request_info).query_string && argc > php_optind) {
int slen = strlen(PG(arg_separator).input);
len = 0;
for (i = php_optind; i < argc; i++) {
if (i < (argc - 1)) {
len += strlen(argv[i]) + slen;
} else {
len += strlen(argv[i]);
}
}
len += 2;
s = malloc(len);
*s = '\0'; /* we are pretending it came from the environment */
for (i = php_optind; i < argc; i++) {
strlcat(s, argv[i], len);
if (i < (argc - 1)) {
strlcat(s, PG(arg_separator).input, len);
}
}
SG(request_info).query_string = s;
free_query_string = 1;
}
} /* end !cgi && !fastcgi */
/*
we never take stdin if we're (f)cgi, always
rely on the web server giving us the info
we need in the environment.
*/
if (SG(request_info).path_translated || cgi || fastcgi) {
file_handle.type = ZEND_HANDLE_FILENAME;
file_handle.filename = SG(request_info).path_translated;
file_handle.handle.fp = NULL;
} else {
file_handle.filename = "-";
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = stdin;
}
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* request startup only after we've done all we can to
* get path_translated */
if (php_request_startup(TSRMLS_C) == FAILURE) {
if (fastcgi) {
fcgi_finish_request(request, 1);
}
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/*
at this point path_translated will be set if:
1. we are running from shell and got filename was there
2. we are running as cgi or fastcgi
*/
if (cgi || fastcgi || SG(request_info).path_translated) {
if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
zend_try {
if (errno == EACCES) {
SG(sapi_headers).http_response_code = 403;
PUTS("Access denied.\n");
} else {
SG(sapi_headers).http_response_code = 404;
PUTS("No input file specified.\n");
}
} zend_catch {
} zend_end_try();
/* we want to serve more requests if this is fastcgi
* so cleanup and continue, request shutdown is
* handled later */
if (fastcgi) {
goto fastcgi_request_done;
}
STR_FREE(SG(request_info).path_translated);
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
php_request_shutdown((void *) 0);
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (CGIG(check_shebang_line)) {
/* #!php support */
switch (file_handle.type) {
case ZEND_HANDLE_FD:
if (file_handle.handle.fd < 0) {
break;
}
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
/* break missing intentionally */
case ZEND_HANDLE_FP:
if (!file_handle.handle.fp ||
(file_handle.handle.fp == stdin)) {
break;
}
c = fgetc(file_handle.handle.fp);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = fgetc(file_handle.handle.fp); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (fgetc(file_handle.handle.fp) != '\n') {
long pos = ftell(file_handle.handle.fp);
fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
rewind(file_handle.handle.fp);
}
break;
case ZEND_HANDLE_STREAM:
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
}
break;
case ZEND_HANDLE_MAPPED:
if (file_handle.handle.stream.mmap.buf[0] == '#') {
int i = 1;
c = file_handle.handle.stream.mmap.buf[i++];
while (c != '\n' && c != '\r' && i < file_handle.handle.stream.mmap.len) {
c = file_handle.handle.stream.mmap.buf[i++];
}
if (c == '\r') {
if (i < file_handle.handle.stream.mmap.len && file_handle.handle.stream.mmap.buf[i] == '\n') {
i++;
}
}
if(i > file_handle.handle.stream.mmap.len) {
i = file_handle.handle.stream.mmap.len;
}
file_handle.handle.stream.mmap.buf += i;
file_handle.handle.stream.mmap.len -= i;
}
}
}
switch (behavior) {
case PHP_MODE_STANDARD:
php_execute_script(&file_handle TSRMLS_CC);
break;
case PHP_MODE_LINT:
PG(during_request_startup) = 0;
exit_status = php_lint_script(&file_handle TSRMLS_CC);
if (exit_status == SUCCESS) {
zend_printf("No syntax errors detected in %s\n", file_handle.filename);
} else {
zend_printf("Errors parsing %s\n", file_handle.filename);
}
break;
case PHP_MODE_STRIP:
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
zend_strip(TSRMLS_C);
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
break;
case PHP_MODE_HIGHLIGHT:
{
zend_syntax_highlighter_ini syntax_highlighter_ini;
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
php_get_highlight_struct(&syntax_highlighter_ini);
zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
if (fastcgi) {
goto fastcgi_request_done;
}
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
}
break;
#if 0
/* Zeev might want to do something with this one day */
case PHP_MODE_INDENT:
open_file_for_scanning(&file_handle TSRMLS_CC);
zend_indent();
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
return SUCCESS;
break;
#endif
}
fastcgi_request_done:
{
STR_FREE(SG(request_info).path_translated);
php_request_shutdown((void *) 0);
if (exit_status == 0) {
exit_status = EG(exit_status);
}
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
}
if (!fastcgi) {
if (benchmark) {
repeats--;
if (repeats > 0) {
script_file = NULL;
php_optind = orig_optind;
php_optarg = orig_optarg;
continue;
}
}
break;
}
/* only fastcgi will get here */
requests++;
if (max_requests && (requests == max_requests)) {
fcgi_finish_request(request, 1);
if (bindpath) {
free(bindpath);
}
if (max_requests != 1) {
/* no need to return exit_status of the last request */
exit_status = 0;
}
break;
}
/* end of fastcgi loop */
}
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
if (cgi_sapi_module.ini_entries) {
free(cgi_sapi_module.ini_entries);
}
} zend_catch {
exit_status = 255;
} zend_end_try();
out:
if (benchmark) {
int sec;
#ifdef HAVE_GETTIMEOFDAY
int usec;
gettimeofday(&end, NULL);
sec = (int)(end.tv_sec - start.tv_sec);
if (end.tv_usec >= start.tv_usec) {
usec = (int)(end.tv_usec - start.tv_usec);
} else {
sec -= 1;
usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
}
fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
#else
time(&end);
sec = (int)(end - start);
fprintf(stderr, "\nElapsed time: %d sec\n", sec);
#endif
}
#ifndef PHP_WIN32
parent_out:
#endif
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
#if defined(PHP_WIN32) && ZEND_DEBUG && 0
_CrtDumpMemoryLeaks();
#endif
return exit_status;
}
| 164,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv)
{
volatile int summary = 1; /* Print the error summary at the end */
volatile int memstats = 0; /* Print memory statistics at the end */
/* Create the given output file on success: */
PNG_CONST char *volatile touch = NULL;
/* This is an array of standard gamma values (believe it or not I've seen
* every one of these mentioned somewhere.)
*
* In the following list the most useful values are first!
*/
static double
gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
/* This records the command and arguments: */
size_t cp = 0;
char command[1024];
anon_context(&pm.this);
/* Add appropriate signal handlers, just the ANSI specified ones: */
signal(SIGABRT, signal_handler);
signal(SIGFPE, signal_handler);
signal(SIGILL, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGSEGV, signal_handler);
signal(SIGTERM, signal_handler);
#ifdef HAVE_FEENABLEEXCEPT
/* Only required to enable FP exceptions on platforms where they start off
* disabled; this is not necessary but if it is not done pngvalid will likely
* end up ignoring FP conditions that other platforms fault.
*/
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
modifier_init(&pm);
/* Preallocate the image buffer, because we know how big it needs to be,
* note that, for testing purposes, it is deliberately mis-aligned by tag
* bytes either side. All rows have an additional five bytes of padding for
* overwrite checking.
*/
store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
/* Don't give argv[0], it's normally some horrible libtool string: */
cp = safecat(command, sizeof command, cp, "pngvalid");
/* Default to error on warning: */
pm.this.treat_warnings_as_errors = 1;
/* Default assume_16_bit_calculations appropriately; this tells the checking
* code that 16-bit arithmetic is used for 8-bit samples when it would make a
* difference.
*/
pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
/* Currently 16 bit expansion happens at the end of the pipeline, so the
* calculations are done in the input bit depth not the output.
*
* TODO: fix this
*/
pm.calculations_use_input_precision = 1U;
/* Store the test gammas */
pm.gammas = gammas;
pm.ngammas = (sizeof gammas) / (sizeof gammas[0]);
pm.ngamma_tests = 0; /* default to off */
/* And the test encodings */
pm.encodings = test_encodings;
pm.nencodings = (sizeof test_encodings) / (sizeof test_encodings[0]);
pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
/* The following allows results to pass if they correspond to anything in the
* transformed range [input-.5,input+.5]; this is is required because of the
* way libpng treates the 16_TO_8 flag when building the gamma tables in
* releases up to 1.6.0.
*
* TODO: review this
*/
pm.use_input_precision_16to8 = 1U;
pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
/* Some default values (set the behavior for 'make check' here).
* These values simply control the maximum error permitted in the gamma
* transformations. The practial limits for human perception are described
* below (the setting for maxpc16), however for 8 bit encodings it isn't
* possible to meet the accepted capabilities of human vision - i.e. 8 bit
* images can never be good enough, regardless of encoding.
*/
pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
pm.maxabs8 = .00005; /* 1/20000 */
pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
pm.maxpc8 = .499; /* I.e., .499% fractional error */
pm.maxout16 = .499; /* Error in *encoded* value */
pm.maxabs16 = .00005;/* 1/20000 */
pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
/* NOTE: this is a reasonable perceptual limit. We assume that humans can
* perceive light level differences of 1% over a 100:1 range, so we need to
* maintain 1 in 10000 accuracy (in linear light space), which is what the
* following guarantees. It also allows significantly higher errors at
* higher 16 bit values, which is important for performance. The actual
* maximum 16 bit error is about +/-1.9 in the fixed point implementation but
* this is only allowed for values >38149 by the following:
*/
pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
/* Now parse the command line options. */
while (--argc >= 1)
{
int catmore = 0; /* Set if the argument has an argument. */
/* Record each argument for posterity: */
cp = safecat(command, sizeof command, cp, " ");
cp = safecat(command, sizeof command, cp, *++argv);
if (strcmp(*argv, "-v") == 0)
pm.this.verbose = 1;
else if (strcmp(*argv, "-l") == 0)
pm.log = 1;
else if (strcmp(*argv, "-q") == 0)
summary = pm.this.verbose = pm.log = 0;
else if (strcmp(*argv, "-w") == 0)
pm.this.treat_warnings_as_errors = 0;
else if (strcmp(*argv, "--speed") == 0)
pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
summary = 0;
else if (strcmp(*argv, "--memory") == 0)
memstats = 1;
else if (strcmp(*argv, "--size") == 0)
pm.test_size = 1;
else if (strcmp(*argv, "--nosize") == 0)
pm.test_size = 0;
else if (strcmp(*argv, "--standard") == 0)
pm.test_standard = 1;
else if (strcmp(*argv, "--nostandard") == 0)
pm.test_standard = 0;
else if (strcmp(*argv, "--transform") == 0)
pm.test_transform = 1;
else if (strcmp(*argv, "--notransform") == 0)
pm.test_transform = 0;
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
else if (strncmp(*argv, "--transform-disable=",
sizeof "--transform-disable") == 0)
{
pm.test_transform = 1;
transform_disable(*argv + sizeof "--transform-disable");
}
else if (strncmp(*argv, "--transform-enable=",
sizeof "--transform-enable") == 0)
{
pm.test_transform = 1;
transform_enable(*argv + sizeof "--transform-enable");
}
#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
else if (strcmp(*argv, "--gamma") == 0)
{
/* Just do two gamma tests here (2.2 and linear) for speed: */
pm.ngamma_tests = 2U;
pm.test_gamma_threshold = 1;
pm.test_gamma_transform = 1;
pm.test_gamma_sbit = 1;
pm.test_gamma_scale16 = 1;
pm.test_gamma_background = 1;
pm.test_gamma_alpha_mode = 1;
}
else if (strcmp(*argv, "--nogamma") == 0)
pm.ngamma_tests = 0;
else if (strcmp(*argv, "--gamma-threshold") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
else if (strcmp(*argv, "--nogamma-threshold") == 0)
pm.test_gamma_threshold = 0;
else if (strcmp(*argv, "--gamma-transform") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
else if (strcmp(*argv, "--nogamma-transform") == 0)
pm.test_gamma_transform = 0;
else if (strcmp(*argv, "--gamma-sbit") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
else if (strcmp(*argv, "--nogamma-sbit") == 0)
pm.test_gamma_sbit = 0;
else if (strcmp(*argv, "--gamma-16-to-8") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
pm.test_gamma_scale16 = 0;
else if (strcmp(*argv, "--gamma-background") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
else if (strcmp(*argv, "--nogamma-background") == 0)
pm.test_gamma_background = 0;
else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
pm.test_gamma_alpha_mode = 0;
else if (strcmp(*argv, "--expand16") == 0)
pm.test_gamma_expand16 = 1;
else if (strcmp(*argv, "--noexpand16") == 0)
pm.test_gamma_expand16 = 0;
else if (strcmp(*argv, "--more-gammas") == 0)
pm.ngamma_tests = 3U;
else if (strcmp(*argv, "--all-gammas") == 0)
pm.ngamma_tests = pm.ngammas;
else if (strcmp(*argv, "--progressive-read") == 0)
pm.this.progressive = 1;
else if (strcmp(*argv, "--use-update-info") == 0)
++pm.use_update_info; /* Can call multiple times */
else if (strcmp(*argv, "--interlace") == 0)
{
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
pm.interlace_type = PNG_INTERLACE_ADAM7;
# else
fprintf(stderr, "pngvalid: no write interlace support\n");
return SKIP;
# endif
}
else if (strcmp(*argv, "--use-input-precision") == 0)
pm.use_input_precision = 1U;
else if (strcmp(*argv, "--use-calculation-precision") == 0)
pm.use_input_precision = 0;
else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
pm.calculations_use_input_precision = 1U;
else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
pm.assume_16_bit_calculations = 1U;
else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
pm.calculations_use_input_precision =
pm.assume_16_bit_calculations = 0;
else if (strcmp(*argv, "--exhaustive") == 0)
pm.test_exhaustive = 1;
else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
--argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
else if (argc > 1 && strcmp(*argv, "--touch") == 0)
--argc, touch = *++argv, catmore = 1;
else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
{
--argc;
if (strcmp(5+*argv, "abs8") == 0)
pm.maxabs8 = atof(*++argv);
else if (strcmp(5+*argv, "abs16") == 0)
pm.maxabs16 = atof(*++argv);
else if (strcmp(5+*argv, "calc8") == 0)
pm.maxcalc8 = atof(*++argv);
else if (strcmp(5+*argv, "calc16") == 0)
pm.maxcalc16 = atof(*++argv);
else if (strcmp(5+*argv, "out8") == 0)
pm.maxout8 = atof(*++argv);
else if (strcmp(5+*argv, "out16") == 0)
pm.maxout16 = atof(*++argv);
else if (strcmp(5+*argv, "pc8") == 0)
pm.maxpc8 = atof(*++argv);
else if (strcmp(5+*argv, "pc16") == 0)
pm.maxpc16 = atof(*++argv);
else
{
fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
exit(99);
}
catmore = 1;
}
else if (strcmp(*argv, "--log8") == 0)
--argc, pm.log8 = atof(*++argv), catmore = 1;
else if (strcmp(*argv, "--log16") == 0)
--argc, pm.log16 = atof(*++argv), catmore = 1;
#ifdef PNG_SET_OPTION_SUPPORTED
else if (strncmp(*argv, "--option=", 9) == 0)
{
/* Syntax of the argument is <option>:{on|off} */
const char *arg = 9+*argv;
unsigned char option=0, setting=0;
#ifdef PNG_ARM_NEON_API_SUPPORTED
if (strncmp(arg, "arm-neon:", 9) == 0)
option = PNG_ARM_NEON, arg += 9;
else
#endif
#ifdef PNG_MAXIMUM_INFLATE_WINDOW
if (strncmp(arg, "max-inflate-window:", 19) == 0)
option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
else
#endif
{
fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
exit(99);
}
if (strcmp(arg, "off") == 0)
setting = PNG_OPTION_OFF;
else if (strcmp(arg, "on") == 0)
setting = PNG_OPTION_ON;
else
{
fprintf(stderr,
"pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
*argv, arg);
exit(99);
}
pm.this.options[pm.this.noptions].option = option;
pm.this.options[pm.this.noptions++].setting = setting;
}
#endif /* PNG_SET_OPTION_SUPPORTED */
else
{
fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
exit(99);
}
if (catmore) /* consumed an extra *argv */
{
cp = safecat(command, sizeof command, cp, " ");
cp = safecat(command, sizeof command, cp, *argv);
}
}
/* If pngvalid is run with no arguments default to a reasonable set of the
* tests.
*/
if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
pm.ngamma_tests == 0)
{
/* Make this do all the tests done in the test shell scripts with the same
* parameters, where possible. The limitation is that all the progressive
* read and interlace stuff has to be done in separate runs, so only the
* basic 'standard' and 'size' tests are done.
*/
pm.test_standard = 1;
pm.test_size = 1;
pm.test_transform = 1;
pm.ngamma_tests = 2U;
}
if (pm.ngamma_tests > 0 &&
pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
{
pm.test_gamma_threshold = 1;
pm.test_gamma_transform = 1;
pm.test_gamma_sbit = 1;
pm.test_gamma_scale16 = 1;
pm.test_gamma_background = 1;
pm.test_gamma_alpha_mode = 1;
}
else if (pm.ngamma_tests == 0)
{
/* Nothing to test so turn everything off: */
pm.test_gamma_threshold = 0;
pm.test_gamma_transform = 0;
pm.test_gamma_sbit = 0;
pm.test_gamma_scale16 = 0;
pm.test_gamma_background = 0;
pm.test_gamma_alpha_mode = 0;
}
Try
{
/* Make useful base images */
make_transform_images(&pm.this);
/* Perform the standard and gamma tests. */
if (pm.test_standard)
{
perform_interlace_macro_validation();
perform_formatting_test(&pm.this);
# ifdef PNG_READ_SUPPORTED
perform_standard_test(&pm);
# endif
perform_error_test(&pm);
}
/* Various oddly sized images: */
if (pm.test_size)
{
make_size_images(&pm.this);
# ifdef PNG_READ_SUPPORTED
perform_size_test(&pm);
# endif
}
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
/* Combinatorial transforms: */
if (pm.test_transform)
perform_transform_test(&pm);
#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
#ifdef PNG_READ_GAMMA_SUPPORTED
if (pm.ngamma_tests > 0)
perform_gamma_test(&pm, summary);
#endif
}
Catch_anonymous
{
fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
if (!pm.this.verbose)
{
if (pm.this.error[0] != 0)
fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
fprintf(stderr, "pngvalid: run with -v to see what happened\n");
}
exit(1);
}
if (summary)
{
printf("%s: %s (%s point arithmetic)\n",
(pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
pm.this.nwarnings)) ? "FAIL" : "PASS",
command,
#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
"floating"
#else
"fixed"
#endif
);
}
if (memstats)
{
printf("Allocated memory statistics (in bytes):\n"
"\tread %lu maximum single, %lu peak, %lu total\n"
"\twrite %lu maximum single, %lu peak, %lu total\n",
(unsigned long)pm.this.read_memory_pool.max_max,
(unsigned long)pm.this.read_memory_pool.max_limit,
(unsigned long)pm.this.read_memory_pool.max_total,
(unsigned long)pm.this.write_memory_pool.max_max,
(unsigned long)pm.this.write_memory_pool.max_limit,
(unsigned long)pm.this.write_memory_pool.max_total);
}
/* Do this here to provoke memory corruption errors in memory not directly
* allocated by libpng - not a complete test, but better than nothing.
*/
store_delete(&pm.this);
/* Error exit if there are any errors, and maybe if there are any
* warnings.
*/
if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
pm.this.nwarnings))
{
if (!pm.this.verbose)
fprintf(stderr, "pngvalid: %s\n", pm.this.error);
fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
pm.this.nwarnings);
exit(1);
}
/* Success case. */
if (touch != NULL)
{
FILE *fsuccess = fopen(touch, "wt");
if (fsuccess != NULL)
{
int error = 0;
fprintf(fsuccess, "PNG validation succeeded\n");
fflush(fsuccess);
error = ferror(fsuccess);
if (fclose(fsuccess) || error)
{
fprintf(stderr, "%s: write failed\n", touch);
exit(1);
}
}
else
{
fprintf(stderr, "%s: open failed\n", touch);
exit(1);
}
}
/* This is required because some very minimal configurations do not use it:
*/
UNUSED(fail)
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int main(int argc, char **argv)
{
int summary = 1; /* Print the error summary at the end */
int memstats = 0; /* Print memory statistics at the end */
/* Create the given output file on success: */
const char *touch = NULL;
/* This is an array of standard gamma values (believe it or not I've seen
* every one of these mentioned somewhere.)
*
* In the following list the most useful values are first!
*/
static double
gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
/* This records the command and arguments: */
size_t cp = 0;
char command[1024];
anon_context(&pm.this);
gnu_volatile(summary)
gnu_volatile(memstats)
gnu_volatile(touch)
/* Add appropriate signal handlers, just the ANSI specified ones: */
signal(SIGABRT, signal_handler);
signal(SIGFPE, signal_handler);
signal(SIGILL, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGSEGV, signal_handler);
signal(SIGTERM, signal_handler);
#ifdef HAVE_FEENABLEEXCEPT
/* Only required to enable FP exceptions on platforms where they start off
* disabled; this is not necessary but if it is not done pngvalid will likely
* end up ignoring FP conditions that other platforms fault.
*/
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
modifier_init(&pm);
/* Preallocate the image buffer, because we know how big it needs to be,
* note that, for testing purposes, it is deliberately mis-aligned by tag
* bytes either side. All rows have an additional five bytes of padding for
* overwrite checking.
*/
store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
/* Don't give argv[0], it's normally some horrible libtool string: */
cp = safecat(command, sizeof command, cp, "pngvalid");
/* Default to error on warning: */
pm.this.treat_warnings_as_errors = 1;
/* Default assume_16_bit_calculations appropriately; this tells the checking
* code that 16-bit arithmetic is used for 8-bit samples when it would make a
* difference.
*/
pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
/* Currently 16 bit expansion happens at the end of the pipeline, so the
* calculations are done in the input bit depth not the output.
*
* TODO: fix this
*/
pm.calculations_use_input_precision = 1U;
/* Store the test gammas */
pm.gammas = gammas;
pm.ngammas = ARRAY_SIZE(gammas);
pm.ngamma_tests = 0; /* default to off */
/* Low bit depth gray images don't do well in the gamma tests, until
* this is fixed turn them off for some gamma cases:
*/
# ifdef PNG_WRITE_tRNS_SUPPORTED
pm.test_tRNS = 1;
# endif
pm.test_lbg = PNG_LIBPNG_VER >= 10600;
pm.test_lbg_gamma_threshold = 1;
pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
pm.test_lbg_gamma_sbit = 1;
pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
/* And the test encodings */
pm.encodings = test_encodings;
pm.nencodings = ARRAY_SIZE(test_encodings);
# if PNG_LIBPNG_VER < 10700
pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
# else
pm.sbitlow = 1U;
# endif
/* The following allows results to pass if they correspond to anything in the
* transformed range [input-.5,input+.5]; this is is required because of the
* way libpng treates the 16_TO_8 flag when building the gamma tables in
* releases up to 1.6.0.
*
* TODO: review this
*/
pm.use_input_precision_16to8 = 1U;
pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
/* Some default values (set the behavior for 'make check' here).
* These values simply control the maximum error permitted in the gamma
* transformations. The practial limits for human perception are described
* below (the setting for maxpc16), however for 8 bit encodings it isn't
* possible to meet the accepted capabilities of human vision - i.e. 8 bit
* images can never be good enough, regardless of encoding.
*/
pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
pm.maxabs8 = .00005; /* 1/20000 */
pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
pm.maxpc8 = .499; /* I.e., .499% fractional error */
pm.maxout16 = .499; /* Error in *encoded* value */
pm.maxabs16 = .00005;/* 1/20000 */
pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
# if PNG_LIBPNG_VER < 10700
pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
# else
pm.maxcalcG = 1./((1<<16)-1);
# endif
/* NOTE: this is a reasonable perceptual limit. We assume that humans can
* perceive light level differences of 1% over a 100:1 range, so we need to
* maintain 1 in 10000 accuracy (in linear light space), which is what the
* following guarantees. It also allows significantly higher errors at
* higher 16 bit values, which is important for performance. The actual
* maximum 16 bit error is about +/-1.9 in the fixed point implementation but
* this is only allowed for values >38149 by the following:
*/
pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
/* Now parse the command line options. */
while (--argc >= 1)
{
int catmore = 0; /* Set if the argument has an argument. */
/* Record each argument for posterity: */
cp = safecat(command, sizeof command, cp, " ");
cp = safecat(command, sizeof command, cp, *++argv);
if (strcmp(*argv, "-v") == 0)
pm.this.verbose = 1;
else if (strcmp(*argv, "-l") == 0)
pm.log = 1;
else if (strcmp(*argv, "-q") == 0)
summary = pm.this.verbose = pm.log = 0;
else if (strcmp(*argv, "-w") == 0 ||
strcmp(*argv, "--strict") == 0)
pm.this.treat_warnings_as_errors = 0;
else if (strcmp(*argv, "--speed") == 0)
pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
summary = 0;
else if (strcmp(*argv, "--memory") == 0)
memstats = 1;
else if (strcmp(*argv, "--size") == 0)
pm.test_size = 1;
else if (strcmp(*argv, "--nosize") == 0)
pm.test_size = 0;
else if (strcmp(*argv, "--standard") == 0)
pm.test_standard = 1;
else if (strcmp(*argv, "--nostandard") == 0)
pm.test_standard = 0;
else if (strcmp(*argv, "--transform") == 0)
pm.test_transform = 1;
else if (strcmp(*argv, "--notransform") == 0)
pm.test_transform = 0;
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
else if (strncmp(*argv, "--transform-disable=",
sizeof "--transform-disable") == 0)
{
pm.test_transform = 1;
transform_disable(*argv + sizeof "--transform-disable");
}
else if (strncmp(*argv, "--transform-enable=",
sizeof "--transform-enable") == 0)
{
pm.test_transform = 1;
transform_enable(*argv + sizeof "--transform-enable");
}
#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
else if (strcmp(*argv, "--gamma") == 0)
{
/* Just do two gamma tests here (2.2 and linear) for speed: */
pm.ngamma_tests = 2U;
pm.test_gamma_threshold = 1;
pm.test_gamma_transform = 1;
pm.test_gamma_sbit = 1;
pm.test_gamma_scale16 = 1;
pm.test_gamma_background = 1; /* composition */
pm.test_gamma_alpha_mode = 1;
}
else if (strcmp(*argv, "--nogamma") == 0)
pm.ngamma_tests = 0;
else if (strcmp(*argv, "--gamma-threshold") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
else if (strcmp(*argv, "--nogamma-threshold") == 0)
pm.test_gamma_threshold = 0;
else if (strcmp(*argv, "--gamma-transform") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
else if (strcmp(*argv, "--nogamma-transform") == 0)
pm.test_gamma_transform = 0;
else if (strcmp(*argv, "--gamma-sbit") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
else if (strcmp(*argv, "--nogamma-sbit") == 0)
pm.test_gamma_sbit = 0;
else if (strcmp(*argv, "--gamma-16-to-8") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
pm.test_gamma_scale16 = 0;
else if (strcmp(*argv, "--gamma-background") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
else if (strcmp(*argv, "--nogamma-background") == 0)
pm.test_gamma_background = 0;
else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
pm.test_gamma_alpha_mode = 0;
else if (strcmp(*argv, "--expand16") == 0)
pm.test_gamma_expand16 = 1;
else if (strcmp(*argv, "--noexpand16") == 0)
pm.test_gamma_expand16 = 0;
else if (strcmp(*argv, "--low-depth-gray") == 0)
pm.test_lbg = pm.test_lbg_gamma_threshold =
pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
pm.test_lbg_gamma_composition = 1;
else if (strcmp(*argv, "--nolow-depth-gray") == 0)
pm.test_lbg = pm.test_lbg_gamma_threshold =
pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
pm.test_lbg_gamma_composition = 0;
# ifdef PNG_WRITE_tRNS_SUPPORTED
else if (strcmp(*argv, "--tRNS") == 0)
pm.test_tRNS = 1;
# endif
else if (strcmp(*argv, "--notRNS") == 0)
pm.test_tRNS = 0;
else if (strcmp(*argv, "--more-gammas") == 0)
pm.ngamma_tests = 3U;
else if (strcmp(*argv, "--all-gammas") == 0)
pm.ngamma_tests = pm.ngammas;
else if (strcmp(*argv, "--progressive-read") == 0)
pm.this.progressive = 1;
else if (strcmp(*argv, "--use-update-info") == 0)
++pm.use_update_info; /* Can call multiple times */
else if (strcmp(*argv, "--interlace") == 0)
{
# if CAN_WRITE_INTERLACE
pm.interlace_type = PNG_INTERLACE_ADAM7;
# else /* !CAN_WRITE_INTERLACE */
fprintf(stderr, "pngvalid: no write interlace support\n");
return SKIP;
# endif /* !CAN_WRITE_INTERLACE */
}
else if (strcmp(*argv, "--use-input-precision") == 0)
pm.use_input_precision = 1U;
else if (strcmp(*argv, "--use-calculation-precision") == 0)
pm.use_input_precision = 0;
else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
pm.calculations_use_input_precision = 1U;
else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
pm.assume_16_bit_calculations = 1U;
else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
pm.calculations_use_input_precision =
pm.assume_16_bit_calculations = 0;
else if (strcmp(*argv, "--exhaustive") == 0)
pm.test_exhaustive = 1;
else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
--argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
else if (argc > 1 && strcmp(*argv, "--touch") == 0)
--argc, touch = *++argv, catmore = 1;
else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
{
--argc;
if (strcmp(5+*argv, "abs8") == 0)
pm.maxabs8 = atof(*++argv);
else if (strcmp(5+*argv, "abs16") == 0)
pm.maxabs16 = atof(*++argv);
else if (strcmp(5+*argv, "calc8") == 0)
pm.maxcalc8 = atof(*++argv);
else if (strcmp(5+*argv, "calc16") == 0)
pm.maxcalc16 = atof(*++argv);
else if (strcmp(5+*argv, "out8") == 0)
pm.maxout8 = atof(*++argv);
else if (strcmp(5+*argv, "out16") == 0)
pm.maxout16 = atof(*++argv);
else if (strcmp(5+*argv, "pc8") == 0)
pm.maxpc8 = atof(*++argv);
else if (strcmp(5+*argv, "pc16") == 0)
pm.maxpc16 = atof(*++argv);
else
{
fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
exit(99);
}
catmore = 1;
}
else if (strcmp(*argv, "--log8") == 0)
--argc, pm.log8 = atof(*++argv), catmore = 1;
else if (strcmp(*argv, "--log16") == 0)
--argc, pm.log16 = atof(*++argv), catmore = 1;
#ifdef PNG_SET_OPTION_SUPPORTED
else if (strncmp(*argv, "--option=", 9) == 0)
{
/* Syntax of the argument is <option>:{on|off} */
const char *arg = 9+*argv;
unsigned char option=0, setting=0;
#ifdef PNG_ARM_NEON
if (strncmp(arg, "arm-neon:", 9) == 0)
option = PNG_ARM_NEON, arg += 9;
else
#endif
#ifdef PNG_EXTENSIONS
if (strncmp(arg, "extensions:", 11) == 0)
option = PNG_EXTENSIONS, arg += 11;
else
#endif
#ifdef PNG_MAXIMUM_INFLATE_WINDOW
if (strncmp(arg, "max-inflate-window:", 19) == 0)
option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
else
#endif
{
fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
exit(99);
}
if (strcmp(arg, "off") == 0)
setting = PNG_OPTION_OFF;
else if (strcmp(arg, "on") == 0)
setting = PNG_OPTION_ON;
else
{
fprintf(stderr,
"pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
*argv, arg);
exit(99);
}
pm.this.options[pm.this.noptions].option = option;
pm.this.options[pm.this.noptions++].setting = setting;
}
#endif /* PNG_SET_OPTION_SUPPORTED */
else
{
fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
exit(99);
}
if (catmore) /* consumed an extra *argv */
{
cp = safecat(command, sizeof command, cp, " ");
cp = safecat(command, sizeof command, cp, *argv);
}
}
/* If pngvalid is run with no arguments default to a reasonable set of the
* tests.
*/
if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
pm.ngamma_tests == 0)
{
/* Make this do all the tests done in the test shell scripts with the same
* parameters, where possible. The limitation is that all the progressive
* read and interlace stuff has to be done in separate runs, so only the
* basic 'standard' and 'size' tests are done.
*/
pm.test_standard = 1;
pm.test_size = 1;
pm.test_transform = 1;
pm.ngamma_tests = 2U;
}
if (pm.ngamma_tests > 0 &&
pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
{
pm.test_gamma_threshold = 1;
pm.test_gamma_transform = 1;
pm.test_gamma_sbit = 1;
pm.test_gamma_scale16 = 1;
pm.test_gamma_background = 1;
pm.test_gamma_alpha_mode = 1;
}
else if (pm.ngamma_tests == 0)
{
/* Nothing to test so turn everything off: */
pm.test_gamma_threshold = 0;
pm.test_gamma_transform = 0;
pm.test_gamma_sbit = 0;
pm.test_gamma_scale16 = 0;
pm.test_gamma_background = 0;
pm.test_gamma_alpha_mode = 0;
}
Try
{
/* Make useful base images */
make_transform_images(&pm);
/* Perform the standard and gamma tests. */
if (pm.test_standard)
{
perform_interlace_macro_validation();
perform_formatting_test(&pm.this);
# ifdef PNG_READ_SUPPORTED
perform_standard_test(&pm);
# endif
perform_error_test(&pm);
}
/* Various oddly sized images: */
if (pm.test_size)
{
make_size_images(&pm.this);
# ifdef PNG_READ_SUPPORTED
perform_size_test(&pm);
# endif
}
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
/* Combinatorial transforms: */
if (pm.test_transform)
perform_transform_test(&pm);
#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
#ifdef PNG_READ_GAMMA_SUPPORTED
if (pm.ngamma_tests > 0)
perform_gamma_test(&pm, summary);
#endif
}
Catch_anonymous
{
fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
if (!pm.this.verbose)
{
if (pm.this.error[0] != 0)
fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
fprintf(stderr, "pngvalid: run with -v to see what happened\n");
}
exit(1);
}
if (summary)
{
printf("%s: %s (%s point arithmetic)\n",
(pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
pm.this.nwarnings)) ? "FAIL" : "PASS",
command,
#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
"floating"
#else
"fixed"
#endif
);
}
if (memstats)
{
printf("Allocated memory statistics (in bytes):\n"
"\tread %lu maximum single, %lu peak, %lu total\n"
"\twrite %lu maximum single, %lu peak, %lu total\n",
(unsigned long)pm.this.read_memory_pool.max_max,
(unsigned long)pm.this.read_memory_pool.max_limit,
(unsigned long)pm.this.read_memory_pool.max_total,
(unsigned long)pm.this.write_memory_pool.max_max,
(unsigned long)pm.this.write_memory_pool.max_limit,
(unsigned long)pm.this.write_memory_pool.max_total);
}
/* Do this here to provoke memory corruption errors in memory not directly
* allocated by libpng - not a complete test, but better than nothing.
*/
store_delete(&pm.this);
/* Error exit if there are any errors, and maybe if there are any
* warnings.
*/
if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
pm.this.nwarnings))
{
if (!pm.this.verbose)
fprintf(stderr, "pngvalid: %s\n", pm.this.error);
fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
pm.this.nwarnings);
exit(1);
}
/* Success case. */
if (touch != NULL)
{
FILE *fsuccess = fopen(touch, "wt");
if (fsuccess != NULL)
{
int error = 0;
fprintf(fsuccess, "PNG validation succeeded\n");
fflush(fsuccess);
error = ferror(fsuccess);
if (fclose(fsuccess) || error)
{
fprintf(stderr, "%s: write failed\n", touch);
exit(1);
}
}
else
{
fprintf(stderr, "%s: open failed\n", touch);
exit(1);
}
}
/* This is required because some very minimal configurations do not use it:
*/
UNUSED(fail)
return 0;
}
| 173,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ip_printts(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
int hoplen;
const char *type;
if (length < 4) {
ND_PRINT((ndo, "[bad length %u]", length));
return;
}
ND_PRINT((ndo, " TS{"));
hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4;
if ((length - 4) & (hoplen-1))
ND_PRINT((ndo, "[bad length %u]", length));
ptr = cp[2] - 1;
len = 0;
if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1)
ND_PRINT((ndo, "[bad ptr %u]", cp[2]));
switch (cp[3]&0xF) {
case IPOPT_TS_TSONLY:
ND_PRINT((ndo, "TSONLY"));
break;
case IPOPT_TS_TSANDADDR:
ND_PRINT((ndo, "TS+ADDR"));
break;
/*
* prespecified should really be 3, but some ones might send 2
* instead, and the IPOPT_TS_PRESPEC constant can apparently
* have both values, so we have to hard-code it here.
*/
case 2:
ND_PRINT((ndo, "PRESPEC2.0"));
break;
case 3: /* IPOPT_TS_PRESPEC */
ND_PRINT((ndo, "PRESPEC"));
break;
default:
ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF));
goto done;
}
type = " ";
for (len = 4; len < length; len += hoplen) {
if (ptr == len)
type = " ^ ";
ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]),
hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len])));
type = " ";
}
done:
ND_PRINT((ndo, "%s", ptr == len ? " ^ " : ""));
if (cp[3]>>4)
ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4));
else
ND_PRINT((ndo, "}"));
Commit Message: CVE-2017-13037/IP: Add bounds checks when printing time stamp options.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ip_printts(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
int hoplen;
const char *type;
if (length < 4) {
ND_PRINT((ndo, "[bad length %u]", length));
return (0);
}
ND_PRINT((ndo, " TS{"));
hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4;
if ((length - 4) & (hoplen-1))
ND_PRINT((ndo, "[bad length %u]", length));
ND_TCHECK(cp[2]);
ptr = cp[2] - 1;
len = 0;
if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1)
ND_PRINT((ndo, "[bad ptr %u]", cp[2]));
ND_TCHECK(cp[3]);
switch (cp[3]&0xF) {
case IPOPT_TS_TSONLY:
ND_PRINT((ndo, "TSONLY"));
break;
case IPOPT_TS_TSANDADDR:
ND_PRINT((ndo, "TS+ADDR"));
break;
/*
* prespecified should really be 3, but some ones might send 2
* instead, and the IPOPT_TS_PRESPEC constant can apparently
* have both values, so we have to hard-code it here.
*/
case 2:
ND_PRINT((ndo, "PRESPEC2.0"));
break;
case 3: /* IPOPT_TS_PRESPEC */
ND_PRINT((ndo, "PRESPEC"));
break;
default:
ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF));
goto done;
}
type = " ";
for (len = 4; len < length; len += hoplen) {
if (ptr == len)
type = " ^ ";
ND_TCHECK2(cp[len], hoplen);
ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]),
hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len])));
type = " ";
}
done:
ND_PRINT((ndo, "%s", ptr == len ? " ^ " : ""));
if (cp[3]>>4)
ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4));
else
ND_PRINT((ndo, "}"));
| 167,846 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_princs_2_svc(gprincs_arg *arg, struct svc_req *rqstp)
{
static gprincs_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprincs_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST,
NULL,
NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_principals", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principals((void *)handle,
arg->exp, &ret.princs,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_principals", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | get_princs_2_svc(gprincs_arg *arg, struct svc_req *rqstp)
{
static gprincs_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprincs_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST,
NULL,
NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_principals", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principals((void *)handle,
arg->exp, &ret.princs,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_principals", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,516 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual InputMethodDescriptors* GetSupportedInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual InputMethodDescriptors* GetSupportedInputMethods() {
virtual input_method::InputMethodDescriptors* GetSupportedInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
| 170,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if ((num_pages != size) ||
(num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
Commit Message: macvtap: zerocopy: validate vectors before building skb
There're several reasons that the vectors need to be validated:
- Return error when caller provides vectors whose num is greater than UIO_MAXIOV.
- Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS.
- Return error when userspace provides vectors whose total length may exceed
- MAX_SKB_FRAGS * PAGE_SIZE.
Signed-off-by: Jason Wang <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
CWE ID: CWE-119 | static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
if (i + size > MAX_SKB_FRAGS)
return -EMSGSIZE;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if (num_pages != size) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
| 166,205 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int x25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name;
size_t copied;
int qbit, header_len;
struct sk_buff *skb;
unsigned char *asmptr;
int rc = -ENOTCONN;
lock_sock(sk);
if (x25->neighbour == NULL)
goto out;
header_len = x25->neighbour->extended ?
X25_EXT_MIN_LEN : X25_STD_MIN_LEN;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if (flags & MSG_OOB) {
rc = -EINVAL;
if (sock_flag(sk, SOCK_URGINLINE) ||
!skb_peek(&x25->interrupt_in_queue))
goto out;
skb = skb_dequeue(&x25->interrupt_in_queue);
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
goto out_free_dgram;
skb_pull(skb, X25_STD_MIN_LEN);
/*
* No Q bit information on Interrupt data.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = 0x00;
}
msg->msg_flags |= MSG_OOB;
} else {
/* Now we can treat all alike */
release_sock(sk);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
lock_sock(sk);
if (!skb)
goto out;
if (!pskb_may_pull(skb, header_len))
goto out_free_dgram;
qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT;
skb_pull(skb, header_len);
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
/* Currently, each datagram always contains a complete record */
msg->msg_flags |= MSG_EOR;
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (rc)
goto out_free_dgram;
if (sx25) {
sx25->sx25_family = AF_X25;
sx25->sx25_addr = x25->dest_addr;
}
msg->msg_namelen = sizeof(struct sockaddr_x25);
x25_check_rbuf(sk);
rc = copied;
out_free_dgram:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[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-20 | static int x25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name;
size_t copied;
int qbit, header_len;
struct sk_buff *skb;
unsigned char *asmptr;
int rc = -ENOTCONN;
lock_sock(sk);
if (x25->neighbour == NULL)
goto out;
header_len = x25->neighbour->extended ?
X25_EXT_MIN_LEN : X25_STD_MIN_LEN;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if (flags & MSG_OOB) {
rc = -EINVAL;
if (sock_flag(sk, SOCK_URGINLINE) ||
!skb_peek(&x25->interrupt_in_queue))
goto out;
skb = skb_dequeue(&x25->interrupt_in_queue);
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
goto out_free_dgram;
skb_pull(skb, X25_STD_MIN_LEN);
/*
* No Q bit information on Interrupt data.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = 0x00;
}
msg->msg_flags |= MSG_OOB;
} else {
/* Now we can treat all alike */
release_sock(sk);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
lock_sock(sk);
if (!skb)
goto out;
if (!pskb_may_pull(skb, header_len))
goto out_free_dgram;
qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT;
skb_pull(skb, header_len);
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
/* Currently, each datagram always contains a complete record */
msg->msg_flags |= MSG_EOR;
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (rc)
goto out_free_dgram;
if (sx25) {
sx25->sx25_family = AF_X25;
sx25->sx25_addr = x25->dest_addr;
msg->msg_namelen = sizeof(*sx25);
}
x25_check_rbuf(sk);
rc = copied;
out_free_dgram:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
| 166,524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.