instruction
stringclasses 1
value | input
stringlengths 306
235k
| output
stringclasses 3
values | __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const ImfHeader
*hdr_info;
Image
*image;
ImageInfo
*read_info;
ImfInputFile
*file;
ImfRgba
*scanline;
int
max_x,
max_y,
min_x,
min_y;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
read_info=CloneImageInfo(image_info);
if (IsPathAccessible(read_info->filename) == MagickFalse)
{
(void) AcquireUniqueFilename(read_info->filename);
(void) ImageToFile(image,read_info->filename,exception);
}
file=ImfOpenInputFile(read_info->filename);
if (file == (ImfInputFile *) NULL)
{
ThrowFileException(exception,BlobError,"UnableToOpenBlob",
ImfErrorMessage());
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
return((Image *) NULL);
}
hdr_info=ImfInputHeader(file);
ImfHeaderDisplayWindow(hdr_info,&min_x,&min_y,&max_x,&max_y);
image->columns=max_x-min_x+1UL;
image->rows=max_y-min_y+1UL;
image->matte=MagickTrue;
SetImageColorspace(image,RGBColorspace);
if (image_info->ping != MagickFalse)
{
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline));
if (scanline == (ImfRgba *) NULL)
{
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline));
ImfInputSetFrameBuffer(file,scanline-min_x-image->columns*(min_y+y),1,
image->columns);
ImfInputReadPixels(file,min_y+y,min_y+y);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].r)));
SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].g)));
SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].b)));
SetPixelAlpha(q,ClampToQuantum((MagickRealType) QuantumRange*
ImfHalfToFloat(scanline[x].a)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
scanline=(ImfRgba *) RelinquishMagickMemory(scanline);
(void) ImfCloseInputFile(file);
if (LocaleCompare(image_info->filename,read_info->filename) != 0)
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file.
Commit Message: | Medium | 168,563 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: Buffer overflow in the git_pkt_parse_line function in transports/smart_pkt.c in the Git Smart Protocol support in libgit2 before 0.24.6 and 0.25.x before 0.25.1 allows remote attackers to have unspecified impact via a crafted non-flush packet.
Commit Message: smart_pkt: verify packet length exceeds PKT_LEN_SIZE
Each packet line in the Git protocol is prefixed by a four-byte
length of how much data will follow, which we parse in
`git_pkt_parse_line`. The transmitted length can either be equal
to zero in case of a flush packet or has to be at least of length
four, as it also includes the encoded length itself. Not
checking this may result in a buffer overflow as we directly pass
the length to functions which accept a `size_t` length as
parameter.
Fix the issue by verifying that non-flush packets have at least a
length of `PKT_LEN_SIZE`. | High | 168,530 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void test_parser(void) {
int i, retval;
bzrtpPacket_t *zrtpPacket;
/* Create zrtp Context to use H0-H3 chains and others */
bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321);
bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678);
/* replace created H by the patterns one to be able to generate the correct packet */
memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32);
memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32);
memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32);
memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32);
memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32);
memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32);
memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32);
memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32);
/* preset the key agreement algo in the contexts */
context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k;
context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k;
context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1;
context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1;
context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256;
context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256;
updateCryptoFunctionPointers(context87654321->channelContext[0]);
updateCryptoFunctionPointers(context12345678->channelContext[0]);
/* set the zrtp and mac keys */
context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32);
context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32);
context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32);
context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32);
context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16);
context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16);
context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16);
context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16);
memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32);
memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32);
memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16);
memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16);
memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32);
memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32);
memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16);
memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16);
/* set the role: 87654321 is initiator in our exchange pattern */
context12345678->channelContext[0]->role = RESPONDER;
for (i=0; i<TEST_PACKET_NUMBER; i++) {
uint8_t freePacketFlag = 1;
/* parse a packet string from patterns */
zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval);
retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket);
/*printf("parsing Ret val is %x index is %d\n", retval, i);*/
/* We must store some packets in the context if we want to be able to parse further packets */
if (zrtpPacket->messageType==MSGTYPE_HELLO) {
if (patternZRTPMetaData[i][2]==0x87654321) {
context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket;
} else {
context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket;
}
freePacketFlag = 0;
}
if (zrtpPacket->messageType==MSGTYPE_COMMIT) {
if (patternZRTPMetaData[i][2]==0x87654321) {
context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket;
} else {
context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket;
}
freePacketFlag = 0;
}
if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) {
if (patternZRTPMetaData[i][2]==0x87654321) {
context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket;
} else {
context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket;
}
freePacketFlag = 0;
}
/* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */
free(zrtpPacket->packetString);
/* build a packet string from the parser packet*/
retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]);
/* if (retval ==0) {
packetDump(zrtpPacket, 1);
} else {
bzrtp_message("Ret val is %x index is %d\n", retval, i);
}*/
/* check they are the same */
if (zrtpPacket->packetString != NULL) {
CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0);
} else {
CU_FAIL("Unable to build packet");
}
if (freePacketFlag == 1) {
bzrtp_freeZrtpPacket(zrtpPacket);
}
}
bzrtp_destroyBzrtpContext(context87654321, 0x87654321);
bzrtp_destroyBzrtpContext(context12345678, 0x12345678);
}
Vulnerability Type:
CWE ID: CWE-254
Summary: The Bzrtp library (aka libbzrtp) 1.0.x before 1.0.4 allows man-in-the-middle attackers to conduct spoofing attacks by leveraging a missing HVI check on DHPart2 packet reception.
Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception | Medium | 168,829 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
mode_t new_umask_val;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
{"umask", required_argument, NULL, 'u'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 'u':
new_umask_val = set_umask(optarg);
if (umask_cmdline)
umask_val = new_umask_val;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
Vulnerability Type:
CWE ID: CWE-59
Summary: keepalived 2.0.8 didn't check for pathnames with symlinks when writing data to a temporary file upon a call to PrintData or PrintStats. This allowed local users to overwrite arbitrary files if fs.protected_symlinks is set to 0, as demonstrated by a symlink from /tmp/keepalived.data or /tmp/keepalived.stats to /etc/passwd.
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]> | Low | 168,985 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
ps_dec->process_called = 1;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
ps_dec->u4_stop_threads = 0;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base;
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
/* Since 8 bytes are read ahead, ensure 8 bytes are free at the
end of the buffer, which will be memset to 0 after emulation prevention */
buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8));
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
if(buflen >= MAX_NAL_UNIT_SIZE)
{
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
H264_DEC_DEBUG_PRINT(
"\nNal Size exceeded %d, Processing Stopped..\n",
MAX_NAL_UNIT_SIZE);
ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA;
ps_dec_op->e_pic_type = -1;
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/*signal end of frame decode for curren frame*/
if(ps_dec->u4_pic_buf_got == 0)
{
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded =
ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return IV_FAIL;
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
header_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
ps_dec->u4_slice_start_code_found = 0;
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
WORD32 ht_in_mbs;
ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag);
num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0))
prev_slice_err = 1;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) ||
(ret1 == ERROR_INV_SPS_PPS_T))
{
ret = ret1;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
&& (ps_dec->u4_pic_buf_got == 1))
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((0 == ps_dec->u4_num_reorder_frames_at_init)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
/*--------------------------------------------------------------------*/
/* Do End of Pic processing. */
/* Should be called only if frame was decoded in previous process call*/
/*--------------------------------------------------------------------*/
if(ps_dec->u4_pic_buf_got == 1)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec);
if(ret != OK)
return ret;
}
else
{
ret = ih264d_end_of_pic(ps_dec);
if(ret != OK)
return ret;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability in libavc in Mediaserver could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access data without permission. Product: Android. Versions: 6.0, 6.0.1, 7.0, 7.1.1. Android ID: A-33551775.
Commit Message: Decoder: Fixed initialization of first_slice_in_pic
To handle some errors, first_slice_in_pic was being set to 2.
This is now cleaned up and first_slice_in_pic is set to 1 only once per pic.
This will ensure picture level initializations are done only once even in case
of error clips
Bug: 33717589
Bug: 33551775
Bug: 33716442
Bug: 33677995
Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
| Medium | 174,037 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void BackendIO::ExecuteBackendOperation() {
switch (operation_) {
case OP_INIT:
result_ = backend_->SyncInit();
break;
case OP_OPEN: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_CREATE: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncCreateEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_DOOM:
result_ = backend_->SyncDoomEntry(key_);
break;
case OP_DOOM_ALL:
result_ = backend_->SyncDoomAllEntries();
break;
case OP_DOOM_BETWEEN:
result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_);
break;
case OP_DOOM_SINCE:
result_ = backend_->SyncDoomEntriesSince(initial_time_);
break;
case OP_SIZE_ALL:
result_ = backend_->SyncCalculateSizeOfAllEntries();
break;
case OP_OPEN_NEXT: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenNextEntry(iterator_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_END_ENUMERATION:
backend_->SyncEndEnumeration(std::move(scoped_iterator_));
result_ = net::OK;
break;
case OP_ON_EXTERNAL_CACHE_HIT:
backend_->SyncOnExternalCacheHit(key_);
result_ = net::OK;
break;
case OP_CLOSE_ENTRY:
entry_->Release();
result_ = net::OK;
break;
case OP_DOOM_ENTRY:
entry_->DoomImpl();
result_ = net::OK;
break;
case OP_FLUSH_QUEUE:
result_ = net::OK;
break;
case OP_RUN_TASK:
task_.Run();
result_ = net::OK;
break;
default:
NOTREACHED() << "Invalid Operation";
result_ = net::ERR_UNEXPECTED;
}
DCHECK_NE(net::ERR_IO_PENDING, result_);
NotifyController();
}
Vulnerability Type: Exec Code
CWE ID: CWE-20
Summary: Re-entry of a destructor in Networking Disk Cache in Google Chrome prior to 66.0.3359.117 allowed a remote attacker to execute arbitrary code via a crafted HTML page.
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103} | Medium | 172,699 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: config_monitor(
config_tree *ptree
)
{
int_node *pfilegen_token;
const char *filegen_string;
const char *filegen_file;
FILEGEN *filegen;
filegen_node *my_node;
attr_val *my_opts;
int filegen_type;
int filegen_flag;
/* Set the statistics directory */
if (ptree->stats_dir)
stats_config(STATS_STATSDIR, ptree->stats_dir);
/* NOTE:
* Calling filegen_get is brain dead. Doing a string
* comparison to find the relavant filegen structure is
* expensive.
*
* Through the parser, we already know which filegen is
* being specified. Hence, we should either store a
* pointer to the specified structure in the syntax tree
* or an index into a filegen array.
*
* Need to change the filegen code to reflect the above.
*/
/* Turn on the specified statistics */
pfilegen_token = HEAD_PFIFO(ptree->stats_list);
for (; pfilegen_token != NULL; pfilegen_token = pfilegen_token->link) {
filegen_string = keyword(pfilegen_token->i);
filegen = filegen_get(filegen_string);
DPRINTF(4, ("enabling filegen for %s statistics '%s%s'\n",
filegen_string, filegen->prefix,
filegen->basename));
filegen->flag |= FGEN_FLAG_ENABLED;
}
/* Configure the statistics with the options */
my_node = HEAD_PFIFO(ptree->filegen_opts);
for (; my_node != NULL; my_node = my_node->link) {
filegen_file = keyword(my_node->filegen_token);
filegen = filegen_get(filegen_file);
/* Initialize the filegen variables to their pre-configuration states */
filegen_flag = filegen->flag;
filegen_type = filegen->type;
/* "filegen ... enabled" is the default (when filegen is used) */
filegen_flag |= FGEN_FLAG_ENABLED;
my_opts = HEAD_PFIFO(my_node->options);
for (; my_opts != NULL; my_opts = my_opts->link) {
switch (my_opts->attr) {
case T_File:
filegen_file = my_opts->value.s;
break;
case T_Type:
switch (my_opts->value.i) {
default:
NTP_INSIST(0);
break;
case T_None:
filegen_type = FILEGEN_NONE;
break;
case T_Pid:
filegen_type = FILEGEN_PID;
break;
case T_Day:
filegen_type = FILEGEN_DAY;
break;
case T_Week:
filegen_type = FILEGEN_WEEK;
break;
case T_Month:
filegen_type = FILEGEN_MONTH;
break;
case T_Year:
filegen_type = FILEGEN_YEAR;
break;
case T_Age:
filegen_type = FILEGEN_AGE;
break;
}
break;
case T_Flag:
switch (my_opts->value.i) {
case T_Link:
filegen_flag |= FGEN_FLAG_LINK;
break;
case T_Nolink:
filegen_flag &= ~FGEN_FLAG_LINK;
break;
case T_Enable:
filegen_flag |= FGEN_FLAG_ENABLED;
break;
case T_Disable:
filegen_flag &= ~FGEN_FLAG_ENABLED;
break;
default:
msyslog(LOG_ERR,
"Unknown filegen flag token %d",
my_opts->value.i);
exit(1);
}
break;
default:
msyslog(LOG_ERR,
"Unknown filegen option token %d",
my_opts->attr);
exit(1);
}
}
filegen_config(filegen, filegen_file, filegen_type,
filegen_flag);
}
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: ntp_openssl.m4 in ntpd in NTP before 4.2.7p112 allows remote attackers to cause a denial of service (segmentation fault) via a crafted statistics or filegen configuration command that is not enabled during compilation.
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL. | Medium | 168,875 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec)
{
stream_t *ps_stream;
UWORD32 u4_start_code;
IMPEG2D_ERROR_CODES_T e_error;
e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while( (u4_start_code == EXTENSION_START_CODE ||
u4_start_code == USER_DATA_START_CODE) &&
(IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error)
{
if(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_dec_user_data(ps_dec);
}
else
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN);
switch(u4_start_code)
{
case SEQ_DISPLAY_EXT_ID:
impeg2d_dec_seq_disp_ext(ps_dec);
break;
case SEQ_SCALABLE_EXT_ID:
e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED;
break;
default:
/* In case its a reserved extension code */
impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN);
impeg2d_peek_next_start_code(ps_dec);
break;
}
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
return e_error;
}
Vulnerability Type: Bypass +Info
CWE ID: CWE-254
Summary: libmpeg2 in libstagefright in Android 6.x before 2016-03-01 allows attackers to obtain sensitive information, and consequently bypass an unspecified protection mechanism, via crafted Bitstream data, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 25765591.
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
| Medium | 173,946 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: status_handler (void *opaque, int fd)
{
struct io_cb_data *data = (struct io_cb_data *) opaque;
engine_uiserver_t uiserver = (engine_uiserver_t) data->handler_value;
gpgme_error_t err = 0;
char *line;
size_t linelen;
do
{
err = assuan_read_line (uiserver->assuan_ctx, &line, &linelen);
if (err)
{
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: error from assuan (%d) getting status line : %s",
fd, err, gpg_strerror (err));
}
else if (linelen >= 3
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& (line[3] == '\0' || line[3] == ' '))
{
if (line[3] == ' ')
err = atoi (&line[4]);
if (! err)
err = gpg_error (GPG_ERR_GENERAL);
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: ERR line - mapped to: %s",
fd, err ? gpg_strerror (err) : "ok");
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
}
else if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value,
GPGME_STATUS_EOF, "");
if (!err && uiserver->colon.fnc && uiserver->colon.any)
{
/* We must tell a colon function about the EOF. We do
this only when we have seen any data lines. Note
that this inlined use of colon data lines will
eventually be changed into using a regular data
channel. */
uiserver->colon.any = 0;
err = uiserver->colon.fnc (uiserver->colon.fnc_value, NULL);
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: OK line - final status: %s",
fd, err ? gpg_strerror (err) : "ok");
_gpgme_io_close (uiserver->status_cb.fd);
return err;
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->colon.fnc)
{
/* We are using the colon handler even for plain inline data
- strange name for that function but for historic reasons
we keep it. */
/* FIXME We can't use this for binary data because we
assume this is a string. For the current usage of colon
output it is correct. */
char *src = line + 2;
char *end = line + linelen;
char *dst;
char **aline = &uiserver->colon.attic.line;
int *alinelen = &uiserver->colon.attic.linelen;
if (uiserver->colon.attic.linesize < *alinelen + linelen + 1)
{
char *newline = realloc (*aline, *alinelen + linelen + 1);
if (!newline)
err = gpg_error_from_syserror ();
else
{
*aline = newline;
uiserver->colon.attic.linesize += linelen + 1;
}
}
if (!err)
{
dst = *aline + *alinelen;
while (!err && src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst = _gpgme_hextobyte (src);
(*alinelen)++;
src += 2;
}
else
{
*dst = *src++;
(*alinelen)++;
}
if (*dst == '\n')
{
/* Terminate the pending line, pass it to the colon
handler and reset it. */
uiserver->colon.any = 1;
if (*alinelen > 1 && *(dst - 1) == '\r')
dst--;
*dst = '\0';
/* FIXME How should we handle the return code? */
err = uiserver->colon.fnc (uiserver->colon.fnc_value, *aline);
if (!err)
{
dst = *aline;
*alinelen = 0;
}
}
else
dst++;
}
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D line; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->inline_data)
{
char *src = line + 2;
char *end = line + linelen;
char *dst = src;
gpgme_ssize_t nwritten;
linelen = 0;
while (src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst++ = _gpgme_hextobyte (src);
src += 2;
}
else
*dst++ = *src++;
linelen++;
}
src = line + 2;
while (linelen > 0)
{
nwritten = gpgme_data_write (uiserver->inline_data, src, linelen);
if (!nwritten || (nwritten < 0 && errno != EINTR)
|| nwritten > linelen)
{
err = gpg_error_from_syserror ();
break;
}
src += nwritten;
linelen -= nwritten;
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D inlinedata; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0)
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value, r, rest);
}
else
fprintf (stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: S line (%s) - final status: %s",
fd, line+2, err? gpg_strerror (err):"ok");
}
else if (linelen >= 7
&& line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
&& line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
&& line[6] == 'E'
&& (line[7] == '\0' || line[7] == ' '))
{
char *keyword = line+7;
while (*keyword == ' ')
keyword++;;
default_inq_cb (uiserver, keyword);
assuan_write_line (uiserver->assuan_ctx, "END");
}
}
while (!err && assuan_pending_line (uiserver->assuan_ctx));
return err;
}
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-119
Summary: Multiple heap-based buffer overflows in the status_handler function in (1) engine-gpgsm.c and (2) engine-uiserver.c in GPGME before 1.5.1 allow remote attackers to cause a denial of service (crash) and possibly execute arbitrary code via vectors related to "different line lengths in a specific order."
Commit Message: | Medium | 165,162 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size > 512)
return 0;
net::ProxyBypassRules rules;
std::string input(data, data + size);
rules.ParseFromString(input);
rules.ParseFromStringUsingSuffixMatching(input);
return 0;
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Lack of special casing of localhost in WPAD files in Google Chrome prior to 71.0.3578.80 allowed an attacker on the local network segment to proxy resources on localhost via a crafted WPAD file.
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112} | Low | 172,645 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
clock_for_test_ = std::move(clock);
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: The Google V8 engine, as used in Google Chrome before 44.0.2403.89 and QtWebEngineCore in Qt before 5.5.1, allows remote attackers to cause a denial of service (memory corruption) or execute arbitrary code via a crafted web site.
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} | High | 171,959 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) {
ASSERT(!getThreadState()->sweepForbidden());
ASSERT(header->checkHeader());
Address address = reinterpret_cast<Address>(header);
Address payload = header->payload();
size_t size = header->size();
size_t payloadSize = header->payloadSize();
ASSERT(size > 0);
ASSERT(pageFromObject(address) == findPageFromAddress(address));
{
ThreadState::SweepForbiddenScope forbiddenScope(getThreadState());
header->finalize(payload, payloadSize);
if (address + size == m_currentAllocationPoint) {
m_currentAllocationPoint = address;
setRemainingAllocationSize(m_remainingAllocationSize + size);
SET_MEMORY_INACCESSIBLE(address, size);
return;
}
SET_MEMORY_INACCESSIBLE(payload, payloadSize);
header->markPromptlyFreed();
}
m_promptlyFreedSize += size;
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: Inline metadata in GarbageCollection in Google Chrome prior to 66.0.3359.117 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489} | Medium | 172,714 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool CheckClientDownloadRequest::ShouldUploadForDlpScan() {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
int check_content_compliance = g_browser_process->local_state()->GetInteger(
prefs::kCheckContentCompliance);
if (check_content_compliance !=
CheckContentComplianceValues::CHECK_DOWNLOADS &&
check_content_compliance !=
CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS)
return false;
if (policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty())
return false;
const base::ListValue* domains = g_browser_process->local_state()->GetList(
prefs::kURLsToCheckComplianceOfDownloadedContent);
url_matcher::URLMatcher matcher;
policy::url_util::AddAllowFilters(&matcher, domains);
return !matcher.MatchURL(item_->GetURL()).empty();
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Insufficient Policy Enforcement in Omnibox in Google Chrome prior to 59.0.3071.104 for Mac allowed a remote attacker to perform domain spoofing via a crafted domain name.
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <[email protected]>
Reviewed-by: Tien Mai <[email protected]>
Reviewed-by: Daniel Rubery <[email protected]>
Cr-Commit-Position: refs/heads/master@{#714196} | Medium | 172,356 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_Int i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_Int bit_width = pitch * 8;
FT_Int bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_Int shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_Int count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The Load_SBit_Png function in sfnt/pngshim.c in FreeType before 2.5.4 does not restrict the rows and pitch values of PNG data, which allows remote attackers to cause a denial of service (integer overflow and heap-based buffer overflow) or possibly have unspecified other impact by embedding a PNG file in a .ttf font file.
Commit Message: | High | 164,850 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static Image *ReadWBMPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
byte;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
bit;
unsigned short
header;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (ReadBlob(image,2,(unsigned char *) &header) == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header != 0)
ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported");
/*
Initialize image structure.
*/
if (WBMPReadInteger(image,&image->columns) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if (WBMPReadInteger(image,&image->rows) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to 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);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 1 : 0);
bit++;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file.
Commit Message: | Medium | 168,619 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session,
TargetRegistry* registry) {
if (!ShouldAllowSession(session))
return false;
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(
GetId(),
frame_tree_node_ ? frame_tree_node_->devtools_frame_token()
: base::UnguessableToken(),
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler(
session->client()->MayDiscoverTargets()
? protocol::TargetHandler::AccessMode::kRegular
: protocol::TargetHandler::AccessMode::kAutoAttachOnly,
GetId(), registry)));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (!frame_tree_node_ || !frame_tree_node_->parent()) {
session->AddHandler(base::WrapUnique(
new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
}
if (sessions().empty()) {
bool use_video_capture_api = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
use_video_capture_api = false;
#endif
if (!use_video_capture_api)
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Inappropriate allowance of the setDownloadBehavior devtools protocol feature in Extensions in Google Chrome prior to 71.0.3578.80 allowed a remote attacker with control of an installed extension to access files on the local file system via a crafted Chrome Extension.
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004} | Medium | 172,609 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool WtsSessionProcessDelegate::Core::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
CommandLine command_line(CommandLine::NO_PROGRAM);
if (launch_elevated_) {
if (!job_.IsValid()) {
return false;
}
FilePath daemon_binary;
if (!GetInstalledBinaryPath(kDaemonBinaryName, &daemon_binary))
return false;
command_line.SetProgram(daemon_binary);
command_line.AppendSwitchPath(kElevateSwitchName, binary_path_);
CHECK(ResetEvent(process_exit_event_));
} else {
command_line.SetProgram(binary_path_);
}
scoped_ptr<IPC::ChannelProxy> channel;
std::string channel_name = GenerateIpcChannelName(this);
if (!CreateIpcChannel(channel_name, channel_security_, io_task_runner_,
delegate, &channel))
return false;
command_line.AppendSwitchNative(kDaemonPipeSwitchName,
UTF8ToWide(channel_name));
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_process;
ScopedHandle worker_thread;
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
session_token_,
false,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
&worker_process,
&worker_thread)) {
return false;
}
HANDLE local_process_exit_event;
if (launch_elevated_) {
if (!AssignProcessToJobObject(job_, worker_process)) {
LOG_GETLASTERROR(ERROR)
<< "Failed to assign the worker to the job object";
TerminateProcess(worker_process, CONTROL_C_EXIT);
return false;
}
local_process_exit_event = process_exit_event_;
} else {
worker_process_ = worker_process.Pass();
local_process_exit_event = worker_process_;
}
if (!ResumeThread(worker_thread)) {
LOG_GETLASTERROR(ERROR) << "Failed to resume the worker thread";
KillProcess(CONTROL_C_EXIT);
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
local_process_exit_event,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = channel.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 24.0.1312.52 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving PDF fields.
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 171,560 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: findoprnd(ITEM *ptr, int32 *pos)
{
#ifdef BS_DEBUG
elog(DEBUG3, (ptr[*pos].type == OPR) ?
"%d %c" : "%d %d", *pos, ptr[*pos].val);
#endif
if (ptr[*pos].type == VAL)
{
ptr[*pos].left = 0;
(*pos)--;
}
else if (ptr[*pos].val == (int32) '!')
{
ptr[*pos].left = -1;
(*pos)--;
findoprnd(ptr, pos);
}
else
{
ITEM *curitem = &ptr[*pos];
int32 tmp = *pos;
(*pos)--;
findoprnd(ptr, pos);
curitem->left = *pos - tmp;
findoprnd(ptr, pos);
}
}
Vulnerability Type: Overflow
CWE ID: CWE-189
Summary: Multiple integer overflows in contrib/hstore/hstore_io.c in PostgreSQL 9.0.x before 9.0.16, 9.1.x before 9.1.12, 9.2.x before 9.2.7, and 9.3.x before 9.3.3 allow remote authenticated users to have unspecified impact via vectors related to the (1) hstore_recv, (2) hstore_from_arrays, and (3) hstore_from_array functions in contrib/hstore/hstore_io.c; and the (4) hstoreArrayToPairs function in contrib/hstore/hstore_op.c, which triggers a buffer overflow. NOTE: this issue was SPLIT from CVE-2014-0064 because it has a different set of affected versions.
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064 | Medium | 166,403 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void VRDisplay::OnBlur() {
display_blurred_ = true;
vr_v_sync_provider_.reset();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayblur, true, false, this, ""));
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 43.0.2357.65 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167} | High | 171,994 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void CrosLibrary::TestApi::SetTouchpadLibrary(
TouchpadLibrary* library, bool own) {
library_->touchpad_lib_.SetImpl(library, own);
}
Vulnerability Type: Exec Code
CWE ID: CWE-189
Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error.
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,648 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: checked_xcalloc (size_t num, size_t size)
{
alloc_limit_assert ("checked_xcalloc", (num *size));
return xcalloc (num, size);
}
Vulnerability Type: Overflow
CWE ID: CWE-190
Summary: An issue was discovered in tnef before 1.4.13. Several Integer Overflows, which can lead to Heap Overflows, have been identified in the functions that wrap memory allocation.
Commit Message: Fix integer overflows and harden memory allocator. | Medium | 168,356 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strcpy(algo->alg_name, auth->alg_name);
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The copy_to_user_auth function in net/xfrm/xfrm_user.c in the Linux kernel before 3.6 uses an incorrect C library function for copying a string, which allows local users to obtain sensitive information from kernel heap memory by leveraging the CAP_NET_ADMIN capability.
Commit Message: xfrm_user: fix info leak in copy_to_user_auth()
copy_to_user_auth() fails to initialize the remainder of alg_name and
therefore discloses up to 54 bytes of heap memory via netlink to
userland.
Use strncpy() instead of strcpy() to fill the trailing bytes of alg_name
with null bytes.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Low | 166,188 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_malloc((sizeof *p->vec) *
(max_frags + NET_TX_PKT_PL_START_FRAG));
p->raw = g_malloc((sizeof *p->raw) * max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Integer overflow in the net_tx_pkt_init function in hw/net/net_tx_pkt.c in QEMU (aka Quick Emulator) allows local guest OS administrators to cause a denial of service (QEMU process crash) via the maximum fragmentation count, which triggers an unchecked multiplication and NULL pointer dereference.
Commit Message: | Low | 164,947 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', 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;
}
Vulnerability Type: Exec Code Overflow +Info
CWE ID: CWE-119
Summary: sapi/cgi/cgi_main.c in the CGI component in PHP through 5.4.36, 5.5.x through 5.5.20, and 5.6.x through 5.6.4, when mmap is used to read a .php file, does not properly consider the mapping's length during processing of an invalid file that begins with a # character and lacks a newline character, which causes an out-of-bounds read and might (1) allow remote attackers to obtain sensitive information from php-cgi process memory by leveraging the ability to upload a .php file or (2) trigger unexpected code execution if a valid PHP script is present in memory locations adjacent to the mapping.
Commit Message: | High | 164,874 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
pipe_buf_get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
out:
kvfree(bufs);
return ret;
}
Vulnerability Type: Overflow
CWE ID: CWE-416
Summary: The Linux kernel before 5.1-rc5 allows page->_refcount reference count overflow, with resultant use-after-free issues, if about 140 GiB of RAM exists. This is related to fs/fuse/dev.c, fs/pipe.c, fs/splice.c, include/linux/mm.h, include/linux/pipe_fs_i.h, kernel/trace/trace.c, mm/gup.c, and mm/hugetlb.c. It can occur with FUSE requests.
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit | High | 170,217 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
Vulnerability Type: DoS
CWE ID: CWE-415
Summary: A double free when handling responses from an HSM Card in sc_pkcs15emu_sc_hsm_init in libopensc/pkcs15-sc-hsm.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to cause a denial of service (application crash) or possibly have unspecified other impact.
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems. | Medium | 169,083 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) {
Resource::LastPluginRefWasDeleted(instance_destroyed);
if (instance_destroyed) {
loader_.reset();
}
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 13.0.782.107 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to instantiation of the Pepper plug-in.
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,411 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: safe_fprintf(FILE *f, const char *fmt, ...)
{
char fmtbuff_stack[256]; /* Place to format the printf() string. */
char outbuff[256]; /* Buffer for outgoing characters. */
char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
int fmtbuff_length;
int length, n;
va_list ap;
const char *p;
unsigned i;
wchar_t wc;
char try_wc;
/* Use a stack-allocated buffer if we can, for speed and safety. */
fmtbuff_heap = NULL;
fmtbuff_length = sizeof(fmtbuff_stack);
fmtbuff = fmtbuff_stack;
/* Try formatting into the stack buffer. */
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
/* If the result was too large, allocate a buffer on the heap. */
while (length < 0 || length >= fmtbuff_length) {
if (length >= fmtbuff_length)
fmtbuff_length = length+1;
else if (fmtbuff_length < 8192)
fmtbuff_length *= 2;
else if (fmtbuff_length < 1000000)
fmtbuff_length += fmtbuff_length / 4;
else {
length = fmtbuff_length;
fmtbuff_heap[length-1] = '\0';
break;
}
free(fmtbuff_heap);
fmtbuff_heap = malloc(fmtbuff_length);
/* Reformat the result into the heap buffer if we can. */
if (fmtbuff_heap != NULL) {
fmtbuff = fmtbuff_heap;
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
} else {
/* Leave fmtbuff pointing to the truncated
* string in fmtbuff_stack. */
length = sizeof(fmtbuff_stack) - 1;
break;
}
}
/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
* more portable, so we use that here instead. */
if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
/* mbtowc() should never fail in practice, but
* handle the theoretical error anyway. */
free(fmtbuff_heap);
return;
}
/* Write data, expanding unprintable characters. */
p = fmtbuff;
i = 0;
try_wc = 1;
while (*p != '\0') {
/* Convert to wide char, test if the wide
* char is printable in the current locale. */
if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
length -= n;
if (iswprint(wc) && wc != L'\\') {
/* Printable, copy the bytes through. */
while (n-- > 0)
outbuff[i++] = *p++;
} else {
/* Not printable, format the bytes. */
while (n-- > 0)
i += (unsigned)bsdtar_expand_char(
outbuff, i, *p++);
}
} else {
/* After any conversion failure, don't bother
* trying to convert the rest. */
i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
try_wc = 0;
}
/* If our output buffer is full, dump it and keep going. */
if (i > (sizeof(outbuff) - 20)) {
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
i = 0;
}
}
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
/* If we allocated a heap-based formatting buffer, free it now. */
free(fmtbuff_heap);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Stack-based buffer overflow in the safe_fprintf function in tar/util.c in libarchive 3.2.1 allows remote attackers to cause a denial of service via a crafted non-printable multibyte character in a filename.
Commit Message: Issue #767: Buffer overflow printing a filename
The safe_fprintf function attempts to ensure clean output for an
arbitrary sequence of bytes by doing a trial conversion of the
multibyte characters to wide characters -- if the resulting wide
character is printable then we pass through the corresponding bytes
unaltered, otherwise, we convert them to C-style ASCII escapes.
The stack trace in Issue #767 suggest that the 20-byte buffer
was getting overflowed trying to format a non-printable multibyte
character. This should only happen if there is a valid multibyte
character of more than 5 bytes that was unprintable. (Each byte
would get expanded to a four-charcter octal-style escape of the form
"\123" resulting in >20 characters for the >5 byte multibyte character.)
I've not been able to reproduce this, but have expanded the conversion
buffer to 128 bytes on the belief that no multibyte character set
has a single character of more than 32 bytes. | Medium | 168,766 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void PPB_Buffer_Proxy::OnMsgCreate(
PP_Instance instance,
uint32_t size,
HostResource* result_resource,
ppapi::proxy::SerializedHandle* result_shm_handle) {
result_shm_handle->set_null_shmem();
HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance);
if (!dispatcher)
return;
thunk::EnterResourceCreation enter(instance);
if (enter.failed())
return;
PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance,
size);
if (local_buffer_resource == 0)
return;
thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer(
local_buffer_resource, false);
if (trusted_buffer.failed())
return;
int local_fd;
if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK)
return;
result_resource->SetHostResource(instance, local_buffer_resource);
base::PlatformFile platform_file =
#if defined(OS_WIN)
reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd));
#elif defined(OS_POSIX)
local_fd;
#else
#error Not implemented.
#endif
result_shm_handle->set_shmem(
dispatcher->ShareHandleWithRemote(platform_file, false), size);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 25.0.1364.97 on Windows and Linux, and before 25.0.1364.99 on Mac OS X, allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to databases.
Commit Message: Add permission checks for PPB_Buffer.
BUG=116317
TEST=browser_tests
Review URL: https://chromiumcodereview.appspot.com/11446075
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171951 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,341 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static long __media_device_enum_links(struct media_device *mdev,
struct media_links_enum *links)
{
struct media_entity *entity;
entity = find_entity(mdev, links->entity);
if (entity == NULL)
return -EINVAL;
if (links->pads) {
unsigned int p;
for (p = 0; p < entity->num_pads; p++) {
struct media_pad_desc pad;
media_device_kpad_to_upad(&entity->pads[p], &pad);
if (copy_to_user(&links->pads[p], &pad, sizeof(pad)))
return -EFAULT;
}
}
if (links->links) {
struct media_link_desc __user *ulink;
unsigned int l;
for (l = 0, ulink = links->links; l < entity->num_links; l++) {
struct media_link_desc link;
/* Ignore backlinks. */
if (entity->links[l].source->entity != entity)
continue;
media_device_kpad_to_upad(entity->links[l].source,
&link.source);
media_device_kpad_to_upad(entity->links[l].sink,
&link.sink);
link.flags = entity->links[l].flags;
if (copy_to_user(ulink, &link, sizeof(*ulink)))
return -EFAULT;
ulink++;
}
}
return 0;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: drivers/media/media-device.c in the Linux kernel before 3.11, as used in Android before 2016-08-05 on Nexus 5 and 7 (2013) devices, does not properly initialize certain data structures, which allows local users to obtain sensitive information via a crafted application, aka Android internal bug 28750150 and Qualcomm internal bug CR570757, a different vulnerability than CVE-2014-1739.
Commit Message: [media] media: info leak in __media_device_enum_links()
These structs have holes and reserved struct members which aren't
cleared. I've added a memset() so we don't leak stack information.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Laurent Pinchart <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]> | Medium | 167,576 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: txid_snapshot_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
TxidSnapshot *snap;
txid last = 0;
int nxip;
int i;
int avail;
int expect;
txid xmin,
xmax;
/*
* load nxip and check for nonsense.
*
* (nxip > avail) check is against int overflows in 'expect'.
*/
nxip = pq_getmsgint(buf, 4);
avail = buf->len - buf->cursor;
expect = 8 + 8 + nxip * 8;
if (nxip < 0 || nxip > avail || expect > avail)
goto bad_format;
xmin = pq_getmsgint64(buf);
xmax = pq_getmsgint64(buf);
if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID)
goto bad_format;
snap = palloc(TXID_SNAPSHOT_SIZE(nxip));
snap->xmin = xmin;
snap->xmax = xmax;
snap->nxip = nxip;
SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip));
for (i = 0; i < nxip; i++)
{
txid cur = pq_getmsgint64(buf);
if (cur <= last || cur < xmin || cur >= xmax)
goto bad_format;
snap->xip[i] = cur;
last = cur;
}
PG_RETURN_POINTER(snap);
bad_format:
elog(ERROR, "invalid snapshot data");
return (Datum) NULL;
}
Vulnerability Type: Overflow
CWE ID: CWE-189
Summary: Multiple integer overflows in contrib/hstore/hstore_io.c in PostgreSQL 9.0.x before 9.0.16, 9.1.x before 9.1.12, 9.2.x before 9.2.7, and 9.3.x before 9.3.3 allow remote authenticated users to have unspecified impact via vectors related to the (1) hstore_recv, (2) hstore_from_arrays, and (3) hstore_from_array functions in contrib/hstore/hstore_io.c; and the (4) hstoreArrayToPairs function in contrib/hstore/hstore_op.c, which triggers a buffer overflow. NOTE: this issue was SPLIT from CVE-2014-0064 because it has a different set of affected versions.
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064 | Medium | 166,416 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: The get_icu_value_internal function in ext/intl/locale/locale_methods.c in PHP before 5.5.36, 5.6.x before 5.6.22, and 7.x before 7.0.7 does not ensure the presence of a '0' character, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted locale_get_primary_language call.
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read | High | 167,207 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen)
{
uint8_t optlen, i;
ND_TCHECK(*option);
if (*option >= 32) {
ND_TCHECK(*(option+1));
optlen = *(option +1);
if (optlen < 2) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen too short", *option));
else
ND_PRINT((ndo, "%s optlen too short",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
} else
optlen = 1;
if (hlen < optlen) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen goes past header length",
*option));
else
ND_PRINT((ndo, "%s optlen goes past header length",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
ND_TCHECK2(*option, optlen);
if (*option >= 128) {
ND_PRINT((ndo, "CCID option %d", *option));
switch (optlen) {
case 4:
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
break;
case 6:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
break;
default:
break;
}
} else {
ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option)));
switch (*option) {
case 32:
case 33:
case 34:
case 35:
if (optlen < 3) {
ND_PRINT((ndo, " optlen too short"));
return optlen;
}
if (*(option + 2) < 10){
ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)]));
for (i = 0; i < optlen - 3; i++)
ND_PRINT((ndo, " %d", *(option + 3 + i)));
}
break;
case 36:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 37:
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, " %d", *(option + 2 + i)));
break;
case 38:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 39:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 40:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 41:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 42:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 43:
if (optlen == 6)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4 or 6"));
break;
case 44:
if (optlen > 2) {
ND_PRINT((ndo, " "));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
}
}
return optlen;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The DCCP parser in tcpdump before 4.9.3 has a buffer over-read in print-dccp.c:dccp_print_option().
Commit Message: (for 4.9.3) CVE-2018-16229/DCCP: Fix printing "Timestamp" and "Timestamp Echo" options
Add some comments.
Moreover:
Put a function definition name at the beginning of the line.
(This change was ported from commit 6df4852 in the master branch.)
Ryan Ackroyd had independently identified this buffer over-read later by
means of fuzzing and provided the packet capture file for the test. | High | 169,819 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
AVFilterContext *ctx = inlink->dst;
FPSContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int64_t delta;
int i, ret;
s->frames_in++;
/* discard frames until we get the first timestamp */
if (s->pts == AV_NOPTS_VALUE) {
if (buf->pts != AV_NOPTS_VALUE) {
ret = write_to_fifo(s->fifo, buf);
if (ret < 0)
return ret;
if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
double first_pts = s->start_time * AV_TIME_BASE;
first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
inlink->time_base);
av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
outlink->time_base));
} else {
s->first_pts = s->pts = buf->pts;
}
} else {
av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
"timestamp.\n");
av_frame_free(&buf);
s->drop++;
}
return 0;
}
/* now wait for the next timestamp */
if (buf->pts == AV_NOPTS_VALUE) {
return write_to_fifo(s->fifo, buf);
}
/* number of output frames */
delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
outlink->time_base, s->rounding);
if (delta < 1) {
/* drop the frame and everything buffered except the first */
AVFrame *tmp;
int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
s->drop += drop;
av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, tmp);
av_frame_free(&buf);
return ret;
}
/* can output >= 1 frames */
for (i = 0; i < delta; i++) {
AVFrame *buf_out;
av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
/* duplicate the frame if needed */
if (!av_fifo_size(s->fifo) && i < delta - 1) {
AVFrame *dup = av_frame_clone(buf_out);
av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
if (dup)
ret = write_to_fifo(s->fifo, dup);
else
ret = AVERROR(ENOMEM);
if (ret < 0) {
av_frame_free(&buf_out);
av_frame_free(&buf);
return ret;
}
s->dup++;
}
buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
outlink->time_base) + s->frames_out;
if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
av_frame_free(&buf);
return ret;
}
s->frames_out++;
}
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, buf);
s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: The filter_frame function in libavfilter/vf_fps.c in FFmpeg before 2.1 does not properly ensure the availability of FIFO content, which allows remote attackers to cause a denial of service (double free) or possibly have unspecified other impact via crafted data.
Commit Message: avfilter/vf_fps: make sure the fifo is not empty before using it
Fixes Ticket2905
Signed-off-by: Michael Niedermayer <[email protected]> | Medium | 165,916 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int iscsi_decode_text_input(
u8 phase,
u8 sender,
char *textbuf,
u32 length,
struct iscsi_conn *conn)
{
struct iscsi_param_list *param_list = conn->param_list;
char *tmpbuf, *start = NULL, *end = NULL;
tmpbuf = kzalloc(length + 1, GFP_KERNEL);
if (!tmpbuf) {
pr_err("Unable to allocate memory for tmpbuf.\n");
return -1;
}
memcpy(tmpbuf, textbuf, length);
tmpbuf[length] = '\0';
start = tmpbuf;
end = (start + length);
while (start < end) {
char *key, *value;
struct iscsi_param *param;
if (iscsi_extract_key_value(start, &key, &value) < 0) {
kfree(tmpbuf);
return -1;
}
pr_debug("Got key: %s=%s\n", key, value);
if (phase & PHASE_SECURITY) {
if (iscsi_check_for_auth_key(key) > 0) {
char *tmpptr = key + strlen(key);
*tmpptr = '=';
kfree(tmpbuf);
return 1;
}
}
param = iscsi_check_key(key, phase, sender, param_list);
if (!param) {
if (iscsi_add_notunderstood_response(key,
value, param_list) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
continue;
}
if (iscsi_check_value(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
if (IS_PSTATE_PROPOSER(param)) {
if (iscsi_check_proposer_state(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_RESPONSE_GOT(param);
} else {
if (iscsi_check_acceptor_state(param, value, conn) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_ACCEPTOR(param);
}
}
kfree(tmpbuf);
return 0;
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: Heap-based buffer overflow in the iscsi_add_notunderstood_response function in drivers/target/iscsi/iscsi_target_parameters.c in the iSCSI target subsystem in the Linux kernel through 3.9.4 allows remote attackers to cause a denial of service (memory corruption and OOPS) or possibly execute arbitrary code via a long key that is not properly handled during construction of an error-response packet.
Commit Message: iscsi-target: fix heap buffer overflow on error
If a key was larger than 64 bytes, as checked by iscsi_check_key(), the
error response packet, generated by iscsi_add_notunderstood_response(),
would still attempt to copy the entire key into the packet, overflowing
the structure on the heap.
Remote preauthentication kernel memory corruption was possible if a
target was configured and listening on the network.
CVE-2013-2850
Signed-off-by: Kees Cook <[email protected]>
Cc: [email protected]
Signed-off-by: Nicholas Bellinger <[email protected]> | High | 166,051 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: gss_context_time (minor_status,
context_handle,
time_rec)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
OM_uint32 * time_rec;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
*minor_status = 0;
if (time_rec == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
if (context_handle == GSS_C_NO_CONTEXT)
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
/*
* 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_context_time) {
status = mech->gss_context_time(
minor_status,
ctx->internal_ctx_id,
time_rec);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
return (GSS_S_BAD_MECH);
}
Vulnerability Type:
CWE ID: CWE-415
Summary: Double free vulnerability in MIT Kerberos 5 (aka krb5) allows attackers to have unspecified impact via vectors involving automatic deletion of security contexts on error.
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 | High | 168,013 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
#if defined(OS_WIN)
base::SharedMemory shared_memory(transfer_buffer,
false,
channel_->renderer_process());
#else
#endif
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
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 | High | 170,938 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped");
if (!view_) {
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
false,
0);
return;
}
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params;
gpu_params.surface_id = surface_id;
gpu_params.surface_handle = surface_handle;
gpu_params.route_id = route_id;
gpu_params.size = size;
#if defined(OS_MACOSX)
gpu_params.window = gfx::kNullPluginWindow;
#endif
view_->AcceleratedSurfaceBuffersSwapped(gpu_params,
gpu_process_host_id);
}
Vulnerability Type:
CWE ID:
Summary: Google Chrome before 25.0.1364.99 on Mac OS X does not properly implement signal handling for Native Client (aka NaCl) code, which has unspecified impact and attack vectors.
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,367 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: cib_remote_perform_op(cib_t * cib, const char *op, const char *host, const char *section,
xmlNode * data, xmlNode ** output_data, int call_options, const char *name)
{
int rc = pcmk_ok;
xmlNode *op_msg = NULL;
xmlNode *op_reply = NULL;
cib_remote_opaque_t *private = cib->variant_opaque;
if (sync_timer == NULL) {
sync_timer = calloc(1, sizeof(struct timer_rec_s));
}
if (cib->state == cib_disconnected) {
return -ENOTCONN;
}
if (output_data != NULL) {
*output_data = NULL;
}
if (op == NULL) {
crm_err("No operation specified");
return -EINVAL;
}
cib->call_id++;
/* prevent call_id from being negative (or zero) and conflicting
* with the cib_errors enum
* use 2 because we use it as (cib->call_id - 1) below
*/
if (cib->call_id < 1) {
cib->call_id = 1;
}
op_msg =
cib_create_op(cib->call_id, private->callback.token, op, host, section, data, call_options,
NULL);
if (op_msg == NULL) {
return -EPROTO;
}
crm_trace("Sending %s message to CIB service", op);
crm_send_remote_msg(private->command.session, op_msg, private->command.encrypted);
free_xml(op_msg);
if ((call_options & cib_discard_reply)) {
crm_trace("Discarding reply");
return pcmk_ok;
} else if (!(call_options & cib_sync_call)) {
return cib->call_id;
}
crm_trace("Waiting for a syncronous reply");
if (cib->call_timeout > 0) {
/* We need this, even with msgfromIPC_timeout(), because we might
* get other/older replies that don't match the active request
*/
timer_expired = FALSE;
sync_timer->call_id = cib->call_id;
sync_timer->timeout = cib->call_timeout * 1000;
sync_timer->ref = g_timeout_add(sync_timer->timeout, cib_timeout_handler, sync_timer);
}
while (timer_expired == FALSE) {
int reply_id = -1;
int msg_id = cib->call_id;
op_reply = crm_recv_remote_msg(private->command.session, private->command.encrypted);
if (op_reply == NULL) {
break;
}
crm_element_value_int(op_reply, F_CIB_CALLID, &reply_id);
CRM_CHECK(reply_id > 0, free_xml(op_reply);
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref); sync_timer->ref = 0;}
return -ENOMSG) ;
if (reply_id == msg_id) {
break;
} else if (reply_id < msg_id) {
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else if ((reply_id - 10000) > msg_id) {
/* wrap-around case */
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else {
crm_err("Received a __future__ reply:" " %d (wanted %d)", reply_id, msg_id);
}
free_xml(op_reply);
op_reply = NULL;
}
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref);
sync_timer->ref = 0;
}
if (timer_expired) {
return -ETIME;
}
/* if(IPC_ISRCONN(native->command_channel) == FALSE) { */
/* crm_err("CIB disconnected: %d", */
/* native->command_channel->ch_status); */
/* cib->state = cib_disconnected; */
/* } */
if (op_reply == NULL) {
crm_err("No reply message - empty");
return -ENOMSG;
}
crm_trace("Syncronous reply received");
/* Start processing the reply... */
if (crm_element_value_int(op_reply, F_CIB_RC, &rc) != 0) {
rc = -EPROTO;
}
if (rc == -pcmk_err_diff_resync) {
/* This is an internal value that clients do not and should not care about */
rc = pcmk_ok;
}
if (rc == pcmk_ok || rc == -EPERM) {
crm_log_xml_debug(op_reply, "passed");
} else {
/* } else if(rc == -ETIME) { */
crm_err("Call failed: %s", pcmk_strerror(rc));
crm_log_xml_warn(op_reply, "failed");
}
if (output_data == NULL) {
/* do nothing more */
} else if (!(call_options & cib_discard_reply)) {
xmlNode *tmp = get_message_xml(op_reply, F_CIB_CALLDATA);
if (tmp == NULL) {
crm_trace("No output in reply to \"%s\" command %d", op, cib->call_id - 1);
} else {
*output_data = copy_xml(tmp);
}
}
free_xml(op_reply);
return rc;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Pacemaker 1.1.10, when remote Cluster Information Base (CIB) configuration or resource management is enabled, does not limit the duration of connections to the blocking sockets, which allows remote attackers to cause a denial of service (connection blocking).
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. | Medium | 166,152 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId,
wStream* s)
{
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp,
cbChId,
ChannelId);
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Vulnerability Type:
CWE ID:
Summary: FreeRDP FreeRDP 2.0.0-rc3 released version before commit 205c612820dac644d665b5bb1cdf437dc5ca01e3 contains a Other/Unknown vulnerability in channels/drdynvc/client/drdynvc_main.c, drdynvc_process_capability_request that can result in The RDP server can read the client's memory.. This attack appear to be exploitable via RDPClient must connect the rdp server with echo option. This vulnerability appears to have been fixed in after commit 205c612820dac644d665b5bb1cdf437dc5ca01e3.
Commit Message: Fix for #4866: Added additional length checks | High | 168,937 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base.
*/
size_t off = 0, len = 0;
if (cmd & 0x01) off = *delta++;
if (cmd & 0x02) off |= *delta++ << 8UL;
if (cmd & 0x04) off |= *delta++ << 16UL;
if (cmd & 0x08) off |= *delta++ << 24UL;
if (cmd & 0x10) len = *delta++;
if (cmd & 0x20) len |= *delta++ << 8UL;
if (cmd & 0x40) len |= *delta++ << 16UL;
if (!len) len = 0x10000;
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
}
else if (cmd) {
/* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
}
else {
/* cmd == 0 is reserved for future encodings.
*/
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-125
Summary: A flaw was found in libgit2 before version 0.27.3. It has been discovered that an unexpected sign extension in git_delta_apply function in delta.c file may lead to an integer overflow which in turn leads to an out of bound read, allowing to read before the base object. An attacker may use this flaw to leak memory addresses or cause a Denial of Service.
Commit Message: delta: fix sign-extension of big left-shift
Our delta code was originally adapted from JGit, which itself adapted it
from git itself. Due to this heritage, we inherited a bug from git.git
in how we compute the delta offset, which was fixed upstream in
48fb7deb5 (Fix big left-shifts of unsigned char, 2009-06-17). As
explained by Linus:
Shifting 'unsigned char' or 'unsigned short' left can result in sign
extension errors, since the C integer promotion rules means that the
unsigned char/short will get implicitly promoted to a signed 'int' due to
the shift (or due to other operations).
This normally doesn't matter, but if you shift things up sufficiently, it
will now set the sign bit in 'int', and a subsequent cast to a bigger type
(eg 'long' or 'unsigned long') will now sign-extend the value despite the
original expression being unsigned.
One example of this would be something like
unsigned long size;
unsigned char c;
size += c << 24;
where despite all the variables being unsigned, 'c << 24' ends up being a
signed entity, and will get sign-extended when then doing the addition in
an 'unsigned long' type.
Since git uses 'unsigned char' pointers extensively, we actually have this
bug in a couple of places.
In our delta code, we inherited such a bogus shift when computing the
offset at which the delta base is to be found. Due to the sign extension
we can end up with an offset where all the bits are set. This can allow
an arbitrary memory read, as the addition in `base_len < off + len` can
now overflow if `off` has all its bits set.
Fix the issue by casting the result of `*delta++ << 24UL` to an unsigned
integer again. Add a test with a crafted delta that would actually
succeed with an out-of-bounds read in case where the cast wouldn't
exist.
Reported-by: Riccardo Schirone <[email protected]>
Test-provided-by: Riccardo Schirone <[email protected]> | Medium | 170,168 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image)
{
#define CFormat "/Filter [ /%s ]\n"
#define ObjectsPerImage 14
DisableMSCWarning(4310)
static const char
XMPProfile[]=
{
"<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
" <xap:ModifyDate>%s</xap:ModifyDate>\n"
" <xap:CreateDate>%s</xap:CreateDate>\n"
" <xap:MetadataDate>%s</xap:MetadataDate>\n"
" <xap:CreatorTool>%s</xap:CreatorTool>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:format>application/pdf</dc:format>\n"
" <dc:title>\n"
" <rdf:Alt>\n"
" <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
" </rdf:Alt>\n"
" </dc:title>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
" <pdf:Producer>%s</pdf:Producer>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
" <pdfaid:part>3</pdfaid:part>\n"
" <pdfaid:conformance>B</pdfaid:conformance>\n"
" </rdf:Description>\n"
" </rdf:RDF>\n"
"</x:xmpmeta>\n"
"<?xpacket end=\"w\"?>\n"
},
XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
RestoreMSCWarning
char
basename[MaxTextExtent],
buffer[MaxTextExtent],
date[MaxTextExtent],
*escape,
**labels,
page_geometry[MaxTextExtent],
*url;
CompressionType
compression;
const char
*device,
*option,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
Image
*next,
*tile_image;
MagickBooleanType
status;
MagickOffsetType
offset,
scene,
*xref;
MagickSizeType
number_pixels;
MagickStatusType
flags;
PointInfo
delta,
resolution,
scale;
RectangleInfo
geometry,
media_info,
page_info;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register unsigned char
*q;
register ssize_t
i,
x;
size_t
channels,
info_id,
length,
object,
pages_id,
root_id,
text_size,
version;
ssize_t
count,
page_count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
wchar_t
*utf16;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Allocate X ref memory.
*/
xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref));
/*
Write Info object.
*/
object=0;
version=3;
if (image_info->compression == JPEG2000Compression)
version=(size_t) MagickMax(version,5);
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
if (next->matte != MagickFalse)
version=(size_t) MagickMax(version,4);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
version=(size_t) MagickMax(version,6);
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
version=(size_t) MagickMax(version,7);
(void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double)
version);
(void) WriteBlobString(image,buffer);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
(void) WriteBlobByte(image,'%');
(void) WriteBlobByte(image,0xe2);
(void) WriteBlobByte(image,0xe3);
(void) WriteBlobByte(image,0xcf);
(void) WriteBlobByte(image,0xd3);
(void) WriteBlobByte(image,'\n');
}
/*
Write Catalog object.
*/
xref[object++]=TellBlob(image);
root_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") != 0)
(void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double)
object+1);
else
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",
(double) object+2);
}
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Catalog");
option=GetImageOption(image_info,"pdf:page-direction");
if ((option != (const char *) NULL) &&
(LocaleCompare(option,"right-to-left") != MagickFalse))
(void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n");
(void) WriteBlobString(image,"\n");
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
GetPathComponent(image->filename,BasePath,basename);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
char
create_date[MaxTextExtent],
modify_date[MaxTextExtent],
timestamp[MaxTextExtent],
xmp_profile[MaxTextExtent],
*url;
/*
Write XMP object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Subtype /XML\n");
*modify_date='\0';
value=GetImageProperty(image,"date:modify");
if (value != (const char *) NULL)
(void) CopyMagickString(modify_date,value,MaxTextExtent);
*create_date='\0';
value=GetImageProperty(image,"date:create");
if (value != (const char *) NULL)
(void) CopyMagickString(create_date,value,MaxTextExtent);
(void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp);
url=GetMagickHomeURL();
escape=EscapeParenthesis(basename);
i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile,
XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);
escape=DestroyString(escape);
url=DestroyString(url);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double)
i);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Metadata\n");
(void) WriteBlobString(image,">>\nstream\n");
(void) WriteBlobString(image,xmp_profile);
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
}
/*
Write Pages object.
*/
xref[object++]=TellBlob(image);
pages_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Pages\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double)
object+1);
(void) WriteBlobString(image,buffer);
count=(ssize_t) (pages_id+ObjectsPerImage+1);
page_count=1;
if (image_info->adjoin != MagickFalse)
{
Image
*kid_image;
/*
Predict page object id's.
*/
kid_image=image;
for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
{
page_count++;
profile=GetImageProfile(kid_image,"icc");
if (profile != (StringInfo *) NULL)
count+=2;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double)
count);
(void) WriteBlobString(image,buffer);
kid_image=GetNextImageInList(kid_image);
}
xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobString(image,"]\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double)
page_count);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
scene=0;
do
{
MagickBooleanType
has_icc_profile;
profile=GetImageProfile(image,"icc");
has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if ((SetImageMonochrome(image,&image->exception) == MagickFalse) ||
(image->matte != MagickFalse))
compression=RLECompression;
break;
}
#if !defined(MAGICKCORE_JPEG_DELEGATE)
case JPEGCompression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
case JPEG2000Compression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_ZLIB_DELEGATE)
case ZipCompression:
{
compression=RLECompression;
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
image->filename);
break;
}
#endif
case LZWCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* LZW compression is forbidden */
break;
}
case NoCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* ASCII 85 compression is forbidden */
break;
}
default:
break;
}
if (compression == JPEG2000Compression)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Scale relative to dots-per-inch.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->x_resolution;
resolution.y=image->y_resolution;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double)
image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PDF") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
(void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,
&image->exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
(void) text_size;
/*
Write Page object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Page\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n",
(double) pages_id);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Resources <<\n");
labels=(char **) NULL;
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+4);
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MaxTextExtent,
"/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+5);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n",
(double) object+3);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 10 : 8));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Contents object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
(void) WriteBlobString(image,"q\n");
if (labels != (char **) NULL)
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) WriteBlobString(image,"BT\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n",
(double) image->scene,pointsize);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n",
(double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
12));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"ET\n");
labels[i]=DestroyString(labels[i]);
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n",
scale.x,scale.y,(double) geometry.x,(double) geometry.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"Q\n");
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Procset object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent);
else
if ((compression == FaxCompression) || (compression == Group4Compression))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent);
else
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ]\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Font object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (labels != (char **) NULL)
{
(void) WriteBlobString(image,"/Type /Font\n");
(void) WriteBlobString(image,"/Subtype /Type1\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/BaseFont /Helvetica\n");
(void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
labels=(char **) RelinquishMagickMemory(labels);
}
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write XObject object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) image->columns,(double) image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
(double) object+2);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
if (image->matte != MagickFalse)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 9 : 7));
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((compression == FaxCompression) || (compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,image);
break;
}
(void) Huffman2DEncodeImage(image_info,image,image);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
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++=ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p)));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
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++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelIndex(indexes+x));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelIndex(indexes+x)));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
Ascii85Encode(image,(unsigned char)
GetPixelIndex(indexes+x));
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Colorspace object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
device="DeviceRGB";
channels=0;
if (image->colorspace == CMYKColorspace)
{
device="DeviceCMYK";
channels=4;
}
else
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse)))
{
device="DeviceGray";
channels=1;
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
{
device="DeviceRGB";
channels=3;
}
profile=GetImageProfile(image,"icc");
if ((profile == (StringInfo *) NULL) || (channels == 0))
{
if (channels != 0)
(void) FormatLocaleString(buffer,MaxTextExtent,"/%s\n",device);
else
(void) FormatLocaleString(buffer,MaxTextExtent,
"[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors-
1,(double) object+3);
(void) WriteBlobString(image,buffer);
}
else
{
const unsigned char
*p;
/*
Write ICC profile.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,
"[/ICCBased %.20g 0 R]\n",(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"<<\n/N %.20g\n"
"/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n"
"stream\n",(double) channels,(double) object+1,device);
(void) WriteBlobString(image,buffer);
offset=TellBlob(image);
Ascii85Initialize(image);
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
Ascii85Encode(image,(unsigned char) *p++);
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"endstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Thumb object.
*/
SetGeometry(image,&geometry);
(void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
tile_image=ThumbnailImage(image,geometry.width,geometry.height,
&image->exception);
if (tile_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,image->exception.reason);
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MaxTextExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MaxTextExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) tile_image->columns,(double) tile_image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
tile_image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
tile_image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
(double) object-(has_icc_profile != MagickFalse ? 3 : 1));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(tile_image,&image->exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,tile_image);
break;
}
(void) Huffman2DEncodeImage(image_info,image,tile_image);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p)));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p))));
p++;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((tile_image->storage_class == DirectClass) ||
(tile_image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CoderError,tile_image->exception.reason);
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runoffset encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
if (tile_image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelIndex(indexes+x));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelIndex(indexes+x)));
p++;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
&tile_image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
Ascii85Encode(image,(unsigned char)
GetPixelIndex(indexes+x));
}
Ascii85Flush(image);
break;
}
}
}
tile_image=DestroyImage(tile_image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == FaxCompression) || (compression == Group4Compression))
(void) WriteBlobString(image,">>\n");
else
{
/*
Write Colormap object.
*/
if (compression == NoCompression)
(void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
if (compression == NoCompression)
Ascii85Initialize(image);
for (i=0; i < (ssize_t) image->colors; i++)
{
if (compression == NoCompression)
{
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red));
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green));
Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue));
continue;
}
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].red));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].green));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[i].blue));
}
if (compression == NoCompression)
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write softmask object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (image->matte == MagickFalse)
(void) WriteBlobString(image,">>\n");
else
{
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"ASCII85Decode");
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"FlateDecode");
break;
}
default:
{
(void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression)
? 1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
image=DestroyImage(image);
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
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++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels);
else
status=PackbitsEncodeImage(image,length,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
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++)
{
Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange-
GetPixelOpacity(p))));
p++;
}
}
Ascii85Flush(image);
break;
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
/*
Write Metadata object.
*/
xref[object++]=TellBlob(image);
info_id=object;
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);
if (utf16 != (wchar_t *) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"/Title (\xfe\xff");
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) length; i++)
(void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);
(void) FormatLocaleString(buffer,MaxTextExtent,")\n");
(void) WriteBlobString(image,buffer);
utf16=(wchar_t *) RelinquishMagickMemory(utf16);
}
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d",
local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
(void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
url=GetMagickHomeURL();
escape=EscapeParenthesis(url);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape);
escape=DestroyString(escape);
url=DestroyString(url);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Xref object.
*/
offset=TellBlob(image)-xref[0]+
(LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
(void) WriteBlobString(image,"xref\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"0000000000 65535 f \n");
for (i=0; i < (ssize_t) object; i++)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n",
(unsigned long) xref[i]);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"trailer\n");
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double)
info_id);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double)
root_id);
(void) WriteBlobString(image,buffer);
(void) SignatureImage(image);
(void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n",
GetImageProperty(image,"signature"),GetImageProperty(image,"signature"));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"startxref\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%EOF\n");
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
(void) CloseBlob(image);
return(MagickTrue);
}
Vulnerability Type:
CWE ID: CWE-772
Summary: ImageMagick 7.0.6-2 has a memory leak vulnerability in WritePDFImage in coders/pdf.c.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/576 | Medium | 167,977 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
client->priv->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)_client_protocol_timeout,
client);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
Vulnerability Type:
CWE ID: CWE-835
Summary: Bad reference counting in the context of accept_ice_connection() in gsm-xsmp-server.c in old versions of gnome-session up until version 2.29.92 allows a local attacker to establish ICE connections to gnome-session with invalid authentication data (an invalid magic cookie). Each failed authentication attempt will leak a file descriptor in gnome-session. When the maximum number of file descriptors is exhausted in the gnome-session process, it will enter an infinite loop trying to communicate without success, consuming 100% of the CPU. The graphical session associated with the gnome-session process will stop working correctly, because communication with gnome-session is no longer possible.
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211 | Medium | 168,051 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType)
{
bool errorOccurred = false;
double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0;
ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred);
pendingScript.stopWatchingForLoad(this);
if (!isExecutingScript()) {
Microtask::performCheckpoint();
if (pendingScriptType == PendingScript::ParsingBlocking) {
m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady();
if (m_hasScriptsWaitingForResources)
return;
}
}
RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear();
double compilationFinishTime = 0;
if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) {
scriptLoader->dispatchErrorEvent();
} else {
element->dispatchEvent(createScriptLoadEvent());
}
}
}
const double epsilon = 1;
if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) {
Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50);
}
ASSERT(!isExecutingScript());
}
Vulnerability Type: Bypass
CWE ID: CWE-254
Summary: core/loader/ImageLoader.cpp in Blink, as used in Google Chrome before 44.0.2403.89, does not properly determine the V8 context of a microtask, which allows remote attackers to bypass Content Security Policy (CSP) restrictions by providing an image from an unintended source.
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | Medium | 171,946 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void chase_port(struct edgeport_port *port, unsigned long timeout,
int flush)
{
int baud_rate;
struct tty_struct *tty = tty_port_tty_get(&port->port->port);
struct usb_serial *serial = port->port->serial;
wait_queue_t wait;
unsigned long flags;
if (!timeout)
timeout = (HZ * EDGE_CLOSING_WAIT)/100;
/* wait for data to drain from the buffer */
spin_lock_irqsave(&port->ep_lock, flags);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tty->write_wait, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (kfifo_len(&port->write_fifo) == 0
|| timeout == 0 || signal_pending(current)
|| serial->disconnected)
/* disconnect */
break;
spin_unlock_irqrestore(&port->ep_lock, flags);
timeout = schedule_timeout(timeout);
spin_lock_irqsave(&port->ep_lock, flags);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&tty->write_wait, &wait);
if (flush)
kfifo_reset_out(&port->write_fifo);
spin_unlock_irqrestore(&port->ep_lock, flags);
tty_kref_put(tty);
/* wait for data to drain from the device */
timeout += jiffies;
while ((long)(jiffies - timeout) < 0 && !signal_pending(current)
&& !serial->disconnected) {
/* not disconnected */
if (!tx_active(port))
break;
msleep(10);
}
/* disconnected */
if (serial->disconnected)
return;
/* wait one more character time, based on baud rate */
/* (tx_active doesn't seem to wait for the last byte) */
baud_rate = port->baud_rate;
if (baud_rate == 0)
baud_rate = 50;
msleep(max(1, DIV_ROUND_UP(10000, baud_rate)));
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The chase_port function in drivers/usb/serial/io_ti.c in the Linux kernel before 3.7.4 allows local users to cause a denial of service (NULL pointer dereference and system crash) via an attempted /dev/ttyUSB read or write operation on a disconnected Edgeport USB serial converter.
Commit Message: USB: io_ti: Fix NULL dereference in chase_port()
The tty is NULL when the port is hanging up.
chase_port() needs to check for this.
This patch is intended for stable series.
The behavior was observed and tested in Linux 3.2 and 3.7.1.
Johan Hovold submitted a more elaborate patch for the mainline kernel.
[ 56.277883] usb 1-1: edge_bulk_in_callback - nonzero read bulk status received: -84
[ 56.278811] usb 1-1: USB disconnect, device number 3
[ 56.278856] usb 1-1: edge_bulk_in_callback - stopping read!
[ 56.279562] BUG: unable to handle kernel NULL pointer dereference at 00000000000001c8
[ 56.280536] IP: [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.281212] PGD 1dc1b067 PUD 1e0f7067 PMD 0
[ 56.282085] Oops: 0002 [#1] SMP
[ 56.282744] Modules linked in:
[ 56.283512] CPU 1
[ 56.283512] Pid: 25, comm: khubd Not tainted 3.7.1 #1 innotek GmbH VirtualBox/VirtualBox
[ 56.283512] RIP: 0010:[<ffffffff8144e62a>] [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.283512] RSP: 0018:ffff88001fa99ab0 EFLAGS: 00010046
[ 56.283512] RAX: 0000000000000046 RBX: 00000000000001c8 RCX: 0000000000640064
[ 56.283512] RDX: 0000000000010000 RSI: ffff88001fa99b20 RDI: 00000000000001c8
[ 56.283512] RBP: ffff88001fa99b20 R08: 0000000000000000 R09: 0000000000000000
[ 56.283512] R10: 0000000000000000 R11: ffffffff812fcb4c R12: ffff88001ddf53c0
[ 56.283512] R13: 0000000000000000 R14: 00000000000001c8 R15: ffff88001e19b9f4
[ 56.283512] FS: 0000000000000000(0000) GS:ffff88001fd00000(0000) knlGS:0000000000000000
[ 56.283512] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[ 56.283512] CR2: 00000000000001c8 CR3: 000000001dc51000 CR4: 00000000000006e0
[ 56.283512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 56.283512] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 56.283512] Process khubd (pid: 25, threadinfo ffff88001fa98000, task ffff88001fa94f80)
[ 56.283512] Stack:
[ 56.283512] 0000000000000046 00000000000001c8 ffffffff810578ec ffffffff812fcb4c
[ 56.283512] ffff88001e19b980 0000000000002710 ffffffff812ffe81 0000000000000001
[ 56.283512] ffff88001fa94f80 0000000000000202 ffffffff00000001 0000000000000296
[ 56.283512] Call Trace:
[ 56.283512] [<ffffffff810578ec>] ? add_wait_queue+0x12/0x3c
[ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28
[ 56.283512] [<ffffffff812ffe81>] ? chase_port+0x84/0x2d6
[ 56.283512] [<ffffffff81063f27>] ? try_to_wake_up+0x199/0x199
[ 56.283512] [<ffffffff81263a5c>] ? tty_ldisc_hangup+0x222/0x298
[ 56.283512] [<ffffffff81300171>] ? edge_close+0x64/0x129
[ 56.283512] [<ffffffff810612f7>] ? __wake_up+0x35/0x46
[ 56.283512] [<ffffffff8106135b>] ? should_resched+0x5/0x23
[ 56.283512] [<ffffffff81264916>] ? tty_port_shutdown+0x39/0x44
[ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28
[ 56.283512] [<ffffffff8125d38c>] ? __tty_hangup+0x307/0x351
[ 56.283512] [<ffffffff812e6ddc>] ? usb_hcd_flush_endpoint+0xde/0xed
[ 56.283512] [<ffffffff8144e625>] ? _raw_spin_lock_irqsave+0x14/0x35
[ 56.283512] [<ffffffff812fd361>] ? usb_serial_disconnect+0x57/0xc2
[ 56.283512] [<ffffffff812ea99b>] ? usb_unbind_interface+0x5c/0x131
[ 56.283512] [<ffffffff8128d738>] ? __device_release_driver+0x7f/0xd5
[ 56.283512] [<ffffffff8128d9cd>] ? device_release_driver+0x1a/0x25
[ 56.283512] [<ffffffff8128d393>] ? bus_remove_device+0xd2/0xe7
[ 56.283512] [<ffffffff8128b7a3>] ? device_del+0x119/0x167
[ 56.283512] [<ffffffff812e8d9d>] ? usb_disable_device+0x6a/0x180
[ 56.283512] [<ffffffff812e2ae0>] ? usb_disconnect+0x81/0xe6
[ 56.283512] [<ffffffff812e4435>] ? hub_thread+0x577/0xe82
[ 56.283512] [<ffffffff8144daa7>] ? __schedule+0x490/0x4be
[ 56.283512] [<ffffffff8105798f>] ? abort_exclusive_wait+0x79/0x79
[ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f
[ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f
[ 56.283512] [<ffffffff810570b4>] ? kthread+0x81/0x89
[ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c
[ 56.283512] [<ffffffff8145387c>] ? ret_from_fork+0x7c/0xb0
[ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c
[ 56.283512] Code: 8b 7c 24 08 e8 17 0b c3 ff 48 8b 04 24 48 83 c4 10 c3 53 48 89 fb 41 50 e8 e0 0a c3 ff 48 89 04 24 e8 e7 0a c3 ff ba 00 00 01 00
<f0> 0f c1 13 48 8b 04 24 89 d1 c1 ea 10 66 39 d1 74 07 f3 90 66
[ 56.283512] RIP [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.283512] RSP <ffff88001fa99ab0>
[ 56.283512] CR2: 00000000000001c8
[ 56.283512] ---[ end trace 49714df27e1679ce ]---
Signed-off-by: Wolfgang Frisch <[email protected]>
Cc: Johan Hovold <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]> | Medium | 166,122 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void WebGLRenderingContextBase::linkProgram(WebGLProgram* program) {
if (!ValidateWebGLProgramOrShader("linkProgram", program))
return;
if (program->ActiveTransformFeedbackCount() > 0) {
SynthesizeGLError(
GL_INVALID_OPERATION, "linkProgram",
"program being used by one or more active transform feedback objects");
return;
}
ContextGL()->LinkProgram(ObjectOrZero(program));
program->IncreaseLinkCount();
}
Vulnerability Type:
CWE ID: CWE-416
Summary: A heap use after free in V8 in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page.
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568} | Medium | 172,537 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void pcd_init_units(void)
{
struct pcd_unit *cd;
int unit;
pcd_drive_count = 0;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
struct gendisk *disk = alloc_disk(1);
if (!disk)
continue;
disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops,
1, BLK_MQ_F_SHOULD_MERGE);
if (IS_ERR(disk->queue)) {
disk->queue = NULL;
continue;
}
INIT_LIST_HEAD(&cd->rq_list);
disk->queue->queuedata = cd;
blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH);
cd->disk = disk;
cd->pi = &cd->pia;
cd->present = 0;
cd->last_sense = 0;
cd->changed = 1;
cd->drive = (*drives[unit])[D_SLV];
if ((*drives[unit])[D_PRT])
pcd_drive_count++;
cd->name = &cd->info.name[0];
snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit);
cd->info.ops = &pcd_dops;
cd->info.handle = cd;
cd->info.speed = 0;
cd->info.capacity = 1;
cd->info.mask = 0;
disk->major = major;
disk->first_minor = unit;
strcpy(disk->disk_name, cd->name); /* umm... */
disk->fops = &pcd_bdops;
disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
}
}
Vulnerability Type:
CWE ID: CWE-476
Summary: An issue was discovered in the Linux kernel before 5.0.9. There is a NULL pointer dereference for a cd data structure if alloc_disk fails in drivers/block/paride/pf.c.
Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak
Syzkaller report this:
pcd: pcd version 1.07, major 46, nice 0
pcd0: Autoprobe failed
pcd: No CD-ROM drive found
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pcd_init+0x95c/0x1000 [pcd]
Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2
RSP: 0018:ffff8881e84df880 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935
RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8
R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000
R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003
FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1508000
? 0xffffffffc1508000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd
ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace d873691c3cd69f56 ]---
If alloc_disk fails in pcd_init_units, cd->disk will be
NULL, however in pcd_detect and pcd_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]> | Medium | 169,520 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', 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 */
{
if (compiler->loop_depth > 0)
{
compiler->loop_depth--;
compiler->loop_identifier[compiler->loop_depth] = NULL;
}
}
#line 2597 "grammar.c" /* yacc.c:1646 */
break;
case 63:
#line 1027 "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 2631 "grammar.c" /* yacc.c:1646 */
break;
case 64:
#line 1057 "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 2670 "grammar.c" /* yacc.c:1646 */
break;
case 65:
#line 1092 "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 2753 "grammar.c" /* yacc.c:1646 */
break;
case 66:
#line 1171 "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 2787 "grammar.c" /* yacc.c:1646 */
break;
case 67:
#line 1201 "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 2840 "grammar.c" /* yacc.c:1646 */
break;
case 68:
#line 1250 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_OF, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2850 "grammar.c" /* yacc.c:1646 */
break;
case 69:
#line 1256 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit(yyscanner, OP_NOT, NULL);
(yyval.expression).type = EXPRESSION_TYPE_BOOLEAN;
}
#line 2860 "grammar.c" /* yacc.c:1646 */
break;
case 70:
#line 1262 "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 2890 "grammar.c" /* yacc.c:1646 */
break;
case 71:
#line 1288 "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 2930 "grammar.c" /* yacc.c:1646 */
break;
case 72:
#line 1324 "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 2959 "grammar.c" /* yacc.c:1646 */
break;
case 73:
#line 1349 "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 2999 "grammar.c" /* yacc.c:1646 */
break;
case 74:
#line 1385 "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 3012 "grammar.c" /* yacc.c:1646 */
break;
case 75:
#line 1394 "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 3025 "grammar.c" /* yacc.c:1646 */
break;
case 76:
#line 1403 "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 3038 "grammar.c" /* yacc.c:1646 */
break;
case 77:
#line 1412 "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 3051 "grammar.c" /* yacc.c:1646 */
break;
case 78:
#line 1421 "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 3064 "grammar.c" /* yacc.c:1646 */
break;
case 79:
#line 1430 "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 3077 "grammar.c" /* yacc.c:1646 */
break;
case 80:
#line 1439 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3085 "grammar.c" /* yacc.c:1646 */
break;
case 81:
#line 1443 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3093 "grammar.c" /* yacc.c:1646 */
break;
case 82:
#line 1450 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_ENUMERATION; }
#line 3099 "grammar.c" /* yacc.c:1646 */
break;
case 83:
#line 1451 "grammar.y" /* yacc.c:1646 */
{ (yyval.integer) = INTEGER_SET_RANGE; }
#line 3105 "grammar.c" /* yacc.c:1646 */
break;
case 84:
#line 1457 "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 3127 "grammar.c" /* yacc.c:1646 */
break;
case 85:
#line 1479 "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 3143 "grammar.c" /* yacc.c:1646 */
break;
case 86:
#line 1491 "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 3158 "grammar.c" /* yacc.c:1646 */
break;
case 87:
#line 1506 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3167 "grammar.c" /* yacc.c:1646 */
break;
case 89:
#line 1512 "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 3178 "grammar.c" /* yacc.c:1646 */
break;
case 92:
#line 1529 "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 3189 "grammar.c" /* yacc.c:1646 */
break;
case 93:
#line 1536 "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 3200 "grammar.c" /* yacc.c:1646 */
break;
case 95:
#line 1548 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);
}
#line 3208 "grammar.c" /* yacc.c:1646 */
break;
case 96:
#line 1552 "grammar.y" /* yacc.c:1646 */
{
yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL);
}
#line 3216 "grammar.c" /* yacc.c:1646 */
break;
case 97:
#line 1560 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[-1].expression);
}
#line 3224 "grammar.c" /* yacc.c:1646 */
break;
case 98:
#line 1564 "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 3238 "grammar.c" /* yacc.c:1646 */
break;
case 99:
#line 1574 "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 3256 "grammar.c" /* yacc.c:1646 */
break;
case 100:
#line 1588 "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 3276 "grammar.c" /* yacc.c:1646 */
break;
case 101:
#line 1604 "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 3290 "grammar.c" /* yacc.c:1646 */
break;
case 102:
#line 1614 "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 3303 "grammar.c" /* yacc.c:1646 */
break;
case 103:
#line 1623 "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 3332 "grammar.c" /* yacc.c:1646 */
break;
case 104:
#line 1648 "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 3348 "grammar.c" /* yacc.c:1646 */
break;
case 105:
#line 1660 "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 3364 "grammar.c" /* yacc.c:1646 */
break;
case 106:
#line 1672 "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 3384 "grammar.c" /* yacc.c:1646 */
break;
case 107:
#line 1688 "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 3400 "grammar.c" /* yacc.c:1646 */
break;
case 108:
#line 1700 "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 3420 "grammar.c" /* yacc.c:1646 */
break;
case 109:
#line 1716 "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 3469 "grammar.c" /* yacc.c:1646 */
break;
case 110:
#line 1761 "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 3492 "grammar.c" /* yacc.c:1646 */
break;
case 111:
#line 1780 "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 3514 "grammar.c" /* yacc.c:1646 */
break;
case 112:
#line 1798 "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 3536 "grammar.c" /* yacc.c:1646 */
break;
case 113:
#line 1816 "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 3558 "grammar.c" /* yacc.c:1646 */
break;
case 114:
#line 1834 "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 3588 "grammar.c" /* yacc.c:1646 */
break;
case 115:
#line 1860 "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 3610 "grammar.c" /* yacc.c:1646 */
break;
case 116:
#line 1878 "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 3624 "grammar.c" /* yacc.c:1646 */
break;
case 117:
#line 1888 "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 3638 "grammar.c" /* yacc.c:1646 */
break;
case 118:
#line 1898 "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 3652 "grammar.c" /* yacc.c:1646 */
break;
case 119:
#line 1908 "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 3666 "grammar.c" /* yacc.c:1646 */
break;
case 120:
#line 1918 "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 3680 "grammar.c" /* yacc.c:1646 */
break;
case 121:
#line 1928 "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 3694 "grammar.c" /* yacc.c:1646 */
break;
case 122:
#line 1938 "grammar.y" /* yacc.c:1646 */
{
(yyval.expression) = (yyvsp[0].expression);
}
#line 3702 "grammar.c" /* yacc.c:1646 */
break;
#line 3706 "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;
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: libyara/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (heap-based out-of-bounds read and application crash) via a crafted rule that is mishandled in the yara_yyparse function.
Commit Message: Fix issue #597 | Medium | 168,374 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
const char *act;
#endif
gid_t gid, gl[65536], egid;
int pid = 0;
for (i = 1; i < argc; i++)
{
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
Vulnerability Type: +Priv
CWE ID: CWE-264
Summary: Enlightenment before 0.17.6 might allow local users to gain privileges via vectors involving the gdb method.
Commit Message: | Medium | 165,512 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void php_snmp_object_free_storage(void *object TSRMLS_DC)
{
php_snmp_object *intern = (php_snmp_object *)object;
if (!intern) {
return;
}
netsnmp_session_free(&(intern->session));
zend_object_std_dtor(&intern->zo TSRMLS_CC);
efree(intern);
}
Vulnerability Type: DoS
CWE ID: CWE-416
Summary: ext/snmp/snmp.c in PHP before 5.5.38, 5.6.x before 5.6.24, and 7.x before 7.0.9 improperly interacts with the unserialize implementation and garbage collection, which allows remote attackers to cause a denial of service (use-after-free and application crash) or possibly have unspecified other impact via crafted serialized data, a related issue to CVE-2016-5773.
Commit Message: | High | 164,977 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
Vulnerability Type: +Priv
CWE ID:
Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085.
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
| High | 173,685 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR("%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_remove_unpaired(config);
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR("%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
Vulnerability Type: +Priv
CWE ID: CWE-20
Summary: Bluetooth in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01 allows local users to gain privileges by establishing a pairing that remains present during a session of the primary user, aka internal bug 27410683.
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
| Medium | 173,553 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ShellWindowFrameView::OnPaint(gfx::Canvas* canvas) {
SkPaint paint;
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorWHITE);
gfx::Path path;
const int radius = 1;
path.moveTo(0, radius);
path.lineTo(radius, 0);
path.lineTo(width() - radius - 1, 0);
path.lineTo(width(), radius + 1);
path.lineTo(width(), kCaptionHeight);
path.lineTo(0, kCaptionHeight);
path.close();
canvas->DrawPath(path, paint);
}
Vulnerability Type: XSS
CWE ID: CWE-79
Summary: Cross-site scripting (XSS) vulnerability in Google Chrome before 22.0.1229.79 allows remote attackers to inject arbitrary web script or HTML via vectors involving frames, aka *Universal XSS (UXSS).*
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,717 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Incorrect handling of confusable characters in URL Formatter in Google Chrome prior to 71.0.3578.80 allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted domain name.
Commit Message: Block modifier-letter-voicing character from domain names
This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812.
Bug: 896717
Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e
Reviewed-on: https://chromium-review.googlesource.com/c/1303037
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604128} | Medium | 172,638 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim;j++)
a[i++]+=v[j];
}
}
return 0;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability in the Android media framework (n/a). Product: Android. Versions: 7.0, 7.1.1, 7.1.2, 8.0. Android ID: A-62800140.
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
| High | 173,986 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool Extension::HasAPIPermission(const std::string& function_name) const {
base::AutoLock auto_lock(runtime_data_lock_);
return runtime_data_.GetActivePermissions()->
HasAccessToFunction(function_name);
}
Vulnerability Type:
CWE ID: CWE-264
Summary: Google Chrome before 25.0.1364.97 on Windows and Linux, and before 25.0.1364.99 on Mac OS X, does not properly restrict API privileges during interaction with the Chrome Web Store, which has unspecified impact and attack vectors.
Commit Message: Tighten restrictions on hosted apps calling extension APIs
Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this).
BUG=172369
Review URL: https://chromiumcodereview.appspot.com/12095095
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,351 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2);
if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p = strchr(p + 1, *s2)) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
Vulnerability Type:
CWE ID:
Summary: Boa through 0.94.14rc21 allows remote attackers to trigger a memory leak because of missing calls to the free function.
Commit Message: misc oom and possible memory leak fix | Low | 169,755 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static ssize_t read_mem(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
phys_addr_t p = *ppos;
ssize_t read, sz;
void *ptr;
if (p != *ppos)
return 0;
if (!valid_phys_addr_range(p, count))
return -EFAULT;
read = 0;
#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
/* we don't have page 0 mapped on sparc and m68k.. */
if (p < PAGE_SIZE) {
sz = size_inside_page(p, count);
if (sz > 0) {
if (clear_user(buf, sz))
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
}
#endif
while (count > 0) {
unsigned long remaining;
sz = size_inside_page(p, count);
if (!range_is_allowed(p >> PAGE_SHIFT, count))
return -EPERM;
/*
* On ia64 if a page has been mapped somewhere as uncached, then
* it must also be accessed uncached by the kernel or data
* corruption may occur.
*/
ptr = xlate_dev_mem_ptr(p);
if (!ptr)
return -EFAULT;
remaining = copy_to_user(buf, ptr, sz);
unxlate_dev_mem_ptr(p, ptr);
if (remaining)
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
*ppos += read;
return read;
}
Vulnerability Type: Bypass
CWE ID: CWE-732
Summary: The mm subsystem in the Linux kernel through 4.10.10 does not properly enforce the CONFIG_STRICT_DEVMEM protection mechanism, which allows local users to read or write to kernel memory locations in the first megabyte (and bypass slab-allocation access restrictions) via an application that opens the /dev/mem file, related to arch/x86/mm/init.c and drivers/char/mem.c.
Commit Message: mm: Tighten x86 /dev/mem with zeroing reads
Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is
disallowed. However, on x86, the first 1MB was always allowed for BIOS
and similar things, regardless of it actually being System RAM. It was
possible for heap to end up getting allocated in low 1MB RAM, and then
read by things like x86info or dd, which would trip hardened usercopy:
usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes)
This changes the x86 exception for the low 1MB by reading back zeros for
System RAM areas instead of blindly allowing them. More work is needed to
extend this to mmap, but currently mmap doesn't go through usercopy, so
hardened usercopy won't Oops the kernel.
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Kees Cook <[email protected]> | High | 168,242 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
Vulnerability Type: Overflow +Priv
CWE ID: CWE-119
Summary: Buffer overflow in codecs/on2/dec/SoftVPX.cpp in libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-09-01, and 7.0 before 2016-09-01 allows attackers to gain privileges via a crafted application, aka internal bug 29421675.
Commit Message: fix build
Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b
| High | 173,414 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: cib_send_plaintext(int sock, xmlNode * msg)
{
char *xml_text = dump_xml_unformatted(msg);
if (xml_text != NULL) {
int rc = 0;
char *unsent = xml_text;
int len = strlen(xml_text);
len++; /* null char */
crm_trace("Message on socket %d: size=%d", sock, len);
retry:
rc = write(sock, unsent, len);
if (rc < 0) {
switch (errno) {
case EINTR:
case EAGAIN:
crm_trace("Retry");
goto retry;
default:
crm_perror(LOG_ERR, "Could only write %d of the remaining %d bytes", rc, len);
break;
}
} else if (rc < len) {
crm_trace("Only sent %d of %d remaining bytes", rc, len);
len -= rc;
unsent += rc;
goto retry;
} else {
crm_trace("Sent %d bytes: %.100s", rc, xml_text);
}
}
free(xml_text);
return NULL;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Pacemaker 1.1.10, when remote Cluster Information Base (CIB) configuration or resource management is enabled, does not limit the duration of connections to the blocking sockets, which allows remote attackers to cause a denial of service (connection blocking).
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. | Medium | 166,160 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
string->space = 1;
else
string->space *= 2;
if (string->space < 0)
{
g_warning ("glyph string length overflows maximum integer size, truncated");
new_len = string->space = G_MAXINT - 8;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-189
Summary: Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
Commit Message: [glyphstring] Handle overflow with very long glyphstrings | Medium | 165,514 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
WORD32 buf_size;
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
/* If dynamic bitstream buffer is not allocated and
* header decode is done, then allocate dynamic bitstream buffer
*/
if((NULL == ps_dec->pu1_bits_buf_dynamic) &&
(ps_dec->i4_header_decoded & 1))
{
WORD32 size;
void *pv_buf;
void *pv_mem_ctxt = ps_dec->pv_mem_ctxt;
size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2);
pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_dynamic = pv_buf;
ps_dec->u4_dynamic_bits_buf_size = size;
}
if(ps_dec->pu1_bits_buf_dynamic)
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic;
buf_size = ps_dec->u4_dynamic_bits_buf_size;
}
else
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static;
buf_size = ps_dec->u4_static_bits_buf_size;
}
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
buflen = MIN(buflen, buf_size);
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
/* Decoder may read extra 8 bytes near end of the frame */
if((buflen + 8) < buf_size)
{
memset(pu1_bitstrm_buf + buflen, 0, 8);
}
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& (ret != IVD_MEM_ALLOC_FAILED)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T))
{
return IV_FAIL;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
Vulnerability Type: DoS
CWE ID: CWE-172
Summary: decoder/ih264d_api.c in mediaserver in Android 6.x before 2016-08-01 mishandles invalid PPS and SPS NAL units, which allows remote attackers to cause a denial of service (device hang or reboot) via a crafted media file, aka internal bug 28835995.
Commit Message: Decoder: Do not conceal slices with invalid SPS/PPS
Bug: 28835995
| High | 173,516 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager,
const std::string& user_agent) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_, user_agent));
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
Vulnerability Type:
CWE ID: CWE-416
Summary: A use after free in PDFium in Google Chrome prior to 57.0.2987.98 for Mac, Windows, and Linux and 57.0.2987.108 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted PDF file.
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} | Medium | 172,416 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void SocketStream::CheckPrivacyMode() {
if (context_.get() && context_->network_delegate()) {
bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_,
url_);
privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled;
if (enable)
server_ssl_config_.channel_id_enabled = false;
}
}
Vulnerability Type: Exec Code
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 28.0.1500.71 allows remote servers to execute arbitrary code via crafted response traffic after a URL request.
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 | High | 171,251 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,
char *errbuf, int *err)
{
bpf_u_int32 magic_int;
size_t amt_read;
bpf_u_int32 total_length;
bpf_u_int32 byte_order_magic;
struct block_header *bhdrp;
struct section_header_block *shbp;
pcap_t *p;
int swapped = 0;
struct pcap_ng_sf *ps;
int status;
struct block_cursor cursor;
struct interface_description_block *idbp;
/*
* Assume no read errors.
*/
*err = 0;
/*
* Check whether the first 4 bytes of the file are the block
* type for a pcapng savefile.
*/
memcpy(&magic_int, magic, sizeof(magic_int));
if (magic_int != BT_SHB) {
/*
* XXX - check whether this looks like what the block
* type would be after being munged by mapping between
* UN*X and DOS/Windows text file format and, if it
* does, look for the byte-order magic number in
* the appropriate place and, if we find it, report
* this as possibly being a pcapng file transferred
* between UN*X and Windows in text file format?
*/
return (NULL); /* nope */
}
/*
* OK, they are. However, that's just \n\r\r\n, so it could,
* conceivably, be an ordinary text file.
*
* It could not, however, conceivably be any other type of
* capture file, so we can read the rest of the putative
* Section Header Block; put the block type in the common
* header, read the rest of the common header and the
* fixed-length portion of the SHB, and look for the byte-order
* magic value.
*/
amt_read = fread(&total_length, 1, sizeof(total_length), fp);
if (amt_read < sizeof(total_length)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
if (amt_read < sizeof(byte_order_magic)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
if (byte_order_magic != BYTE_ORDER_MAGIC) {
byte_order_magic = SWAPLONG(byte_order_magic);
if (byte_order_magic != BYTE_ORDER_MAGIC) {
/*
* Not a pcapng file.
*/
return (NULL);
}
swapped = 1;
total_length = SWAPLONG(total_length);
}
/*
* Check the sanity of the total length.
*/
if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Section Header Block in pcapng dump file has a length of %u < %" PRIsize,
total_length,
sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer));
*err = 1;
return (NULL);
}
/*
* Make sure it's not too big.
*/
if (total_length > INITIAL_MAX_BLOCKSIZE) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"pcapng block size %u > maximum %u",
total_length, INITIAL_MAX_BLOCKSIZE);
*err = 1;
return (NULL);
}
/*
* OK, this is a good pcapng file.
* Allocate a pcap_t for it.
*/
p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
if (p == NULL) {
/* Allocation failed. */
*err = 1;
return (NULL);
}
p->swapped = swapped;
ps = p->priv;
/*
* What precision does the user want?
*/
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
ps->user_tsresol = 1000000;
break;
case PCAP_TSTAMP_PRECISION_NANO:
ps->user_tsresol = 1000000000;
break;
default:
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unknown time stamp resolution %u", precision);
free(p);
*err = 1;
return (NULL);
}
p->opt.tstamp_precision = precision;
/*
* Allocate a buffer into which to read blocks. We default to
* the maximum of:
*
* the total length of the SHB for which we read the header;
*
* 2K, which should be more than large enough for an Enhanced
* Packet Block containing a full-size Ethernet frame, and
* leaving room for some options.
*
* If we find a bigger block, we reallocate the buffer, up to
* the maximum size. We start out with a maximum size of
* INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types
* with a maximum snapshot that results in a larger maximum
* block length, we boost the maximum.
*/
p->bufsize = 2048;
if (p->bufsize < total_length)
p->bufsize = total_length;
p->buffer = malloc(p->bufsize);
if (p->buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
free(p);
*err = 1;
return (NULL);
}
ps->max_blocksize = INITIAL_MAX_BLOCKSIZE;
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the SHB.
*/
bhdrp = (struct block_header *)p->buffer;
shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header));
bhdrp->block_type = magic_int;
bhdrp->total_length = total_length;
shbp->byte_order_magic = byte_order_magic;
if (read_bytes(fp,
(u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
1, errbuf) == -1)
goto fail;
if (p->swapped) {
/*
* Byte-swap the fields we've read.
*/
shbp->major_version = SWAPSHORT(shbp->major_version);
shbp->minor_version = SWAPSHORT(shbp->minor_version);
/*
* XXX - we don't care about the section length.
*/
}
/* currently only SHB version 1.0 is supported */
if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR &&
shbp->minor_version == PCAP_NG_VERSION_MINOR)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unsupported pcapng savefile version %u.%u",
shbp->major_version, shbp->minor_version);
goto fail;
}
p->version_major = shbp->major_version;
p->version_minor = shbp->minor_version;
/*
* Save the time stamp resolution the user requested.
*/
p->opt.tstamp_precision = precision;
/*
* Now start looking for an Interface Description Block.
*/
for (;;) {
/*
* Read the next block.
*/
status = read_block(fp, p, &cursor, errbuf);
if (status == 0) {
/* EOF - no IDB in this file */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has no Interface Description Blocks");
goto fail;
}
if (status == -1)
goto fail; /* error */
switch (cursor.block_type) {
case BT_IDB:
/*
* Get a pointer to the fixed-length portion of the
* IDB.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
errbuf);
if (idbp == NULL)
goto fail; /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, errbuf))
goto fail;
goto done;
case BT_EPB:
case BT_SPB:
case BT_PB:
/*
* Saw a packet before we saw any IDBs. That's
* not valid, as we don't know what link-layer
* encapsulation the packet has.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has a packet block before any Interface Description Blocks");
goto fail;
default:
/*
* Just ignore it.
*/
break;
}
}
done:
p->tzoff = 0; /* XXX - not used in pcap */
p->linktype = linktype_to_dlt(idbp->linktype);
p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen);
p->linktype_ext = 0;
/*
* If the maximum block size for a packet with the maximum
* snapshot length for this DLT_ is bigger than the current
* maximum block size, increase the maximum.
*/
if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize)
ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype));
p->next_packet_op = pcap_ng_next_packet;
p->cleanup_op = pcap_ng_cleanup;
return (p);
fail:
free(ps->ifaces);
free(p->buffer);
free(p);
*err = 1;
return (NULL);
}
Vulnerability Type:
CWE ID: CWE-20
Summary: sf-pcapng.c in libpcap before 1.9.1 does not properly validate the PHB header length before allocating memory.
Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error | Medium | 170,187 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CheckOverflowException(length,width,height) \
(((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))
char
*comment;
Image
*image;
int
x_status;
MagickBooleanType
authentic_colormap;
MagickStatusType
status;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register size_t
pixel;
size_t
length;
ssize_t
count,
y;
unsigned long
lsb_first;
XColor
*colors;
XImage
*ximage;
XWDFileHeader
header;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read in header information.
*/
count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);
if (count != sz_XWDheader)
ThrowReaderException(CorruptImageError,"UnableToReadImageHeader");
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
MSBOrderLong((unsigned char *) &header,sz_XWDheader);
/*
Check to see if the dump file is in the proper format.
*/
if (header.file_version != XWD_FILE_VERSION)
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
if (header.header_size < sz_XWDheader)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.visual_class)
{
case StaticGray:
case GrayScale:
{
if (header.bits_per_pixel != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case StaticColor:
case PseudoColor:
{
if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) ||
(header.ncolors == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case TrueColor:
case DirectColor:
{
if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) &&
(header.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.pixmap_format)
{
case XYBitmap:
{
if (header.pixmap_depth != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case XYPixmap:
case ZPixmap:
{
if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.bitmap_pad)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_unit)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.byte_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_bit_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (header.ncolors > 65535)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
length=(size_t) (header.header_size-sz_XWDheader);
comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length,(unsigned char *) comment);
comment[length]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/*
Initialize the X image.
*/
ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));
if (ximage == (XImage *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ximage->depth=(int) header.pixmap_depth;
ximage->format=(int) header.pixmap_format;
ximage->xoffset=(int) header.xoffset;
ximage->data=(char *) NULL;
ximage->width=(int) header.pixmap_width;
ximage->height=(int) header.pixmap_height;
ximage->bitmap_pad=(int) header.bitmap_pad;
ximage->bytes_per_line=(int) header.bytes_per_line;
ximage->byte_order=(int) header.byte_order;
ximage->bitmap_unit=(int) header.bitmap_unit;
ximage->bitmap_bit_order=(int) header.bitmap_bit_order;
ximage->bits_per_pixel=(int) header.bits_per_pixel;
ximage->red_mask=header.red_mask;
ximage->green_mask=header.green_mask;
ximage->blue_mask=header.blue_mask;
if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) ||
(ximage->format < 0) || (ximage->byte_order < 0) ||
(ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||
(ximage->bytes_per_line < 0))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->width > 65535) || (ximage->height > 65535))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
x_status=XInitImage(ximage);
if (x_status == 0)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
/*
Read colormap.
*/
authentic_colormap=MagickFalse;
colors=(XColor *) NULL;
if (header.ncolors != 0)
{
XWDColor
color;
colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors,
sizeof(*colors));
if (colors == (XColor *) NULL)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) header.ncolors; i++)
{
count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);
if (count != sz_XWDColor)
{
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
colors[i].pixel=color.pixel;
colors[i].red=color.red;
colors[i].green=color.green;
colors[i].blue=color.blue;
colors[i].flags=(char) color.flags;
if (color.flags != 0)
authentic_colormap=MagickTrue;
}
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
for (i=0; i < (ssize_t) header.ncolors; i++)
{
MSBOrderLong((unsigned char *) &colors[i].pixel,
sizeof(colors[i].pixel));
MSBOrderShort((unsigned char *) &colors[i].red,3*
sizeof(colors[i].red));
}
}
/*
Allocate the pixel buffer.
*/
length=(size_t) ximage->bytes_per_line*ximage->height;
if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (ximage->format != ZPixmap)
{
size_t
extent;
extent=length;
length*=ximage->depth;
if (CheckOverflowException(length,extent,ximage->depth))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));
if (ximage->data == (char *) NULL)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,length,(unsigned char *) ximage->data);
if (count != (ssize_t) length)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
/*
Convert image to MIFF format.
*/
image->columns=(size_t) ximage->width;
image->rows=(size_t) ximage->height;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
return(DestroyImageList(image));
}
if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||
(ximage->green_mask != 0) || (ximage->blue_mask != 0))
image->storage_class=DirectClass;
else
image->storage_class=PseudoClass;
image->colors=header.ncolors;
if (image_info->ping == MagickFalse)
switch (image->storage_class)
{
case DirectClass:
default:
{
register size_t
color;
size_t
blue_mask,
blue_shift,
green_mask,
green_shift,
red_mask,
red_shift;
/*
Determine shift and mask for red, green, and blue.
*/
red_mask=ximage->red_mask;
red_shift=0;
while ((red_mask != 0) && ((red_mask & 0x01) == 0))
{
red_mask>>=1;
red_shift++;
}
green_mask=ximage->green_mask;
green_shift=0;
while ((green_mask != 0) && ((green_mask & 0x01) == 0))
{
green_mask>>=1;
green_shift++;
}
blue_mask=ximage->blue_mask;
blue_shift=0;
while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))
{
blue_mask>>=1;
blue_shift++;
}
/*
Convert X image to DirectClass packets.
*/
if ((image->colors != 0) && (authentic_colormap != MagickFalse))
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
red_shift) & red_mask,exception);
SetPixelRed(image,ScaleShortToQuantum(
colors[(ssize_t) index].red),q);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
green_shift) & green_mask,exception);
SetPixelGreen(image,ScaleShortToQuantum(
colors[(ssize_t) index].green),q);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
blue_shift) & blue_mask,exception);
SetPixelBlue(image,ScaleShortToQuantum(
colors[(ssize_t) index].blue),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
color=(pixel >> red_shift) & red_mask;
if (red_mask != 0)
color=(color*65535UL)/red_mask;
SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q);
color=(pixel >> green_shift) & green_mask;
if (green_mask != 0)
color=(color*65535UL)/green_mask;
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color),
q);
color=(pixel >> blue_shift) & blue_mask;
if (blue_mask != 0)
color=(color*65535UL)/blue_mask;
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
case PseudoClass:
{
/*
Convert X image to PseudoClass packets.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType) ScaleShortToQuantum(
colors[i].red);
image->colormap[i].green=(MagickRealType) ScaleShortToQuantum(
colors[i].green);
image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum(
colors[i].blue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=(Quantum) ConstrainColormapIndex(image,(ssize_t)
XGetPixel(ximage,(int) x,(int) y),exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
}
/*
Free image and colormap.
*/
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The XWD image (X Window System window dumping file) parsing component in ImageMagick 7.0.8-41 Q16 allows attackers to cause a denial-of-service (application crash resulting from an out-of-bounds Read) in ReadXWDImage in coders/xwd.c by crafting a corrupted XWD image file, a different vulnerability than CVE-2019-11472.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1553 | Medium | 169,556 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: RunLoop::RunLoop()
: delegate_(tls_delegate.Get().Get()),
origin_task_runner_(ThreadTaskRunnerHandle::Get()),
weak_factory_(this) {
DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
"to using RunLoop.";
DCHECK(origin_task_runner_);
}
Vulnerability Type: DoS
CWE ID:
Summary: Use-after-free vulnerability in the SkMatrix::invertNonIdentity function in core/SkMatrix.cpp in Skia, as used in Google Chrome before 45.0.2454.85, allows remote attackers to cause a denial of service or possibly have unspecified other impact by triggering the use of matrix elements that lead to an infinite result during an inversion calculation.
Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower.
(as well as MessageLoop::SetNestableTasksAllowed())
Surveying usage: the scoped object is always instantiated right before
RunLoop().Run(). The intent is really to allow nestable tasks in that
RunLoop so it's better to explicitly label that RunLoop as such and it
allows us to break the last dependency that forced some RunLoop users
to use MessageLoop APIs.
There's also the odd case of allowing nestable tasks for loops that are
reentrant from a native task (without going through RunLoop), these
are the minority but will have to be handled (after cleaning up the
majority of cases that are RunLoop induced).
As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517
(which was merged in this CL).
[email protected]
Bug: 750779
Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448
Reviewed-on: https://chromium-review.googlesource.com/594713
Commit-Queue: Gabriel Charette <[email protected]>
Reviewed-by: Robert Liao <[email protected]>
Reviewed-by: danakj <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492263} | High | 171,869 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ipt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ipt_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 && unconditional(&e->ip)) ||
visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ipt_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ipt_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ipt_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ipt_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
Vulnerability Type: DoS Overflow +Priv Mem. Corr.
CWE ID: CWE-119
Summary: The netfilter subsystem in the Linux kernel through 4.5.2 does not validate certain offset fields, which allows local users to gain privileges or cause a denial of service (heap memory corruption) via an IPT_SO_SET_REPLACE setsockopt call.
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]> | High | 167,370 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: userauth_gssapi(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
gss_OID_desc goid = {0, NULL};
Gssctxt *ctxt = NULL;
int r, present;
u_int mechs;
OM_uint32 ms;
size_t len;
u_char *doid = NULL;
if (!authctxt->valid || authctxt->user == NULL)
return (0);
if ((r = sshpkt_get_u32(ssh, &mechs)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (mechs == 0) {
debug("Mechanism negotiation is not supported");
return (0);
}
do {
mechs--;
free(doid);
present = 0;
if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (len > 2 && doid[0] == SSH_GSS_OIDTYPE &&
doid[1] == len - 2) {
goid.elements = doid + 2;
goid.length = len - 2;
ssh_gssapi_test_oid_supported(&ms, &goid, &present);
} else {
logit("Badly formed OID received");
}
} while (mechs > 0 && !present);
if (!present) {
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) {
if (ctxt != NULL)
ssh_gssapi_delete_ctx(&ctxt);
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
authctxt->methoddata = (void *)ctxt;
/* Return the OID that we received */
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 ||
(r = sshpkt_put_string(ssh, doid, len)) != 0 ||
(r = sshpkt_send(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
free(doid);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
authctxt->postponed = 1;
return (0);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: OpenSSH through 7.7 is prone to a user enumeration vulnerability due to not delaying bailout for an invalid authenticating user until after the packet containing the request has been fully parsed, related to auth2-gss.c, auth2-hostbased.c, and auth2-pubkey.c.
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt | Medium | 169,104 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int __init acpi_custom_method_init(void)
{
if (!acpi_debugfs_dir)
return -ENOENT;
cm_dentry = debugfs_create_file("custom_method", S_IWUSR,
acpi_debugfs_dir, NULL, &cm_fops);
if (!cm_dentry)
return -ENODEV;
return 0;
}
Vulnerability Type:
CWE ID: CWE-264
Summary: drivers/acpi/debugfs.c in the Linux kernel before 3.0 allows local users to modify arbitrary kernel memory locations by leveraging root privileges to write to the /sys/kernel/debug/acpi/custom_method file. NOTE: this vulnerability exists because of an incomplete fix for CVE-2010-4347.
Commit Message: ACPI: Split out custom_method functionality into an own driver
With /sys/kernel/debug/acpi/custom_method root can write
to arbitrary memory and increase his priveleges, even if
these are restricted.
-> Make this an own debug .config option and warn about the
security issue in the config description.
-> Still keep acpi/debugfs.c which now only creates an empty
/sys/kernel/debug/acpi directory. There might be other
users of it later.
Signed-off-by: Thomas Renninger <[email protected]>
Acked-by: Rafael J. Wysocki <[email protected]>
Acked-by: [email protected]
Signed-off-by: Len Brown <[email protected]> | Low | 165,901 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: _TIFFmalloc(tmsize_t s)
{
return (malloc((size_t) s));
}
Vulnerability Type: DoS
CWE ID: CWE-369
Summary: The _TIFFmalloc function in tif_unix.c in LibTIFF 4.0.3 does not reject a zero size, which allows remote attackers to cause a denial of service (divide-by-zero error and application crash) via a crafted TIFF image that is mishandled by the TIFFWriteScanline function in tif_write.c, as demonstrated by tiffdither.
Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not
require malloc() to return NULL pointer if requested allocation
size is zero. Assure that _TIFFmalloc does. | Medium | 169,459 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
return touchpad_lib_.GetDefaultImpl(use_stub_impl_);
}
Vulnerability Type: Exec Code
CWE ID: CWE-189
Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error.
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 | High | 170,633 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool NavigationControllerImpl::RendererDidNavigate(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
LoadCommittedDetails* details,
bool is_navigation_within_page,
NavigationHandleImpl* navigation_handle) {
is_initial_navigation_ = false;
bool overriding_user_agent_changed = false;
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->GetURL();
details->previous_entry_index = GetLastCommittedEntryIndex();
if (pending_entry_ &&
pending_entry_->GetIsOverridingUserAgent() !=
GetLastCommittedEntry()->GetIsOverridingUserAgent())
overriding_user_agent_changed = true;
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
bool was_restored = false;
DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
pending_entry_->restore_type() != RestoreType::NONE);
if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) {
pending_entry_->set_restore_type(RestoreType::NONE);
was_restored = true;
}
details->did_replace_entry = params.should_replace_current_entry;
details->type = ClassifyNavigation(rfh, params);
details->is_same_document = is_navigation_within_page;
if (PendingEntryMatchesHandle(navigation_handle)) {
if (pending_entry_->reload_type() != ReloadType::NONE) {
last_committed_reload_type_ = pending_entry_->reload_type();
last_committed_reload_time_ =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
} else if (!pending_entry_->is_renderer_initiated() ||
params.gesture == NavigationGestureUser) {
last_committed_reload_type_ = ReloadType::NONE;
last_committed_reload_time_ = base::Time();
}
}
switch (details->type) {
case NAVIGATION_TYPE_NEW_PAGE:
RendererDidNavigateToNewPage(rfh, params, details->is_same_document,
details->did_replace_entry,
navigation_handle);
break;
case NAVIGATION_TYPE_EXISTING_PAGE:
details->did_replace_entry = details->is_same_document;
RendererDidNavigateToExistingPage(rfh, params, details->is_same_document,
was_restored, navigation_handle);
break;
case NAVIGATION_TYPE_SAME_PAGE:
RendererDidNavigateToSamePage(rfh, params, navigation_handle);
break;
case NAVIGATION_TYPE_NEW_SUBFRAME:
RendererDidNavigateNewSubframe(rfh, params, details->is_same_document,
details->did_replace_entry);
break;
case NAVIGATION_TYPE_AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(rfh, params)) {
NotifyEntryChanged(GetLastCommittedEntry());
return false;
}
break;
case NAVIGATION_TYPE_NAV_IGNORE:
if (pending_entry_) {
DiscardNonCommittedEntries();
delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
return false;
default:
NOTREACHED();
}
base::Time timestamp =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DVLOG(1) << "Navigation finished at (smoothed) timestamp "
<< timestamp.ToInternalValue();
DiscardNonCommittedEntriesInternal();
DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
NavigationEntryImpl* active_entry = GetLastCommittedEntry();
active_entry->SetTimestamp(timestamp);
active_entry->SetHttpStatusCode(params.http_status_code);
FrameNavigationEntry* frame_entry =
active_entry->GetFrameEntry(rfh->frame_tree_node());
if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
frame_entry = nullptr;
if (frame_entry) {
DCHECK(params.page_state == frame_entry->page_state());
}
if (!rfh->GetParent() &&
IsBlockedNavigation(navigation_handle->GetNetErrorCode())) {
DCHECK(params.url_is_unreachable);
active_entry->SetURL(GURL(url::kAboutBlankURL));
active_entry->SetVirtualURL(params.url);
if (frame_entry) {
frame_entry->SetPageState(
PageState::CreateFromURL(active_entry->GetURL()));
}
}
size_t redirect_chain_size = 0;
for (size_t i = 0; i < params.redirects.size(); ++i) {
redirect_chain_size += params.redirects[i].spec().length();
}
UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
active_entry->ResetForCommit(frame_entry);
if (!rfh->GetParent())
CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
active_entry->SetBindings(rfh->GetEnabledBindings());
details->entry = active_entry;
details->is_main_frame = !rfh->GetParent();
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details);
if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
navigation_handle->GetNetErrorCode() == net::OK) {
UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus",
!!active_entry->GetSSL().certificate);
}
if (overriding_user_agent_changed)
delegate_->UpdateOverridingUserAgent();
int nav_entry_id = active_entry->GetUniqueID();
for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes())
node->current_frame_host()->set_nav_entry_id(nav_entry_id);
return true;
}
Vulnerability Type:
CWE ID: CWE-20
Summary: Incorrect handling of back navigations in error pages in Navigation in Google Chrome prior to 63.0.3239.84 allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted HTML page.
Commit Message: Do not use NavigationEntry to block history navigations.
This is no longer necessary after r477371.
BUG=777419
TEST=See bug for repro steps.
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18
Reviewed-on: https://chromium-review.googlesource.com/733959
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511942} | Medium | 172,932 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess,
struct tee_ta_session *called_sess,
struct utee_params *callee_params,
struct tee_ta_param *param,
void *tmp_buf_va[TEE_NUM_PARAMS],
struct mobj **mobj_tmp)
{
size_t n;
TEE_Result res;
size_t req_mem = 0;
size_t s;
uint8_t *dst = 0;
bool ta_private_memref[TEE_NUM_PARAMS];
struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
void *va;
size_t dst_offs;
/* fill 'param' input struct with caller params description buffer */
if (!callee_params) {
memset(param, 0, sizeof(*param));
} else {
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)callee_params, sizeof(struct utee_params));
if (res != TEE_SUCCESS)
return res;
utee_param_to_param(param, callee_params);
}
if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) {
/* pseudo TA borrows the mapping of the calling TA */
return TEE_SUCCESS;
}
/* All mobj in param are of type MOJB_TYPE_VIRT */
for (n = 0; n < TEE_NUM_PARAMS; n++) {
ta_private_memref[n] = false;
switch (TEE_PARAM_TYPE_GET(param->types, n)) {
case TEE_PARAM_TYPE_MEMREF_INPUT:
case TEE_PARAM_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_TYPE_MEMREF_INOUT:
va = (void *)param->u[n].mem.offs;
s = param->u[n].mem.size;
if (!va) {
if (s)
return TEE_ERROR_BAD_PARAMETERS;
break;
}
/* uTA cannot expose its private memory */
if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) {
s = ROUNDUP(s, sizeof(uint32_t));
if (ADD_OVERFLOW(req_mem, s, &req_mem))
return TEE_ERROR_BAD_PARAMETERS;
ta_private_memref[n] = true;
break;
}
res = tee_mmu_vbuf_to_mobj_offs(utc, va, s,
¶m->u[n].mem.mobj,
¶m->u[n].mem.offs);
if (res != TEE_SUCCESS)
return res;
break;
default:
break;
}
}
if (req_mem == 0)
return TEE_SUCCESS;
res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst);
if (res != TEE_SUCCESS)
return res;
dst_offs = 0;
for (n = 0; n < TEE_NUM_PARAMS; n++) {
if (!ta_private_memref[n])
continue;
s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t));
switch (TEE_PARAM_TYPE_GET(param->types, n)) {
case TEE_PARAM_TYPE_MEMREF_INPUT:
case TEE_PARAM_TYPE_MEMREF_INOUT:
va = (void *)param->u[n].mem.offs;
if (va) {
res = tee_svc_copy_from_user(dst, va,
param->u[n].mem.size);
if (res != TEE_SUCCESS)
return res;
param->u[n].mem.offs = dst_offs;
param->u[n].mem.mobj = *mobj_tmp;
tmp_buf_va[n] = dst;
dst += s;
dst_offs += s;
}
break;
case TEE_PARAM_TYPE_MEMREF_OUTPUT:
va = (void *)param->u[n].mem.offs;
if (va) {
param->u[n].mem.offs = dst_offs;
param->u[n].mem.mobj = *mobj_tmp;
tmp_buf_va[n] = dst;
dst += s;
dst_offs += s;
}
break;
default:
continue;
}
}
return TEE_SUCCESS;
}
Vulnerability Type: Overflow Mem. Corr.
CWE ID: CWE-119
Summary: Linaro/OP-TEE OP-TEE 3.3.0 and earlier is affected by: Buffer Overflow. The impact is: Memory corruption and disclosure of memory content. The component is: optee_os. The fixed version is: 3.4.0 and later.
Commit Message: core: svc: always check ta parameters
Always check TA parameters from a user TA. This prevents a user TA from
passing invalid pointers to a pseudo TA.
Fixes: OP-TEE-2018-0007: "Buffer checks missing when calling pseudo
TAs".
Signed-off-by: Jens Wiklander <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Joakim Bech <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]> | High | 169,470 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void _isdn_setup(struct net_device *dev)
{
isdn_net_local *lp = netdev_priv(dev);
ether_setup(dev);
/* Setup the generic properties */
dev->flags = IFF_NOARP|IFF_POINTOPOINT;
dev->header_ops = NULL;
dev->netdev_ops = &isdn_netdev_ops;
/* for clients with MPPP maybe higher values better */
dev->tx_queue_len = 30;
lp->p_encap = ISDN_NET_ENCAP_RAWIP;
lp->magic = ISDN_NET_MAGIC;
lp->last = lp;
lp->next = lp;
lp->isdn_device = -1;
lp->isdn_channel = -1;
lp->pre_device = -1;
lp->pre_channel = -1;
lp->exclusive = -1;
lp->ppp_slot = -1;
lp->pppbind = -1;
skb_queue_head_init(&lp->super_tx_queue);
lp->l2_proto = ISDN_PROTO_L2_X75I;
lp->l3_proto = ISDN_PROTO_L3_TRANS;
lp->triggercps = 6000;
lp->slavedelay = 10 * HZ;
lp->hupflags = ISDN_INHUP; /* Do hangup even on incoming calls */
lp->onhtime = 10; /* Default hangup-time for saving costs */
lp->dialmax = 1;
/* Hangup before Callback, manual dial */
lp->flags = ISDN_NET_CBHUP | ISDN_NET_DM_MANUAL;
lp->cbdelay = 25; /* Wait 5 secs before Callback */
lp->dialtimeout = -1; /* Infinite Dial-Timeout */
lp->dialwait = 5 * HZ; /* Wait 5 sec. after failed dial */
lp->dialstarted = 0; /* Jiffies of last dial-start */
lp->dialwait_timer = 0; /* Jiffies of earliest next dial-start */
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: The net subsystem in the Linux kernel before 3.1 does not properly restrict use of the IFF_TX_SKB_SHARING flag, which allows local users to cause a denial of service (panic) by leveraging the CAP_NET_ADMIN capability to access /proc/net/pktgen/pgctrl, and then using the pktgen package in conjunction with a bridge device for a VLAN interface.
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Medium | 165,725 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static char* cJSON_strdup( const char* str )
{
size_t len;
char* copy;
len = strlen( str ) + 1;
if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
return 0;
memcpy( copy, str, len );
return copy;
}
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-119
Summary: The parse_string function in cjson.c in the cJSON library mishandles UTF8/16 strings, which allows remote attackers to cause a denial of service (crash) or execute arbitrary code via a non-hex character in a JSON string, which triggers a heap-based buffer overflow.
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]> | High | 167,298 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: int sandbox(void* sandbox_arg) {
(void)sandbox_arg;
pid_t child_pid = getpid();
if (arg_debug)
printf("Initializing child process\n");
close(parent_to_child_fds[1]);
close(child_to_parent_fds[0]);
wait_for_other(parent_to_child_fds[0]);
if (arg_debug && child_pid == 1)
printf("PID namespace installed\n");
if (cfg.hostname) {
if (sethostname(cfg.hostname, strlen(cfg.hostname)) < 0)
errExit("sethostname");
}
if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
chk_chroot();
}
preproc_mount_mnt_dir();
if (mount(LIBDIR "/firejail", RUN_FIREJAIL_LIB_DIR, "none", MS_BIND, NULL) < 0)
errExit("mounting " RUN_FIREJAIL_LIB_DIR);
if (cfg.name)
fs_logger2("sandbox name:", cfg.name);
fs_logger2int("sandbox pid:", (int) sandbox_pid);
if (cfg.chrootdir)
fs_logger("sandbox filesystem: chroot");
else if (arg_overlay)
fs_logger("sandbox filesystem: overlay");
else
fs_logger("sandbox filesystem: local");
fs_logger("install mount namespace");
if (arg_netfilter && any_bridge_configured()) { // assuming by default the client filter
netfilter(arg_netfilter_file);
}
if (arg_netfilter6 && any_bridge_configured()) { // assuming by default the client filter
netfilter6(arg_netfilter6_file);
}
int gw_cfg_failed = 0; // default gw configuration flag
if (arg_nonetwork) {
net_if_up("lo");
if (arg_debug)
printf("Network namespace enabled, only loopback interface available\n");
}
else if (arg_netns) {
netns(arg_netns);
if (arg_debug)
printf("Network namespace '%s' activated\n", arg_netns);
}
else if (any_bridge_configured() || any_interface_configured()) {
net_if_up("lo");
if (mac_not_zero(cfg.bridge0.macsandbox))
net_config_mac(cfg.bridge0.devsandbox, cfg.bridge0.macsandbox);
sandbox_if_up(&cfg.bridge0);
if (mac_not_zero(cfg.bridge1.macsandbox))
net_config_mac(cfg.bridge1.devsandbox, cfg.bridge1.macsandbox);
sandbox_if_up(&cfg.bridge1);
if (mac_not_zero(cfg.bridge2.macsandbox))
net_config_mac(cfg.bridge2.devsandbox, cfg.bridge2.macsandbox);
sandbox_if_up(&cfg.bridge2);
if (mac_not_zero(cfg.bridge3.macsandbox))
net_config_mac(cfg.bridge3.devsandbox, cfg.bridge3.macsandbox);
sandbox_if_up(&cfg.bridge3);
if (cfg.interface0.configured && cfg.interface0.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface0.ip), cfg.interface0.dev);
net_config_interface(cfg.interface0.dev, cfg.interface0.ip, cfg.interface0.mask, cfg.interface0.mtu);
}
if (cfg.interface1.configured && cfg.interface1.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface1.ip), cfg.interface1.dev);
net_config_interface(cfg.interface1.dev, cfg.interface1.ip, cfg.interface1.mask, cfg.interface1.mtu);
}
if (cfg.interface2.configured && cfg.interface2.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface2.ip), cfg.interface2.dev);
net_config_interface(cfg.interface2.dev, cfg.interface2.ip, cfg.interface2.mask, cfg.interface2.mtu);
}
if (cfg.interface3.configured && cfg.interface3.ip) {
if (arg_debug)
printf("Configuring %d.%d.%d.%d address on interface %s\n", PRINT_IP(cfg.interface3.ip), cfg.interface3.dev);
net_config_interface(cfg.interface3.dev, cfg.interface3.ip, cfg.interface3.mask, cfg.interface3.mtu);
}
if (cfg.defaultgw) {
if (net_add_route(0, 0, cfg.defaultgw)) {
fwarning("cannot configure default route\n");
gw_cfg_failed = 1;
}
}
if (arg_debug)
printf("Network namespace enabled\n");
}
if (!arg_quiet) {
if (any_bridge_configured() || any_interface_configured() || cfg.defaultgw || cfg.dns1) {
fmessage("\n");
if (any_bridge_configured() || any_interface_configured()) {
if (arg_scan)
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 3, PATH_FNET, "printif", "scan");
else
sbox_run(SBOX_ROOT | SBOX_CAPS_NETWORK | SBOX_SECCOMP, 2, PATH_FNET, "printif");
}
if (cfg.defaultgw != 0) {
if (gw_cfg_failed)
fmessage("Default gateway configuration failed\n");
else
fmessage("Default gateway %d.%d.%d.%d\n", PRINT_IP(cfg.defaultgw));
}
if (cfg.dns1 != NULL)
fmessage("DNS server %s\n", cfg.dns1);
if (cfg.dns2 != NULL)
fmessage("DNS server %s\n", cfg.dns2);
if (cfg.dns3 != NULL)
fmessage("DNS server %s\n", cfg.dns3);
if (cfg.dns4 != NULL)
fmessage("DNS server %s\n", cfg.dns4);
fmessage("\n");
}
}
if (arg_nonetwork || any_bridge_configured() || any_interface_configured()) {
}
else {
EUID_USER();
env_ibus_load();
EUID_ROOT();
}
#ifdef HAVE_SECCOMP
if (cfg.protocol) {
if (arg_debug)
printf("Build protocol filter: %s\n", cfg.protocol);
int rv = sbox_run(SBOX_USER | SBOX_CAPS_NONE | SBOX_SECCOMP, 5,
PATH_FSECCOMP, "protocol", "build", cfg.protocol, RUN_SECCOMP_PROTOCOL);
if (rv)
exit(rv);
}
if (arg_seccomp && (cfg.seccomp_list || cfg.seccomp_list_drop || cfg.seccomp_list_keep))
arg_seccomp_postexec = 1;
#endif
bool need_preload = arg_trace || arg_tracelog || arg_seccomp_postexec;
if (getuid() != 0 && (arg_appimage || cfg.chrootdir || arg_overlay)) {
enforce_filters();
need_preload = arg_trace || arg_tracelog;
}
if (need_preload)
fs_trace_preload();
if (cfg.hosts_file)
fs_store_hosts_file();
#ifdef HAVE_CHROOT
if (cfg.chrootdir) {
fs_chroot(cfg.chrootdir);
if (need_preload)
fs_trace_preload();
}
else
#endif
#ifdef HAVE_OVERLAYFS
if (arg_overlay)
fs_overlayfs();
else
#endif
fs_basic_fs();
if (arg_private) {
if (cfg.home_private) { // --private=
if (cfg.chrootdir)
fwarning("private=directory feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private=directory feature is disabled in overlay\n");
else
fs_private_homedir();
}
else if (cfg.home_private_keep) { // --private-home=
if (cfg.chrootdir)
fwarning("private-home= feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-home= feature is disabled in overlay\n");
else
fs_private_home_list();
}
else // --private
fs_private();
}
if (arg_private_dev)
fs_private_dev();
if (arg_private_etc) {
if (cfg.chrootdir)
fwarning("private-etc feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-etc feature is disabled in overlay\n");
else {
fs_private_dir_list("/etc", RUN_ETC_DIR, cfg.etc_private_keep);
if (need_preload)
fs_trace_preload();
}
}
if (arg_private_opt) {
if (cfg.chrootdir)
fwarning("private-opt feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-opt feature is disabled in overlay\n");
else {
fs_private_dir_list("/opt", RUN_OPT_DIR, cfg.opt_private_keep);
}
}
if (arg_private_srv) {
if (cfg.chrootdir)
fwarning("private-srv feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-srv feature is disabled in overlay\n");
else {
fs_private_dir_list("/srv", RUN_SRV_DIR, cfg.srv_private_keep);
}
}
if (arg_private_bin && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-bin feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-bin feature is disabled in overlay\n");
else {
if (arg_x11_xorg) {
EUID_USER();
char *tmp;
if (asprintf(&tmp, "%s,xauth", cfg.bin_private_keep) == -1)
errExit("asprintf");
cfg.bin_private_keep = tmp;
EUID_ROOT();
}
fs_private_bin_list();
}
}
if (arg_private_lib && !arg_appimage) {
if (cfg.chrootdir)
fwarning("private-lib feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-lib feature is disabled in overlay\n");
else {
fs_private_lib();
}
}
if (arg_private_cache) {
if (cfg.chrootdir)
fwarning("private-cache feature is disabled in chroot\n");
else if (arg_overlay)
fwarning("private-cache feature is disabled in overlay\n");
else
fs_private_cache();
}
if (arg_private_tmp) {
EUID_USER();
fs_private_tmp();
EUID_ROOT();
}
if (arg_nodbus)
dbus_session_disable();
if (cfg.hostname)
fs_hostname(cfg.hostname);
if (cfg.hosts_file)
fs_mount_hosts_file();
if (arg_netns)
netns_mounts(arg_netns);
fs_proc_sys_dev_boot();
if (checkcfg(CFG_DISABLE_MNT))
fs_mnt(1);
else if (arg_disable_mnt)
fs_mnt(0);
fs_whitelist();
fs_blacklist(); // mkdir and mkfile are processed all over again
if (arg_nosound) {
pulseaudio_disable();
fs_dev_disable_sound();
}
else if (!arg_noautopulse)
pulseaudio_init();
if (arg_no3d)
fs_dev_disable_3d();
if (arg_notv)
fs_dev_disable_tv();
if (arg_nodvd)
fs_dev_disable_dvd();
if (arg_nou2f)
fs_dev_disable_u2f();
if (arg_novideo)
fs_dev_disable_video();
if (need_preload)
fs_trace();
fs_resolvconf();
fs_logger_print();
fs_logger_change_owner();
EUID_USER();
int cwd = 0;
if (cfg.cwd) {
if (chdir(cfg.cwd) == 0)
cwd = 1;
}
if (!cwd) {
if (chdir("/") < 0)
errExit("chdir");
if (cfg.homedir) {
struct stat s;
if (stat(cfg.homedir, &s) == 0) {
/* coverity[toctou] */
if (chdir(cfg.homedir) < 0)
errExit("chdir");
}
}
}
if (arg_debug) {
char *cpath = get_current_dir_name();
if (cpath) {
printf("Current directory: %s\n", cpath);
free(cpath);
}
}
EUID_ROOT();
fs_x11();
if (arg_x11_xorg)
x11_xorg();
save_umask();
save_nonewprivs();
set_caps();
save_cpu();
save_cgroup();
#ifdef HAVE_SECCOMP
#ifdef SYS_socket
if (cfg.protocol) {
if (arg_debug)
printf("Install protocol filter: %s\n", cfg.protocol);
seccomp_load(RUN_SECCOMP_PROTOCOL); // install filter
protocol_filter_save(); // save filter in RUN_PROTOCOL_CFG
}
else {
int rv = unlink(RUN_SECCOMP_PROTOCOL);
(void) rv;
}
#endif
if (arg_seccomp == 1) {
if (cfg.seccomp_list_keep)
seccomp_filter_keep();
else
seccomp_filter_drop();
}
else { // clean seccomp files under /run/firejail/mnt
int rv = unlink(RUN_SECCOMP_CFG);
rv |= unlink(RUN_SECCOMP_32);
(void) rv;
}
if (arg_memory_deny_write_execute) {
if (arg_debug)
printf("Install memory write&execute filter\n");
seccomp_load(RUN_SECCOMP_MDWX); // install filter
}
else {
int rv = unlink(RUN_SECCOMP_MDWX);
(void) rv;
}
#endif
FILE *rj = create_ready_for_join_file();
save_nogroups();
if (arg_noroot) {
int rv = unshare(CLONE_NEWUSER);
if (rv == -1) {
fwarning("cannot create a new user namespace, going forward without it...\n");
arg_noroot = 0;
}
}
notify_other(child_to_parent_fds[1]);
close(child_to_parent_fds[1]);
wait_for_other(parent_to_child_fds[0]);
close(parent_to_child_fds[0]);
if (arg_noroot) {
if (arg_debug)
printf("noroot user namespace installed\n");
set_caps();
}
if (arg_nonewprivs) {
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) {
fwarning("cannot set NO_NEW_PRIVS, it requires a Linux kernel version 3.5 or newer.\n");
if (force_nonewprivs) {
fprintf(stderr, "Error: NO_NEW_PRIVS required for this sandbox, exiting ...\n");
exit(1);
}
}
else if (arg_debug)
printf("NO_NEW_PRIVS set\n");
}
drop_privs(arg_nogroups);
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
if (cfg.cpus)
set_cpu_affinity();
pid_t app_pid = fork();
if (app_pid == -1)
errExit("fork");
if (app_pid == 0) {
#ifdef HAVE_APPARMOR
if (checkcfg(CFG_APPARMOR) && arg_apparmor) {
errno = 0;
if (aa_change_onexec("firejail-default")) {
fwarning("Cannot confine the application using AppArmor.\n"
"Maybe firejail-default AppArmor profile is not loaded into the kernel.\n"
"As root, run \"aa-enforce firejail-default\" to load it.\n");
}
else if (arg_debug)
printf("AppArmor enabled\n");
}
#endif
if (arg_nice)
set_nice(cfg.nice);
set_rlimits();
start_application(0, rj);
}
fclose(rj);
int status = monitor_application(app_pid); // monitor application
flush_stdin();
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
} else {
return -1;
}
}
Vulnerability Type:
CWE ID: CWE-284
Summary: In Firejail before 0.9.60, seccomp filters are writable inside the jail, leading to a lack of intended seccomp restrictions for a process that is joined to the jail after a filter has been modified by an attacker.
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more | Medium | 169,659 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: IW_IMPL(int) iw_get_i32le(const iw_byte *b)
{
return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24));
}
Vulnerability Type: DoS
CWE ID: CWE-682
Summary: libimageworsener.a in ImageWorsener before 1.3.1 has *left shift cannot be represented in type int* undefined behavior issues, which might allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted image, related to imagew-bmp.c and imagew-util.c.
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16 | Medium | 168,196 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
if (image->columns == 0)
image->columns=2592;
if (image->rows == 0)
image->rows=3508;
image->depth=8;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Monochrome colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=HuffmanDecodeImage(image);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file.
Commit Message: | Medium | 168,564 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: print_pixel(png_structp png_ptr, png_infop info_ptr, png_const_bytep row,
png_uint_32 x)
{
PNG_CONST unsigned int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
switch (png_get_color_type(png_ptr, info_ptr))
{
case PNG_COLOR_TYPE_GRAY:
printf("GRAY %u\n", component(row, x, 0, bit_depth, 1));
return;
/* The palette case is slightly more difficult - the palette and, if
* present, the tRNS ('transparency', though the values are really
* opacity) data must be read to give the full picture:
*/
case PNG_COLOR_TYPE_PALETTE:
{
PNG_CONST unsigned int index = component(row, x, 0, bit_depth, 1);
png_colorp palette = NULL;
int num_palette = 0;
if ((png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette) &
PNG_INFO_PLTE) && num_palette > 0 && palette != NULL)
{
png_bytep trans_alpha = NULL;
int num_trans = 0;
if ((png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans,
NULL) & PNG_INFO_tRNS) && num_trans > 0 &&
trans_alpha != NULL)
printf("INDEXED %u = %d %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue,
index < num_trans ? trans_alpha[index] : 255);
else /* no transparency */
printf("INDEXED %u = %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue);
}
else
printf("INDEXED %u = invalid index\n", index);
}
return;
case PNG_COLOR_TYPE_RGB:
printf("RGB %u %u %u\n", component(row, x, 0, bit_depth, 3),
component(row, x, 1, bit_depth, 3),
component(row, x, 2, bit_depth, 3));
return;
case PNG_COLOR_TYPE_GRAY_ALPHA:
printf("GRAY+ALPHA %u %u\n", component(row, x, 0, bit_depth, 2),
component(row, x, 1, bit_depth, 2));
return;
case PNG_COLOR_TYPE_RGB_ALPHA:
printf("RGBA %u %u %u %u\n", component(row, x, 0, bit_depth, 4),
component(row, x, 1, bit_depth, 4),
component(row, x, 2, bit_depth, 4),
component(row, x, 3, bit_depth, 4));
return;
default:
png_error(png_ptr, "pngpixel: invalid color type");
}
}
Vulnerability Type: +Priv
CWE ID:
Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085.
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
| High | 173,566 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: stub_charset ()
{
locale = get_locale_var ("LC_CTYPE");
locale = get_locale_var ("LC_CTYPE");
if (locale == 0 || *locale == 0)
return "ASCII";
s = strrchr (locale, '.');
if (s)
{
t = strchr (s, '@');
if (t)
*t = 0;
return ++s;
}
else if (STREQ (locale, "UTF-8"))
return "UTF-8";
else
return "ASCII";
}
Vulnerability Type: Exec Code Overflow
CWE ID: CWE-119
Summary: A heap-based buffer overflow exists in GNU Bash before 4.3 when wide characters, not supported by the current locale set in the LC_CTYPE environment variable, are printed through the echo built-in function. A local attacker, who can provide data to print through the "echo -e" built-in function, may use this flaw to crash a script or execute code with the privileges of the bash process. This occurs because ansicstr() in lib/sh/strtrans.c mishandles u32cconv().
Commit Message: | Medium | 165,431 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: vmnc_handle_packet (GstVMncDec * dec, const guint8 * data, int len,
gboolean decode)
{
int type;
int offset = 0;
if (len < 4) {
GST_LOG_OBJECT (dec, "Packet too short");
return ERROR_INSUFFICIENT_DATA;
}
type = data[0];
switch (type) {
case 0:
{
int numrect = RFB_GET_UINT16 (data + 2);
int i;
int read;
offset = 4;
for (i = 0; i < numrect; i++) {
struct RfbRectangle r;
rectangle_handler handler;
if (len < offset + 12) {
GST_LOG_OBJECT (dec,
"Packet too short for rectangle header: %d < %d",
len, offset + 12);
return ERROR_INSUFFICIENT_DATA;
}
GST_LOG_OBJECT (dec, "Reading rectangle %d", i);
r.x = RFB_GET_UINT16 (data + offset);
r.y = RFB_GET_UINT16 (data + offset + 2);
r.width = RFB_GET_UINT16 (data + offset + 4);
r.height = RFB_GET_UINT16 (data + offset + 6);
r.type = RFB_GET_UINT32 (data + offset + 8);
if (r.type != TYPE_WMVi) {
/* We must have a WMVi packet to initialise things before we can
* continue */
if (!dec->have_format) {
GST_WARNING_OBJECT (dec, "Received packet without WMVi: %d",
r.type);
return ERROR_INVALID;
}
if (r.x + r.width > dec->format.width ||
r.y + r.height > dec->format.height) {
GST_WARNING_OBJECT (dec, "Rectangle out of range, type %d", r.type);
return ERROR_INVALID;
}
}
switch (r.type) {
handler = vmnc_handle_wmve_rectangle;
break;
case TYPE_WMVf:
handler = vmnc_handle_wmvf_rectangle;
break;
case TYPE_WMVg:
handler = vmnc_handle_wmvg_rectangle;
break;
case TYPE_WMVh:
handler = vmnc_handle_wmvh_rectangle;
break;
case TYPE_WMVi:
handler = vmnc_handle_wmvi_rectangle;
break;
case TYPE_WMVj:
handler = vmnc_handle_wmvj_rectangle;
break;
case TYPE_RAW:
handler = vmnc_handle_raw_rectangle;
break;
case TYPE_COPY:
handler = vmnc_handle_copy_rectangle;
break;
case TYPE_HEXTILE:
handler = vmnc_handle_hextile_rectangle;
break;
default:
GST_WARNING_OBJECT (dec, "Unknown rectangle type");
return ERROR_INVALID;
}
read = handler (dec, &r, data + offset + 12, len - offset - 12, decode);
if (read < 0) {
GST_DEBUG_OBJECT (dec, "Error calling rectangle handler\n");
return read;
}
offset += 12 + read;
}
break;
}
default:
GST_WARNING_OBJECT (dec, "Packet type unknown: %d", type);
return ERROR_INVALID;
}
return offset;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The vmnc decoder in the gstreamer does not initialize the render canvas, which allows remote attackers to obtain sensitive information as demonstrated by thumbnailing a simple 1 frame vmnc movie that does not draw to the allocated render canvas.
Commit Message: | Medium | 165,251 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,
AVStream *st, char *mime)
{
int number_of_streams = avio_rb16(pb);
int number_of_mdpr;
int i, ret;
unsigned size2;
for (i = 0; i<number_of_streams; i++)
avio_rb16(pb);
number_of_mdpr = avio_rb16(pb);
if (number_of_mdpr != 1) {
avpriv_request_sample(s, "MLTI with multiple (%d) MDPR", number_of_mdpr);
}
for (i = 0; i < number_of_mdpr; i++) {
AVStream *st2;
if (i > 0) {
st2 = avformat_new_stream(s, NULL);
if (!st2) {
ret = AVERROR(ENOMEM);
return ret;
}
st2->id = st->id + (i<<16);
st2->codecpar->bit_rate = st->codecpar->bit_rate;
st2->start_time = st->start_time;
st2->duration = st->duration;
st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;
st2->priv_data = ff_rm_alloc_rmstream();
if (!st2->priv_data)
return AVERROR(ENOMEM);
} else
st2 = st;
size2 = avio_rb32(pb);
ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,
size2, mime);
if (ret < 0)
return ret;
}
return 0;
}
Vulnerability Type:
CWE ID: CWE-416
Summary: FFmpeg before commit a7e032a277452366771951e29fd0bf2bd5c029f0 contains a use-after-free vulnerability in the realmedia demuxer that can result in vulnerability allows attacker to read heap memory. This attack appear to be exploitable via specially crafted RM file has to be provided as input. This vulnerability appears to have been fixed in a7e032a277452366771951e29fd0bf2bd5c029f0 and later.
Commit Message: avformat/rmdec: Do not pass mime type in rm_read_multi() to ff_rm_read_mdpr_codecdata()
Fixes: use after free()
Fixes: rmdec-crash-ffe85b4cab1597d1cfea6955705e53f1f5c8a362
Found-by: Paul Ch <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]> | Medium | 168,924 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void ff_h264_free_tables(H264Context *h, int free_rbsp)
{
int i;
H264Context *hx;
av_freep(&h->intra4x4_pred_mode);
av_freep(&h->chroma_pred_mode_table);
av_freep(&h->cbp_table);
av_freep(&h->mvd_table[0]);
av_freep(&h->mvd_table[1]);
av_freep(&h->direct_table);
av_freep(&h->non_zero_count);
av_freep(&h->slice_table_base);
h->slice_table = NULL;
av_freep(&h->list_counts);
av_freep(&h->mb2b_xy);
av_freep(&h->mb2br_xy);
av_buffer_pool_uninit(&h->qscale_table_pool);
av_buffer_pool_uninit(&h->mb_type_pool);
av_buffer_pool_uninit(&h->motion_val_pool);
av_buffer_pool_uninit(&h->ref_index_pool);
if (free_rbsp && h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
ff_h264_unref_picture(h, &h->DPB[i]);
av_freep(&h->DPB);
} else if (h->DPB) {
for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
h->DPB[i].needs_realloc = 1;
}
h->cur_pic_ptr = NULL;
for (i = 0; i < H264_MAX_THREADS; i++) {
hx = h->thread_context[i];
if (!hx)
continue;
av_freep(&hx->top_borders[1]);
av_freep(&hx->top_borders[0]);
av_freep(&hx->bipred_scratchpad);
av_freep(&hx->edge_emu_buffer);
av_freep(&hx->dc_val_base);
av_freep(&hx->er.mb_index2xy);
av_freep(&hx->er.error_status_table);
av_freep(&hx->er.er_temp_buffer);
av_freep(&hx->er.mbintra_table);
av_freep(&hx->er.mbskip_table);
if (free_rbsp) {
av_freep(&hx->rbsp_buffer[1]);
av_freep(&hx->rbsp_buffer[0]);
hx->rbsp_buffer_size[0] = 0;
hx->rbsp_buffer_size[1] = 0;
}
if (i)
av_freep(&h->thread_context[i]);
}
}
Vulnerability Type: DoS
CWE ID:
Summary: Use-after-free vulnerability in the ff_h264_free_tables function in libavcodec/h264.c in FFmpeg before 2.3.6 allows remote attackers to cause a denial of service or possibly have unspecified other impact via crafted H.264 data in an MP4 file, as demonstrated by an HTML VIDEO element that references H.264 data.
Commit Message: avcodec/h264: Clear delayed_pic on deallocation
Fixes use of freed memory
Fixes: case5_av_frame_copy_props.mp4
Found-by: Michal Zalewski <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]> | Medium | 166,624 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int nonCallback(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
if (exec->argumentCount() <= 1 || !exec->argument(1).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(1)), castedThis->globalObject());
impl->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback);
return JSValue::encode(jsUndefined());
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The HTML parser in Google Chrome before 12.0.742.112 does not properly address *lifetime and re-entrancy issues,* which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors.
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 | High | 170,593 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void WebPluginDelegateProxy::SendUpdateGeometry(
bool bitmaps_changed) {
PluginMsg_UpdateGeometry_Param param;
param.window_rect = plugin_rect_;
param.clip_rect = clip_rect_;
param.windowless_buffer0 = TransportDIB::DefaultHandleValue();
param.windowless_buffer1 = TransportDIB::DefaultHandleValue();
param.windowless_buffer_index = back_buffer_index();
param.background_buffer = TransportDIB::DefaultHandleValue();
param.transparent = transparent_;
#if defined(OS_POSIX)
if (bitmaps_changed)
#endif
{
if (transport_stores_[0].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(),
¶m.windowless_buffer0);
if (transport_stores_[1].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(),
¶m.windowless_buffer1);
if (background_store_.dib.get())
CopyTransportDIBHandleForMessage(background_store_.dib->handle(),
¶m.background_buffer);
}
IPC::Message* msg;
#if defined(OS_WIN)
if (UseSynchronousGeometryUpdates()) {
msg = new PluginMsg_UpdateGeometrySync(instance_id_, param);
} else // NOLINT
#endif
{
msg = new PluginMsg_UpdateGeometry(instance_id_, param);
msg->set_unblock(true);
}
Send(msg);
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
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 | High | 170,956 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen;
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
Vulnerability Type: DoS
CWE ID: CWE-909
Summary: In ipSecSetEncapSocketOwner of XfrmController.cpp, there is a possible failure to initialize a security feature due to uninitialized data. This could lead to local denial of service of IPsec on sockets with no additional execution privileges needed. User interaction is not needed for exploitation. Product: Android Versions: Android-9.0 Android ID: A-111650288
Commit Message: Set optlen for UDP-encap check in XfrmController
When setting the socket owner for an encap socket XfrmController will
first attempt to verify that the socket has the UDP-encap socket option
set. When doing so it would pass in an uninitialized optlen parameter
which could cause the call to not modify the option value if the optlen
happened to be too short. So for example if the stack happened to
contain a zero where optlen was located the check would fail and the
socket owner would not be changed.
Fix this by setting optlen to the size of the option value parameter.
Test: run cts -m CtsNetTestCases
BUG: 111650288
Change-Id: I57b6e9dba09c1acda71e3ec2084652e961667bd9
(cherry picked from commit fc42a105147310bd680952d4b71fe32974bd8506)
| Medium | 174,073 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: ProfilingProcessHost::Mode ProfilingProcessHost::GetCurrentMode() {
const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(USE_ALLOCATOR_SHIM)
if (cmdline->HasSwitch(switches::kMemlog) ||
base::FeatureList::IsEnabled(kOOPHeapProfilingFeature)) {
if (cmdline->HasSwitch(switches::kEnableHeapProfiling)) {
LOG(ERROR) << "--" << switches::kEnableHeapProfiling
<< " specified with --" << switches::kMemlog
<< "which are not compatible. Memlog will be disabled.";
return Mode::kNone;
}
std::string mode;
if (cmdline->HasSwitch(switches::kMemlog)) {
mode = cmdline->GetSwitchValueASCII(switches::kMemlog);
} else {
mode = base::GetFieldTrialParamValueByFeature(
kOOPHeapProfilingFeature, kOOPHeapProfilingFeatureMode);
}
if (mode == switches::kMemlogModeAll)
return Mode::kAll;
if (mode == switches::kMemlogModeMinimal)
return Mode::kMinimal;
if (mode == switches::kMemlogModeBrowser)
return Mode::kBrowser;
if (mode == switches::kMemlogModeGpu)
return Mode::kGpu;
if (mode == switches::kMemlogModeRendererSampling)
return Mode::kRendererSampling;
DLOG(ERROR) << "Unsupported value: \"" << mode << "\" passed to --"
<< switches::kMemlog;
}
return Mode::kNone;
#else
LOG_IF(ERROR, cmdline->HasSwitch(switches::kMemlog))
<< "--" << switches::kMemlog
<< " specified but it will have no effect because the use_allocator_shim "
<< "is not available in this build.";
return Mode::kNone;
#endif
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Use after free in PDFium in Google Chrome prior to 63.0.3239.84 allowed a remote attacker to potentially exploit heap corruption via a crafted PDF file.
Commit Message: [Reland #1] Add Android OOP HP end-to-end tests.
The original CL added a javatest and its dependencies to the apk_under_test.
This causes the dependencies to be stripped from the instrumentation_apk, which
causes issue. This CL updates the build configuration so that the javatest and
its dependencies are only added to the instrumentation_apk.
This is a reland of e0b4355f0651adb1ebc2c513dc4410471af712f5
Original change's description:
> Add Android OOP HP end-to-end tests.
>
> This CL has three components:
> 1) The bulk of the logic in OOP HP was refactored into ProfilingTestDriver.
> 2) Adds a java instrumentation test, along with a JNI shim that forwards into
> ProfilingTestDriver.
> 3) Creates a new apk: chrome_public_apk_for_test that contains the same
> content as chrome_public_apk, as well as native files needed for (2).
> chrome_public_apk_test now targets chrome_public_apk_for_test instead of
> chrome_public_apk.
>
> Other ideas, discarded:
> * Originally, I attempted to make the browser_tests target runnable on
> Android. The primary problem is that native test harness cannot fork
> or spawn processes. This is difficult to solve.
>
> More details on each of the components:
> (1) ProfilingTestDriver
> * The TracingController test was migrated to use ProfilingTestDriver, but the
> write-to-file test was left as-is. The latter behavior will likely be phased
> out, but I'll clean that up in a future CL.
> * gtest isn't supported for Android instrumentation tests. ProfilingTestDriver
> has a single function RunTest that returns a 'bool' indicating success. On
> failure, the class uses LOG(ERROR) to print the nature of the error. This will
> cause the error to be printed out on browser_test error. On instrumentation
> test failure, the error will be forwarded to logcat, which is available on all
> infra bot test runs.
> (2) Instrumentation test
> * For now, I only added a single test for the "browser" mode. Furthermore, I'm
> only testing the start with command-line path.
> (3) New apk
> * libchromefortest is a new shared library that contains all content from
> libchrome, but also contains native sources for the JNI shim.
> * chrome_public_apk_for_test is a new apk that contains all content from
> chrome_public_apk, but uses a single shared library libchromefortest rather
> than libchrome. This also contains java sources for the JNI shim.
> * There is no way to just add a second shared library to chrome_public_apk
> that just contains the native sources from the JNI shim without causing ODR
> issues.
> * chrome_public_test_apk now has apk_under_test = chrome_public_apk_for_test.
> * There is no way to add native JNI sources as a shared library to
> chrome_public_test_apk without causing ODR issues.
>
> Finally, this CL drastically increases the timeout to wait for native
> initialization. The previous timeout was 2 *
> CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL, which flakily failed for this test.
> This suggests that this step/timeout is generally flaky. I increased the timeout
> to 20 * CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL.
>
> Bug: 753218
> Change-Id: Ic224b7314fff57f1770a4048aa5753f54e040b55
> Reviewed-on: https://chromium-review.googlesource.com/770148
> Commit-Queue: Erik Chen <[email protected]>
> Reviewed-by: John Budorick <[email protected]>
> Reviewed-by: Brett Wilson <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#517541}
Bug: 753218
TBR: [email protected]
Change-Id: Ic6aafb34c2467253f75cc85da48200d19f3bc9af
Reviewed-on: https://chromium-review.googlesource.com/777697
Commit-Queue: Erik Chen <[email protected]>
Reviewed-by: John Budorick <[email protected]>
Cr-Commit-Position: refs/heads/master@{#517850} | Medium | 172,924 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
{
if (x + 1 > 10)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"x is bigger than 9");
return FALSE;
}
return x + 1;
}
Vulnerability Type: DoS Bypass
CWE ID: CWE-264
Summary: DBus-GLib 0.73 disregards the access flag of exported GObject properties, which allows local users to bypass intended access restrictions and possibly cause a denial of service by modifying properties, as demonstrated by properties of the (1) DeviceKit-Power, (2) NetworkManager, and (3) ModemManager services.
Commit Message: | Low | 165,107 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: bool nodeHasRole(Node* node, const String& role) {
if (!node || !node->isElementNode())
return false;
return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role);
}
Vulnerability Type: Exec Code
CWE ID: CWE-254
Summary: Google Chrome before 44.0.2403.89 does not ensure that the auto-open list omits all dangerous file types, which makes it easier for remote attackers to execute arbitrary code by providing a crafted file and leveraging a user's previous *Always open files of this type* choice, related to download_commands.cc and download_prefs.cc.
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858} | Medium | 171,930 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: long Cluster::Parse(long long& pos, long& len) const {
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; // nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total)) {
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; // consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0) {
if (block_stop > cluster_stop) {
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
} else if ((total >= 0) && (block_stop > total)) {
m_element_size = total - m_element_start;
pos = total;
break;
} else if (block_stop > avail) {
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) // BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) // SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; // consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0) {
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; // defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; // defend against trucated stream
}
return 1; // no more entries
}
Vulnerability Type: DoS Exec Code Mem. Corr.
CWE ID: CWE-20
Summary: libvpx in libwebm in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726.
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
| High | 173,846 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void smp_task_timedout(struct timer_list *t)
{
struct sas_task_slow *slow = from_timer(slow, t, timer);
struct sas_task *task = slow->task;
unsigned long flags;
spin_lock_irqsave(&task->task_state_lock, flags);
if (!(task->task_state_flags & SAS_TASK_STATE_DONE))
task->task_state_flags |= SAS_TASK_STATE_ABORTED;
spin_unlock_irqrestore(&task->task_state_lock, flags);
complete(&task->slow_task->completion);
}
Vulnerability Type:
CWE ID: CWE-416
Summary: An issue was discovered in the Linux kernel before 4.20. There is a race condition in smp_task_timedout() and smp_task_done() in drivers/scsi/libsas/sas_expander.c, leading to a use-after-free.
Commit Message: scsi: libsas: fix a race condition when smp task timeout
When the lldd is processing the complete sas task in interrupt and set the
task stat as SAS_TASK_STATE_DONE, the smp timeout timer is able to be
triggered at the same time. And smp_task_timedout() will complete the task
wheter the SAS_TASK_STATE_DONE is set or not. Then the sas task may freed
before lldd end the interrupt process. Thus a use-after-free will happen.
Fix this by calling the complete() only when SAS_TASK_STATE_DONE is not
set. And remove the check of the return value of the del_timer(). Once the
LLDD sets DONE, it must call task->done(), which will call
smp_task_done()->complete() and the task will be completed and freed
correctly.
Reported-by: chenxiang <[email protected]>
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
CC: Hannes Reinecke <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Reviewed-by: John Garry <[email protected]>
Reviewed-by: Johannes Thumshirn <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]> | High | 169,783 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-189
Summary: Integer overflow in the xfs_acl_from_disk function in fs/xfs/xfs_acl.c in the Linux kernel before 3.1.9 allows local users to cause a denial of service (panic) via a filesystem with a malformed ACL, leading to a heap-based buffer overflow.
Commit Message: xfs: validate acl count
This prevents in-memory corruption and possible panics if the on-disk
ACL is badly corrupted.
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Ben Myers <[email protected]> | Medium | 165,656 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static void willRemoveChildren(ContainerNode* container)
{
NodeVector children;
getChildNodes(container, children);
container->document().nodeChildrenWillBeRemoved(container);
ChildListMutationScope mutation(container);
for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
Node* child = it->get();
mutation.willRemoveChild(child);
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in core/dom/ContainerNode.cpp in Blink, as used in Google Chrome before 31.0.1650.48, allows remote attackers to cause a denial of service or possibly have unspecified other impact by leveraging improper handling of DOM range objects in circumstances that require child node removal after a (1) mutation or (2) blur event.
Commit Message: Notify nodes removal to Range/Selection after dispatching blur and mutation event
This patch changes notifying nodes removal to Range/Selection after dispatching blur and mutation event. In willRemoveChildren(), like willRemoveChild(); r115686 did same change, although it didn't change willRemoveChildren().
The issue 295010, use-after-free, is caused by setting removed node to Selection in mutation event handler.
BUG=295010
TEST=LayoutTests/fast/dom/Range/range-created-during-remove-children.html, LayoutTests/editing/selection/selection-change-in-mutation-event-by-remove-children.html, LayoutTests/editing/selection/selection-change-in-blur-event-by-remove-children.html
[email protected]
Review URL: https://codereview.chromium.org/25389004
git-svn-id: svn://svn.chromium.org/blink/trunk@159007 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | Medium | 171,159 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*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);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
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,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,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(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,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
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,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) 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+=GetPixelChannels(image);
}
*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 Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) 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,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%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+=GetPixelChannels(image);
}
*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,exception);
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 Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,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+=GetPixelChannels(image);
}
*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':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
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 Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,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':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.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 Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
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':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.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);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
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':
{
register unsigned char
*pixels;
/*
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 Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,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->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
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->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
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->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
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':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,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 Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,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);
}
Vulnerability Type: Overflow
CWE ID: CWE-119
Summary: ImageMagick 7.0.8-50 Q16 has a stack-based buffer overflow at coders/pnm.c in WritePNMImage because of off-by-one errors.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1612 | Medium | 170,202 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: cJSON *cJSON_CreateFloat( double num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-119
Summary: The parse_string function in cjson.c in the cJSON library mishandles UTF8/16 strings, which allows remote attackers to cause a denial of service (crash) or execute arbitrary code via a non-hex character in a JSON string, which triggers a heap-based buffer overflow.
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]> | High | 167,272 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors,
int *pexit_code, ref * perror_object)
{
ref *epref = pref;
ref doref;
ref *perrordict;
ref error_name;
int code, ccode;
ref saref;
i_ctx_t *i_ctx_p = *pi_ctx_p;
int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal;
*pexit_code = 0;
*gc_signal = 0;
ialloc_reset_requested(idmemory);
again:
/* Avoid a dangling error object that might get traced by a future GC. */
make_null(perror_object);
o_stack.requested = e_stack.requested = d_stack.requested = 0;
while (*gc_signal) { /* Some routine below triggered a GC. */
gs_gc_root_t epref_root;
*gc_signal = 0;
/* Make sure that doref will get relocated properly if */
/* a garbage collection happens with epref == &doref. */
gs_register_ref_root(imemory_system, &epref_root,
(void **)&epref, "gs_call_interp(epref)");
code = interp_reclaim(pi_ctx_p, -1);
i_ctx_p = *pi_ctx_p;
gs_unregister_root(imemory_system, &epref_root,
"gs_call_interp(epref)");
if (code < 0)
return code;
}
code = interp(pi_ctx_p, epref, perror_object);
i_ctx_p = *pi_ctx_p;
if (!r_has_type(&i_ctx_p->error_object, t__invalid)) {
*perror_object = i_ctx_p->error_object;
make_t(&i_ctx_p->error_object, t__invalid);
}
/* Prevent a dangling reference to the GC signal in ticks_left */
/* in the frame of interp, but be prepared to do a GC if */
/* an allocation in this routine asks for it. */
*gc_signal = 0;
set_gc_signal(i_ctx_p, 1);
if (esp < esbot) /* popped guard entry */
esp = esbot;
switch (code) {
case gs_error_Fatal:
*pexit_code = 255;
return code;
case gs_error_Quit:
*perror_object = osp[-1];
*pexit_code = code = osp->value.intval;
osp -= 2;
return
(code == 0 ? gs_error_Quit :
code < 0 && code > -100 ? code : gs_error_Fatal);
case gs_error_InterpreterExit:
return 0;
case gs_error_ExecStackUnderflow:
/****** WRONG -- must keep mark blocks intact ******/
ref_stack_pop_block(&e_stack);
doref = *perror_object;
epref = &doref;
goto again;
case gs_error_VMreclaim:
/* Do the GC and continue. */
/* We ignore the return value here, if it fails here
* we'll call it again having jumped to the "again" label.
* Where, assuming it fails again, we'll handle the error.
*/
(void)interp_reclaim(pi_ctx_p,
(osp->value.intval == 2 ?
avm_global : avm_local));
i_ctx_p = *pi_ctx_p;
make_oper(&doref, 0, zpop);
epref = &doref;
goto again;
case gs_error_NeedInput:
case gs_error_interrupt:
return code;
}
/* Adjust osp in case of operand stack underflow */
if (osp < osbot - 1)
osp = osbot - 1;
/* We have to handle stack over/underflow specially, because */
/* we might be able to recover by adding or removing a block. */
switch (code) {
case gs_error_dictstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_dstack, which does a ref_stack_extend, */
/* so if` we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
/* Skip system dictionaries for CET 20-02-02 */
ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref);
if (ccode < 0)
return ccode;
ref_stack_pop_to(&d_stack, min_dstack_size);
dict_set_top();
*++osp = saref;
break;
case gs_error_dictstackunderflow:
if (ref_stack_pop_block(&d_stack) >= 0) {
dict_set_top();
doref = *perror_object;
epref = &doref;
goto again;
}
break;
case gs_error_execstackoverflow:
/* We don't have to handle this specially: */
/* The only places that could generate it */
/* use check_estack, which does a ref_stack_extend, */
/* so if we get this error, it's a real one. */
if (osp >= ostop) {
if ((ccode = ref_stack_extend(&o_stack, 1)) < 0)
return ccode;
}
ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref);
if (ccode < 0)
return ccode;
{
uint count = ref_stack_count(&e_stack);
uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM;
if (count > limit) {
/*
* If there is an e-stack mark within MIN_BLOCK_ESTACK of
* the new top, cut the stack back to remove the mark.
*/
int skip = count - limit;
int i;
for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) {
const ref *ep = ref_stack_index(&e_stack, i);
if (r_has_type_attrs(ep, t_null, a_executable)) {
skip = i + 1;
break;
}
}
pop_estack(i_ctx_p, skip);
}
}
*++osp = saref;
break;
case gs_error_stackoverflow:
if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */
/* it might be a procedure being pushed as a */
/* literal. We check for this case specially. */
doref = *perror_object;
if (r_is_proc(&doref)) {
*++osp = doref;
make_null_proc(&doref);
}
epref = &doref;
goto again;
}
ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref);
if (ccode < 0)
return ccode;
ref_stack_clear(&o_stack);
*++osp = saref;
break;
case gs_error_stackunderflow:
if (ref_stack_pop_block(&o_stack) >= 0) {
doref = *perror_object;
epref = &doref;
goto again;
}
break;
}
if (user_errors < 0)
return code;
if (gs_errorname(i_ctx_p, code, &error_name) < 0)
return code; /* out-of-range error code! */
/*
* For greater Adobe compatibility, only the standard PostScript errors
* are defined in errordict; the rest are in gserrordict.
*/
if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
(dict_find(perrordict, &error_name, &epref) <= 0 &&
(dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
dict_find(perrordict, &error_name, &epref) <= 0))
)
return code; /* error name not in errordict??? */
doref = *epref;
epref = &doref;
/* Push the error object on the operand stack if appropriate. */
if (!GS_ERROR_IS_INTERRUPT(code)) {
/* Replace the error object if within an oparray or .errorexec. */
*++osp = *perror_object;
errorexec_find(i_ctx_p, osp);
}
goto again;
}
Vulnerability Type:
CWE ID: CWE-388
Summary: In Artifex Ghostscript before 9.24, attackers able to supply crafted PostScript files could use insufficient interpreter stack-size checking during error handling to crash the interpreter.
Commit Message: | Medium | 164,694 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
Vulnerability Type:
CWE ID:
Summary: Google Chrome before 25.0.1364.99 on Mac OS X does not properly implement signal handling for Native Client (aka NaCl) code, which has unspecified impact and attack vectors.
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 | High | 171,389 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
Vulnerability Type: +Info
CWE ID: CWE-362
Summary: Race condition in the environ_read function in fs/proc/base.c in the Linux kernel before 4.5.4 allows local users to obtain sensitive information from kernel memory by reading a /proc/*/environ file during a process-setup time interval in which environment-variable copying is incomplete.
Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready
If /proc/<PID>/environ gets read before the envp[] array is fully set up
in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to
read more bytes than are actually written, as env_start will already be
set but env_end will still be zero, making the range calculation
underflow, allowing to read beyond the end of what has been written.
Fix this as it is done for /proc/<PID>/cmdline by testing env_end for
zero. It is, apparently, intentionally set last in create_*_tables().
This bug was found by the PaX size_overflow plugin that detected the
arithmetic underflow of 'this_len = env_end - (env_start + src)' when
env_end is still zero.
The expected consequence is that userland trying to access
/proc/<PID>/environ of a not yet fully set up process may get
inconsistent data as we're in the middle of copying in the environment
variables.
Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363
Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461
Signed-off-by: Mathias Krause <[email protected]>
Cc: Emese Revfy <[email protected]>
Cc: Pax Team <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Alexey Dobriyan <[email protected]>
Cc: Cyrill Gorcunov <[email protected]>
Cc: Jarod Wilson <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]> | Medium | 166,920 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation. | Code: void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
Vulnerability Type:
CWE ID: CWE-416
Summary: A heap use after free in PDFium in Google Chrome prior to 54.0.2840.59 for Windows, Mac, and Linux; 54.0.2840.85 for Android allows a remote attacker to potentially exploit heap corruption via crafted PDF files.
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122} | Medium | 172,080 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.