func_name
stringlengths 2
53
| func_src_before
stringlengths 63
114k
| func_src_after
stringlengths 86
114k
| line_changes
dict | char_changes
dict | commit_link
stringlengths 66
117
| file_name
stringlengths 5
72
| vul_type
stringclasses 9
values |
---|---|---|---|---|---|---|---|
sctp_sf_ootb | sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
} | sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
} | {
"deleted": [
{
"line_no": 56,
"char_start": 1500,
"char_end": 1548,
"line": "\t\t/* Report violation if chunk len overflows */\n"
},
{
"line_no": 57,
"char_start": 1548,
"char_end": 1604,
"line": "\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n"
},
{
"line_no": 58,
"char_start": 1604,
"char_end": 1642,
"line": "\t\tif (ch_end > skb_tail_pointer(skb))\n"
},
{
"line_no": 59,
"char_start": 1642,
"char_end": 1705,
"line": "\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n"
},
{
"line_no": 60,
"char_start": 1705,
"char_end": 1724,
"line": "\t\t\t\t\t\t commands);\n"
},
{
"line_no": 61,
"char_start": 1724,
"char_end": 1725,
"line": "\n"
}
],
"added": [
{
"line_no": 25,
"char_start": 668,
"char_end": 716,
"line": "\t\t/* Report violation if chunk len overflows */\n"
},
{
"line_no": 26,
"char_start": 716,
"char_end": 772,
"line": "\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n"
},
{
"line_no": 27,
"char_start": 772,
"char_end": 810,
"line": "\t\tif (ch_end > skb_tail_pointer(skb))\n"
},
{
"line_no": 28,
"char_start": 810,
"char_end": 873,
"line": "\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n"
},
{
"line_no": 29,
"char_start": 873,
"char_end": 892,
"line": "\t\t\t\t\t\t commands);\n"
},
{
"line_no": 30,
"char_start": 892,
"char_end": 893,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 1498,
"char_end": 1723,
"chars": "\n\n\t\t/* Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);"
}
],
"added": [
{
"char_start": 673,
"char_end": 898,
"chars": "Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* "
}
]
} | github.com/torvalds/linux/commit/bf911e985d6bbaa328c20c3e05f4eb03de11fdd6 | net/sctp/sm_statefuns.c | cwe-125 |
asylo::primitives::TrustedPrimitives::UntrustedCall | PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,
MessageWriter *input,
MessageReader *output) {
int ret;
UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();
SgxParams *const sgx_params =
reinterpret_cast<SgxParams *>(untrusted_cache->Malloc(sizeof(SgxParams)));
Cleanup clean_up(
[sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });
sgx_params->input_size = 0;
sgx_params->input = nullptr;
if (input) {
sgx_params->input_size = input->MessageSize();
if (sgx_params->input_size > 0) {
// Allocate and copy data to |input_buffer|.
sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);
input->Serialize(const_cast<void *>(sgx_params->input));
}
}
sgx_params->output_size = 0;
sgx_params->output = nullptr;
CHECK_OCALL(
ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));
if (sgx_params->input) {
untrusted_cache->Free(const_cast<void *>(sgx_params->input));
}
if (sgx_params->output) {
// For the results obtained in |output_buffer|, copy them to |output|
// before freeing the buffer.
output->Deserialize(sgx_params->output, sgx_params->output_size);
TrustedPrimitives::UntrustedLocalFree(sgx_params->output);
}
return PrimitiveStatus::OkStatus();
} | PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,
MessageWriter *input,
MessageReader *output) {
int ret;
UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();
SgxParams *const sgx_params =
reinterpret_cast<SgxParams *>(untrusted_cache->Malloc(sizeof(SgxParams)));
Cleanup clean_up(
[sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });
sgx_params->input_size = 0;
sgx_params->input = nullptr;
if (input) {
sgx_params->input_size = input->MessageSize();
if (sgx_params->input_size > 0) {
// Allocate and copy data to |input_buffer|.
sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);
input->Serialize(const_cast<void *>(sgx_params->input));
}
}
sgx_params->output_size = 0;
sgx_params->output = nullptr;
CHECK_OCALL(
ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));
if (sgx_params->input) {
untrusted_cache->Free(const_cast<void *>(sgx_params->input));
}
if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,
sgx_params->output_size)) {
TrustedPrimitives::BestEffortAbort(
"UntrustedCall: sgx_param output should be in untrusted memory");
}
if (sgx_params->output) {
// For the results obtained in |output_buffer|, copy them to |output|
// before freeing the buffer.
output->Deserialize(sgx_params->output, sgx_params->output_size);
TrustedPrimitives::UntrustedLocalFree(sgx_params->output);
}
return PrimitiveStatus::OkStatus();
} | {
"deleted": [],
"added": [
{
"line_no": 29,
"char_start": 1137,
"char_end": 1200,
"line": " if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n"
},
{
"line_no": 30,
"char_start": 1200,
"char_end": 1271,
"line": " sgx_params->output_size)) {\n"
},
{
"line_no": 31,
"char_start": 1271,
"char_end": 1311,
"line": " TrustedPrimitives::BestEffortAbort(\n"
},
{
"line_no": 32,
"char_start": 1311,
"char_end": 1385,
"line": " \"UntrustedCall: sgx_param output should be in untrusted memory\");\n"
},
{
"line_no": 33,
"char_start": 1385,
"char_end": 1389,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1143,
"char_end": 1395,
"chars": "!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if ("
}
]
} | github.com/google/asylo/commit/83036fd841d33baa7e039f842d131aa7881fdcc2 | asylo/platform/primitives/sgx/trusted_sgx.cc | cwe-125 |
string_scan_range | static int string_scan_range(RList *list, const ut8 *buf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (!buf || !min) {
return -1;
}
while (needle < to) {
rc = r_utf8_decode (buf + needle, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc;
if ((to - needle) > 4) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r)) {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\e", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 28) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e"[r];
} else {
// string too long
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
// reduce false positives
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
if (list) {
RBinString *new = R_NEW0 (RBinString);
if (!new) {
break;
}
new->type = str_type;
new->length = runes;
new->size = needle - str_start;
new->ordinal = count++;
// TODO: move into adjust_offset
switch (str_type) {
case R_STRING_TYPE_WIDE:
{
const ut8 *p = buf + str_start - 2;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
{
const ut8 *p = buf + str_start - 4;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
new->paddr = new->vaddr = str_start;
new->string = r_str_ndup ((const char *)tmp, i);
r_list_append (list, new);
} else {
// DUMP TO STDOUT. raw dumping for rabin2 -zzz
printf ("0x%08" PFMT64x " %s\n", str_start, tmp);
}
}
}
return count;
} | static int string_scan_range(RList *list, const ut8 *buf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (!buf || !min) {
return -1;
}
while (needle < to) {
rc = r_utf8_decode (buf + needle, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc;
if ((to - needle) > 4) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r)) {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\e", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 28) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e"[r];
} else {
// string too long
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
// reduce false positives
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
if (list) {
RBinString *new = R_NEW0 (RBinString);
if (!new) {
break;
}
new->type = str_type;
new->length = runes;
new->size = needle - str_start;
new->ordinal = count++;
// TODO: move into adjust_offset
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start > 1) {
const ut8 *p = buf + str_start - 2;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start > 3) {
const ut8 *p = buf + str_start - 4;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
new->paddr = new->vaddr = str_start;
new->string = r_str_ndup ((const char *)tmp, i);
r_list_append (list, new);
} else {
// DUMP TO STDOUT. raw dumping for rabin2 -zzz
printf ("0x%08" PFMT64x " %s\n", str_start, tmp);
}
}
}
return count;
} | {
"deleted": [
{
"line_no": 123,
"char_start": 2779,
"char_end": 2786,
"line": "\t\t\t\t\t{\n"
},
{
"line_no": 124,
"char_start": 2786,
"char_end": 2829,
"line": "\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n"
},
{
"line_no": 131,
"char_start": 2964,
"char_end": 2971,
"line": "\t\t\t\t\t{\n"
},
{
"line_no": 132,
"char_start": 2971,
"char_end": 3014,
"line": "\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n"
}
],
"added": [
{
"line_no": 123,
"char_start": 2779,
"char_end": 2805,
"line": "\t\t\t\t\tif (str_start > 1) {\n"
},
{
"line_no": 124,
"char_start": 2805,
"char_end": 2847,
"line": "\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n"
},
{
"line_no": 131,
"char_start": 2982,
"char_end": 3008,
"line": "\t\t\t\t\tif (str_start > 3) {\n"
},
{
"line_no": 132,
"char_start": 3008,
"char_end": 3050,
"line": "\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n"
}
]
} | {
"deleted": [
{
"char_start": 2810,
"char_end": 2811,
"chars": " "
},
{
"char_start": 2995,
"char_end": 2996,
"chars": " "
}
],
"added": [
{
"char_start": 2784,
"char_end": 2803,
"chars": "if (str_start > 1) "
},
{
"char_start": 2987,
"char_end": 3006,
"chars": "if (str_start > 3) "
}
]
} | github.com/radare/radare2/commit/d31c4d3cbdbe01ea3ded16a584de94149ecd31d9 | libr/bin/bin.c | cwe-125 |
ReadMATImage | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
} | static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
} | {
"deleted": [],
"added": [
{
"line_no": 336,
"char_start": 12091,
"char_end": 12142,
"line": " quantum_info=DestroyQuantumInfo(quantum_info);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 12091,
"char_end": 12142,
"chars": " quantum_info=DestroyQuantumInfo(quantum_info);\n"
}
]
} | github.com/ImageMagick/ImageMagick/commit/b173a352397877775c51c9a0e9d59eb6ce24c455 | coders/mat.c | cwe-125 |
bitmap_cache_new | rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)
{
int i;
rdpBitmapCache* bitmapCache;
bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));
if (!bitmapCache)
return NULL;
bitmapCache->settings = settings;
bitmapCache->update = ((freerdp*)settings->instance)->update;
bitmapCache->context = bitmapCache->update->context;
bitmapCache->maxCells = settings->BitmapCacheV2NumCells;
bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));
if (!bitmapCache->cells)
goto fail;
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;
/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */
bitmapCache->cells[i].entries =
(rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));
if (!bitmapCache->cells[i].entries)
goto fail;
}
return bitmapCache;
fail:
if (bitmapCache->cells)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
free(bitmapCache->cells[i].entries);
}
free(bitmapCache);
return NULL;
} | rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)
{
int i;
rdpBitmapCache* bitmapCache;
bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));
if (!bitmapCache)
return NULL;
bitmapCache->settings = settings;
bitmapCache->update = ((freerdp*)settings->instance)->update;
bitmapCache->context = bitmapCache->update->context;
bitmapCache->cells =
(BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));
if (!bitmapCache->cells)
goto fail;
bitmapCache->maxCells = settings->BitmapCacheV2NumCells;
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;
/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */
bitmapCache->cells[i].entries =
(rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));
if (!bitmapCache->cells[i].entries)
goto fail;
}
return bitmapCache;
fail:
if (bitmapCache->cells)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
free(bitmapCache->cells[i].entries);
}
free(bitmapCache);
return NULL;
} | {
"deleted": [
{
"line_no": 13,
"char_start": 351,
"char_end": 409,
"line": "\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n"
},
{
"line_no": 14,
"char_start": 409,
"char_end": 503,
"line": "\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 351,
"char_end": 373,
"line": "\tbitmapCache->cells =\n"
},
{
"line_no": 14,
"char_start": 373,
"char_end": 460,
"line": "\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n"
},
{
"line_no": 18,
"char_start": 500,
"char_end": 558,
"line": "\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n"
}
]
} | {
"deleted": [
{
"char_start": 365,
"char_end": 369,
"chars": "maxC"
},
{
"char_start": 375,
"char_end": 408,
"chars": " settings->BitmapCacheV2NumCells;"
},
{
"char_start": 410,
"char_end": 428,
"chars": "bitmapCache->cells"
},
{
"char_start": 429,
"char_end": 430,
"chars": "="
},
{
"char_start": 455,
"char_end": 456,
"chars": "b"
},
{
"char_start": 466,
"char_end": 468,
"chars": "->"
},
{
"char_start": 469,
"char_end": 471,
"chars": "ax"
}
],
"added": [
{
"char_start": 365,
"char_end": 366,
"chars": "c"
},
{
"char_start": 374,
"char_end": 376,
"chars": " "
},
{
"char_start": 402,
"char_end": 413,
"chars": "settings->B"
},
{
"char_start": 423,
"char_end": 427,
"chars": "V2Nu"
},
{
"char_start": 498,
"char_end": 556,
"chars": ";\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells"
}
]
} | github.com/FreeRDP/FreeRDP/commit/58dc36b3c883fd460199cedb6d30e58eba58298c | libfreerdp/cache/bitmap.c | cwe-125 |
ImagingPcxDecode | ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
UINT8 n;
UINT8* ptr;
if ((state->xsize * state->bits + 7) / 8 > state->bytes) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
ptr = buf;
for (;;) {
if (bytes < 1)
return ptr - buf;
if ((*ptr & 0xC0) == 0xC0) {
/* Run */
if (bytes < 2)
return ptr - buf;
n = ptr[0] & 0x3F;
while (n > 0) {
if (state->x >= state->bytes) {
state->errcode = IMAGING_CODEC_OVERRUN;
break;
}
state->buffer[state->x++] = ptr[1];
n--;
}
ptr += 2; bytes -= 2;
} else {
/* Literal */
state->buffer[state->x++] = ptr[0];
ptr++; bytes--;
}
if (state->x >= state->bytes) {
if (state->bytes % state->xsize && state->bytes > state->xsize) {
int bands = state->bytes / state->xsize;
int stride = state->bytes / bands;
int i;
for (i=1; i< bands; i++) { // note -- skipping first band
memmove(&state->buffer[i*state->xsize],
&state->buffer[i*stride],
state->xsize);
}
}
/* Got a full line, unpack it */
state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->buffer,
state->xsize);
state->x = 0;
if (++state->y >= state->ysize) {
/* End of file (errcode = 0) */
return -1;
}
}
}
} | ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
UINT8 n;
UINT8* ptr;
if ((state->xsize * state->bits + 7) / 8 > state->bytes) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
ptr = buf;
for (;;) {
if (bytes < 1)
return ptr - buf;
if ((*ptr & 0xC0) == 0xC0) {
/* Run */
if (bytes < 2)
return ptr - buf;
n = ptr[0] & 0x3F;
while (n > 0) {
if (state->x >= state->bytes) {
state->errcode = IMAGING_CODEC_OVERRUN;
break;
}
state->buffer[state->x++] = ptr[1];
n--;
}
ptr += 2; bytes -= 2;
} else {
/* Literal */
state->buffer[state->x++] = ptr[0];
ptr++; bytes--;
}
if (state->x >= state->bytes) {
if (state->bytes % state->xsize && state->bytes > state->xsize) {
int bands = state->bytes / state->xsize;
int stride = state->bytes / bands;
int i;
for (i=1; i< bands; i++) { // note -- skipping first band
memmove(&state->buffer[i*state->xsize],
&state->buffer[i*stride],
state->xsize);
}
}
/* Got a full line, unpack it */
state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->buffer,
state->xsize);
state->x = 0;
if (++state->y >= state->ysize) {
/* End of file (errcode = 0) */
return -1;
}
}
}
} | {
"deleted": [
{
"line_no": 6,
"char_start": 116,
"char_end": 179,
"line": " if (strcmp(im->mode, \"1\") == 0 && state->xsize > state->bytes * 8) {\n"
},
{
"line_no": 7,
"char_start": 179,
"char_end": 227,
"line": " state->errcode = IMAGING_CODEC_OVERRUN;\n"
},
{
"line_no": 8,
"char_start": 227,
"char_end": 246,
"line": " return -1;\n"
},
{
"line_no": 9,
"char_start": 246,
"char_end": 252,
"line": " } else if (strcmp(im->mode, \"P\") == 0 && state->xsize > state->bytes) {\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 116,
"char_end": 179,
"line": " if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n"
}
]
} | {
"deleted": [],
"added": []
} | github.com/python-pillow/Pillow/commit/6a83e4324738bb0452fbe8074a995b1c73f08de7#diff-9478f2787e3ae9668a15123b165c23ac | src/libImaging/PcxDecode.c | cwe-125 |
glyph_cache_put | BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
rdpGlyph* prevGlyph;
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return FALSE;
}
if (index > glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
return FALSE;
}
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
prevGlyph = glyphCache->glyphCache[id].entries[index];
if (prevGlyph)
prevGlyph->Free(glyphCache->context, prevGlyph);
glyphCache->glyphCache[id].entries[index] = glyph;
return TRUE;
} | BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
rdpGlyph* prevGlyph;
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return FALSE;
}
if (index >= glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
return FALSE;
}
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
prevGlyph = glyphCache->glyphCache[id].entries[index];
if (prevGlyph)
prevGlyph->Free(glyphCache->context, prevGlyph);
glyphCache->glyphCache[id].entries[index] = glyph;
return TRUE;
} | {
"deleted": [
{
"line_no": 11,
"char_start": 211,
"char_end": 259,
"line": "\tif (index > glyphCache->glyphCache[id].number)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 211,
"char_end": 260,
"line": "\tif (index >= glyphCache->glyphCache[id].number)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 223,
"char_end": 224,
"chars": "="
}
]
} | github.com/FreeRDP/FreeRDP/commit/c0fd449ec0870b050d350d6d844b1ea6dad4bc7d | libfreerdp/cache/glyph.c | cwe-125 |
read_Header | read_Header(struct archive_read *a, struct _7z_header_info *h,
int check_header_id)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7z_folder *folders;
struct _7z_stream_info *si = &(zip->si);
struct _7zip_entry *entries;
uint32_t folderIndex, indexInFolder;
unsigned i;
int eindex, empty_streams, sindex;
if (check_header_id) {
/*
* Read Header.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kHeader)
return (-1);
}
/*
* Read ArchiveProperties.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kArchiveProperties) {
for (;;) {
uint64_t size;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Read MainStreamsInfo.
*/
if (*p == kMainStreamsInfo) {
if (read_StreamsInfo(a, &(zip->si)) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kEnd)
return (0);
/*
* Read FilesInfo.
*/
if (*p != kFilesInfo)
return (-1);
if (parse_7zip_uint64(a, &(zip->numFiles)) < 0)
return (-1);
if (UMAX_ENTRY < zip->numFiles)
return (-1);
zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries));
if (zip->entries == NULL)
return (-1);
entries = zip->entries;
empty_streams = 0;
for (;;) {
int type;
uint64_t size;
size_t ll;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kEnd)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
if (zip->header_bytes_remaining < size)
return (-1);
ll = (size_t)size;
switch (type) {
case kEmptyStream:
h->emptyStreamBools = calloc((size_t)zip->numFiles,
sizeof(*h->emptyStreamBools));
if (h->emptyStreamBools == NULL)
return (-1);
if (read_Bools(
a, h->emptyStreamBools, (size_t)zip->numFiles) < 0)
return (-1);
empty_streams = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools[i])
empty_streams++;
}
break;
case kEmptyFile:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
h->emptyFileBools = calloc(empty_streams,
sizeof(*h->emptyFileBools));
if (h->emptyFileBools == NULL)
return (-1);
if (read_Bools(a, h->emptyFileBools, empty_streams) < 0)
return (-1);
break;
case kAnti:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
h->antiBools = calloc(empty_streams,
sizeof(*h->antiBools));
if (h->antiBools == NULL)
return (-1);
if (read_Bools(a, h->antiBools, empty_streams) < 0)
return (-1);
break;
case kCTime:
case kATime:
case kMTime:
if (read_Times(a, h, type) < 0)
return (-1);
break;
case kName:
{
unsigned char *np;
size_t nl, nb;
/* Skip one byte. */
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
ll--;
if ((ll & 1) || ll < zip->numFiles * 4)
return (-1);
zip->entry_names = malloc(ll);
if (zip->entry_names == NULL)
return (-1);
np = zip->entry_names;
nb = ll;
/*
* Copy whole file names.
* NOTE: This loop prevents from expanding
* the uncompressed buffer in order not to
* use extra memory resource.
*/
while (nb) {
size_t b;
if (nb > UBUFF_SIZE)
b = UBUFF_SIZE;
else
b = nb;
if ((p = header_bytes(a, b)) == NULL)
return (-1);
memcpy(np, p, b);
np += b;
nb -= b;
}
np = zip->entry_names;
nl = ll;
for (i = 0; i < zip->numFiles; i++) {
entries[i].utf16name = np;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
entries[i].wname = (wchar_t *)np;
#endif
/* Find a terminator. */
while (nl >= 2 && (np[0] || np[1])) {
np += 2;
nl -= 2;
}
if (nl < 2)
return (-1);/* Terminator not found */
entries[i].name_len = np - entries[i].utf16name;
np += 2;
nl -= 2;
}
break;
}
case kAttributes:
{
int allAreDefined;
if ((p = header_bytes(a, 2)) == NULL)
return (-1);
allAreDefined = *p;
h->attrBools = calloc((size_t)zip->numFiles,
sizeof(*h->attrBools));
if (h->attrBools == NULL)
return (-1);
if (allAreDefined)
memset(h->attrBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, h->attrBools,
(size_t)zip->numFiles) < 0)
return (-1);
}
for (i = 0; i < zip->numFiles; i++) {
if (h->attrBools[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
entries[i].attr = archive_le32dec(p);
}
}
break;
}
case kDummy:
if (ll == 0)
break;
default:
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
}
/*
* Set up entry's attributes.
*/
folders = si->ci.folders;
eindex = sindex = 0;
folderIndex = indexInFolder = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0)
entries[i].flg |= HAS_STREAM;
/* The high 16 bits of attributes is a posix file mode. */
entries[i].mode = entries[i].attr >> 16;
if (entries[i].flg & HAS_STREAM) {
if ((size_t)sindex >= si->ss.unpack_streams)
return (-1);
if (entries[i].mode == 0)
entries[i].mode = AE_IFREG | 0666;
if (si->ss.digestsDefined[sindex])
entries[i].flg |= CRC32_IS_SET;
entries[i].ssIndex = sindex;
sindex++;
} else {
int dir;
if (h->emptyFileBools == NULL)
dir = 1;
else {
if (h->emptyFileBools[eindex])
dir = 0;
else
dir = 1;
eindex++;
}
if (entries[i].mode == 0) {
if (dir)
entries[i].mode = AE_IFDIR | 0777;
else
entries[i].mode = AE_IFREG | 0666;
} else if (dir &&
(entries[i].mode & AE_IFMT) != AE_IFDIR) {
entries[i].mode &= ~AE_IFMT;
entries[i].mode |= AE_IFDIR;
}
if ((entries[i].mode & AE_IFMT) == AE_IFDIR &&
entries[i].name_len >= 2 &&
(entries[i].utf16name[entries[i].name_len-2] != '/' ||
entries[i].utf16name[entries[i].name_len-1] != 0)) {
entries[i].utf16name[entries[i].name_len] = '/';
entries[i].utf16name[entries[i].name_len+1] = 0;
entries[i].name_len += 2;
}
entries[i].ssIndex = -1;
}
if (entries[i].attr & 0x01)
entries[i].mode &= ~0222;/* Read only. */
if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) {
/*
* The entry is an empty file or a directory file,
* those both have no contents.
*/
entries[i].folderIndex = -1;
continue;
}
if (indexInFolder == 0) {
for (;;) {
if (folderIndex >= si->ci.numFolders)
return (-1);
if (folders[folderIndex].numUnpackStreams)
break;
folderIndex++;
}
}
entries[i].folderIndex = folderIndex;
if ((entries[i].flg & HAS_STREAM) == 0)
continue;
indexInFolder++;
if (indexInFolder >= folders[folderIndex].numUnpackStreams) {
folderIndex++;
indexInFolder = 0;
}
}
return (0);
} | read_Header(struct archive_read *a, struct _7z_header_info *h,
int check_header_id)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
const unsigned char *p;
struct _7z_folder *folders;
struct _7z_stream_info *si = &(zip->si);
struct _7zip_entry *entries;
uint32_t folderIndex, indexInFolder;
unsigned i;
int eindex, empty_streams, sindex;
if (check_header_id) {
/*
* Read Header.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p != kHeader)
return (-1);
}
/*
* Read ArchiveProperties.
*/
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == kArchiveProperties) {
for (;;) {
uint64_t size;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
if (*p == 0)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
/*
* Read MainStreamsInfo.
*/
if (*p == kMainStreamsInfo) {
if (read_StreamsInfo(a, &(zip->si)) < 0)
return (-1);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
}
if (*p == kEnd)
return (0);
/*
* Read FilesInfo.
*/
if (*p != kFilesInfo)
return (-1);
if (parse_7zip_uint64(a, &(zip->numFiles)) < 0)
return (-1);
if (UMAX_ENTRY < zip->numFiles)
return (-1);
zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries));
if (zip->entries == NULL)
return (-1);
entries = zip->entries;
empty_streams = 0;
for (;;) {
int type;
uint64_t size;
size_t ll;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kEnd)
break;
if (parse_7zip_uint64(a, &size) < 0)
return (-1);
if (zip->header_bytes_remaining < size)
return (-1);
ll = (size_t)size;
switch (type) {
case kEmptyStream:
if (h->emptyStreamBools != NULL)
return (-1);
h->emptyStreamBools = calloc((size_t)zip->numFiles,
sizeof(*h->emptyStreamBools));
if (h->emptyStreamBools == NULL)
return (-1);
if (read_Bools(
a, h->emptyStreamBools, (size_t)zip->numFiles) < 0)
return (-1);
empty_streams = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools[i])
empty_streams++;
}
break;
case kEmptyFile:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->emptyFileBools != NULL)
return (-1);
h->emptyFileBools = calloc(empty_streams,
sizeof(*h->emptyFileBools));
if (h->emptyFileBools == NULL)
return (-1);
if (read_Bools(a, h->emptyFileBools, empty_streams) < 0)
return (-1);
break;
case kAnti:
if (empty_streams <= 0) {
/* Unexcepted sequence. Skip this. */
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
if (h->antiBools != NULL)
return (-1);
h->antiBools = calloc(empty_streams,
sizeof(*h->antiBools));
if (h->antiBools == NULL)
return (-1);
if (read_Bools(a, h->antiBools, empty_streams) < 0)
return (-1);
break;
case kCTime:
case kATime:
case kMTime:
if (read_Times(a, h, type) < 0)
return (-1);
break;
case kName:
{
unsigned char *np;
size_t nl, nb;
/* Skip one byte. */
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
ll--;
if ((ll & 1) || ll < zip->numFiles * 4)
return (-1);
if (zip->entry_names != NULL)
return (-1);
zip->entry_names = malloc(ll);
if (zip->entry_names == NULL)
return (-1);
np = zip->entry_names;
nb = ll;
/*
* Copy whole file names.
* NOTE: This loop prevents from expanding
* the uncompressed buffer in order not to
* use extra memory resource.
*/
while (nb) {
size_t b;
if (nb > UBUFF_SIZE)
b = UBUFF_SIZE;
else
b = nb;
if ((p = header_bytes(a, b)) == NULL)
return (-1);
memcpy(np, p, b);
np += b;
nb -= b;
}
np = zip->entry_names;
nl = ll;
for (i = 0; i < zip->numFiles; i++) {
entries[i].utf16name = np;
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
entries[i].wname = (wchar_t *)np;
#endif
/* Find a terminator. */
while (nl >= 2 && (np[0] || np[1])) {
np += 2;
nl -= 2;
}
if (nl < 2)
return (-1);/* Terminator not found */
entries[i].name_len = np - entries[i].utf16name;
np += 2;
nl -= 2;
}
break;
}
case kAttributes:
{
int allAreDefined;
if ((p = header_bytes(a, 2)) == NULL)
return (-1);
allAreDefined = *p;
if (h->attrBools != NULL)
return (-1);
h->attrBools = calloc((size_t)zip->numFiles,
sizeof(*h->attrBools));
if (h->attrBools == NULL)
return (-1);
if (allAreDefined)
memset(h->attrBools, 1, (size_t)zip->numFiles);
else {
if (read_Bools(a, h->attrBools,
(size_t)zip->numFiles) < 0)
return (-1);
}
for (i = 0; i < zip->numFiles; i++) {
if (h->attrBools[i]) {
if ((p = header_bytes(a, 4)) == NULL)
return (-1);
entries[i].attr = archive_le32dec(p);
}
}
break;
}
case kDummy:
if (ll == 0)
break;
default:
if (header_bytes(a, ll) == NULL)
return (-1);
break;
}
}
/*
* Set up entry's attributes.
*/
folders = si->ci.folders;
eindex = sindex = 0;
folderIndex = indexInFolder = 0;
for (i = 0; i < zip->numFiles; i++) {
if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0)
entries[i].flg |= HAS_STREAM;
/* The high 16 bits of attributes is a posix file mode. */
entries[i].mode = entries[i].attr >> 16;
if (entries[i].flg & HAS_STREAM) {
if ((size_t)sindex >= si->ss.unpack_streams)
return (-1);
if (entries[i].mode == 0)
entries[i].mode = AE_IFREG | 0666;
if (si->ss.digestsDefined[sindex])
entries[i].flg |= CRC32_IS_SET;
entries[i].ssIndex = sindex;
sindex++;
} else {
int dir;
if (h->emptyFileBools == NULL)
dir = 1;
else {
if (h->emptyFileBools[eindex])
dir = 0;
else
dir = 1;
eindex++;
}
if (entries[i].mode == 0) {
if (dir)
entries[i].mode = AE_IFDIR | 0777;
else
entries[i].mode = AE_IFREG | 0666;
} else if (dir &&
(entries[i].mode & AE_IFMT) != AE_IFDIR) {
entries[i].mode &= ~AE_IFMT;
entries[i].mode |= AE_IFDIR;
}
if ((entries[i].mode & AE_IFMT) == AE_IFDIR &&
entries[i].name_len >= 2 &&
(entries[i].utf16name[entries[i].name_len-2] != '/' ||
entries[i].utf16name[entries[i].name_len-1] != 0)) {
entries[i].utf16name[entries[i].name_len] = '/';
entries[i].utf16name[entries[i].name_len+1] = 0;
entries[i].name_len += 2;
}
entries[i].ssIndex = -1;
}
if (entries[i].attr & 0x01)
entries[i].mode &= ~0222;/* Read only. */
if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) {
/*
* The entry is an empty file or a directory file,
* those both have no contents.
*/
entries[i].folderIndex = -1;
continue;
}
if (indexInFolder == 0) {
for (;;) {
if (folderIndex >= si->ci.numFolders)
return (-1);
if (folders[folderIndex].numUnpackStreams)
break;
folderIndex++;
}
}
entries[i].folderIndex = folderIndex;
if ((entries[i].flg & HAS_STREAM) == 0)
continue;
indexInFolder++;
if (indexInFolder >= folders[folderIndex].numUnpackStreams) {
folderIndex++;
indexInFolder = 0;
}
}
return (0);
} | {
"deleted": [],
"added": [
{
"line_no": 90,
"char_start": 1753,
"char_end": 1789,
"line": "\t\t\tif (h->emptyStreamBools != NULL)\n"
},
{
"line_no": 91,
"char_start": 1789,
"char_end": 1806,
"line": "\t\t\t\treturn (-1);\n"
},
{
"line_no": 112,
"char_start": 2340,
"char_end": 2374,
"line": "\t\t\tif (h->emptyFileBools != NULL)\n"
},
{
"line_no": 113,
"char_start": 2374,
"char_end": 2391,
"line": "\t\t\t\treturn (-1);\n"
},
{
"line_no": 128,
"char_start": 2766,
"char_end": 2795,
"line": "\t\t\tif (h->antiBools != NULL)\n"
},
{
"line_no": 129,
"char_start": 2795,
"char_end": 2812,
"line": "\t\t\t\treturn (-1);\n"
},
{
"line_no": 156,
"char_start": 3330,
"char_end": 3363,
"line": "\t\t\tif (zip->entry_names != NULL)\n"
},
{
"line_no": 157,
"char_start": 3363,
"char_end": 3380,
"line": "\t\t\t\treturn (-1);\n"
},
{
"line_no": 210,
"char_start": 4491,
"char_end": 4520,
"line": "\t\t\tif (h->attrBools != NULL)\n"
},
{
"line_no": 211,
"char_start": 4520,
"char_end": 4537,
"line": "\t\t\t\treturn (-1);\n"
}
]
} | {
"deleted": [
{
"char_start": 1808,
"char_end": 1808,
"chars": ""
},
{
"char_start": 4268,
"char_end": 4268,
"chars": ""
}
],
"added": [
{
"char_start": 1756,
"char_end": 1809,
"chars": "if (h->emptyStreamBools != NULL)\n\t\t\t\treturn (-1);\n\t\t\t"
},
{
"char_start": 2340,
"char_end": 2391,
"chars": "\t\t\tif (h->emptyFileBools != NULL)\n\t\t\t\treturn (-1);\n"
},
{
"char_start": 2766,
"char_end": 2812,
"chars": "\t\t\tif (h->antiBools != NULL)\n\t\t\t\treturn (-1);\n"
},
{
"char_start": 3330,
"char_end": 3380,
"chars": "\t\t\tif (zip->entry_names != NULL)\n\t\t\t\treturn (-1);\n"
},
{
"char_start": 4489,
"char_end": 4535,
"chars": ";\n\t\t\tif (h->attrBools != NULL)\n\t\t\t\treturn (-1)"
}
]
} | github.com/libarchive/libarchive/commit/7f17c791dcfd8c0416e2cd2485b19410e47ef126 | libarchive/archive_read_support_format_7zip.c | cwe-125 |
ReadRLEImage | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == 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)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 64)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4);
pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == 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)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 64)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*number_planes_filled;
pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | {
"deleted": [
{
"line_no": 185,
"char_start": 4971,
"char_end": 5052,
"line": " if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes))\n"
},
{
"line_no": 187,
"char_start": 5125,
"char_end": 5202,
"line": " pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4);\n"
}
],
"added": [
{
"line_no": 50,
"char_start": 643,
"char_end": 669,
"line": " number_planes_filled,\n"
},
{
"line_no": 186,
"char_start": 4997,
"char_end": 5065,
"line": " number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n"
},
{
"line_no": 187,
"char_start": 5065,
"char_end": 5088,
"line": " number_planes+1;\n"
},
{
"line_no": 188,
"char_start": 5088,
"char_end": 5161,
"line": " if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n"
},
{
"line_no": 189,
"char_start": 5161,
"char_end": 5193,
"line": " number_planes_filled))\n"
},
{
"line_no": 191,
"char_start": 5266,
"char_end": 5337,
"line": " pixel_info_length=image->columns*image->rows*number_planes_filled;\n"
}
]
} | {
"deleted": [
{
"char_start": 5174,
"char_end": 5184,
"chars": "MagickMax("
},
{
"char_start": 5197,
"char_end": 5200,
"chars": ",4)"
}
],
"added": [
{
"char_start": 647,
"char_end": 673,
"chars": "number_planes_filled,\n "
},
{
"char_start": 5001,
"char_end": 5092,
"chars": "number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n "
},
{
"char_start": 5124,
"char_end": 5131,
"chars": "_filled"
},
{
"char_start": 5160,
"char_end": 5170,
"chars": "\n "
},
{
"char_start": 5183,
"char_end": 5190,
"chars": "_filled"
},
{
"char_start": 5328,
"char_end": 5335,
"chars": "_filled"
}
]
} | github.com/ImageMagick/ImageMagick/commit/2ad6d33493750a28a5a655d319a8e0b16c392de1 | coders/rle.c | cwe-125 |
HPHP::JSON_parser | bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
int depth, int64_t options) {
// No GC safepoints during JSON parsing, please. Code is not re-entrant.
NoHandleSurpriseScope no_surprise(SafepointFlags);
json_parser *json = s_json_parser.get(); /* the parser state */
// Clear and reuse the thread-local string buffers. They are only freed if
// they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
// is explicitly flushed (e.g., due to being idle).
json->initSb(length);
SCOPE_EXIT {
constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
};
// SimpleParser only handles the most common set of options. Also, only use it
// if its array nesting depth check is *more* restrictive than what the user
// asks for, to ensure that the precise semantics of the general case is
// applied for all nesting overflows.
if (assoc &&
options == (options & (k_JSON_FB_LOOSE |
k_JSON_FB_DARRAYS |
k_JSON_FB_DARRAYS_AND_VARRAYS |
k_JSON_FB_HACK_ARRAYS |
k_JSON_FB_THRIFT_SIMPLE_JSON |
k_JSON_FB_LEGACY_HACK_ARRAYS)) &&
depth >= SimpleParser::kMaxArrayDepth &&
length <= RuntimeOption::EvalSimpleJsonMaxLength &&
SimpleParser::TryParse(p, length, json->tl_buffer.tv, z,
get_container_type_from_options(options),
options & k_JSON_FB_THRIFT_SIMPLE_JSON)) {
return true;
}
int b; /* the next character */
int c; /* the next character class */
int s; /* the next state */
int state = 0;
/*<fb>*/
bool const loose = options & k_JSON_FB_LOOSE;
JSONContainerType const container_type =
get_container_type_from_options(options);
int qchr = 0;
int8_t const *byte_class;
int8_t const (*next_state_table)[32];
if (loose) {
byte_class = loose_ascii_class;
next_state_table = loose_state_transition_table;
} else {
byte_class = ascii_class;
next_state_table = state_transition_table;
}
/*</fb>*/
UncheckedBuffer *buf = &json->sb_buf;
UncheckedBuffer *key = &json->sb_key;
DataType type = kInvalidDataType;
unsigned short escaped_bytes = 0;
auto reset_type = [&] { type = kInvalidDataType; };
json->depth = depth;
// Since the stack is maintainined on a per request basis, for performance
// reasons, it only makes sense to expand if necessary and cycles are wasted
// contracting. Calls with a depth other than default should be rare.
if (depth > json->stack.size()) {
json->stack.resize(depth);
}
SCOPE_EXIT {
if (json->stack.empty()) return;
for (int i = 0; i <= json->mark; i++) {
json->stack[i].key.reset();
json->stack[i].val.unset();
}
json->mark = -1;
};
json->mark = json->top = -1;
push(json, Mode::DONE);
UTF8To16Decoder decoder(p, length, loose);
for (;;) {
b = decoder.decode();
// Fast-case most common transition: append a simple string character.
if (state == 3 && type == KindOfString) {
while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') {
buf->append((char)b);
b = decoder.decode();
}
}
if (b == UTF8_END) break; // UTF-8 decoding finishes successfully.
if (b == UTF8_ERROR) {
s_json_parser->error_code = JSON_ERROR_UTF8;
return false;
}
assertx(b >= 0);
if ((b & 127) == b) {
/*<fb>*/
c = byte_class[b];
/*</fb>*/
if (c <= S_ERR) {
s_json_parser->error_code = JSON_ERROR_CTRL_CHAR;
return false;
}
} else {
c = S_ETC;
}
/*
Get the next state from the transition table.
*/
/*<fb>*/
s = next_state_table[state][c];
if (s == -4) {
if (b != qchr) {
s = 3;
} else {
qchr = 0;
}
}
/*</fb>*/
if (s < 0) {
/*
Perform one of the predefined actions.
*/
switch (s) {
/*
empty }
*/
case -9:
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::KEY)) {
return false;
}
state = 9;
break;
/*
{
*/
case -8:
if (!push(json, Mode::KEY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 1;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
// stable_maps is meaningless
top = req::make<c_Map>();
} else {
/*</fb>*/
if (!assoc) {
top = SystemLib::AllocStdClassObject();
/* <fb> */
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateDict();
} else if (container_type == JSONContainerType::DARRAYS ||
container_type == JSONContainerType::DARRAYS_AND_VARRAYS)
{
top = Array::CreateDArray();
/* </fb> */
} else if (
container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyDictArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*<fb>*/
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
}
*/
case -7:
/*** BEGIN Facebook: json_utf8_loose ***/
/*
If this is a trailing comma in an object definition,
we're in Mode::KEY. In that case, throw that off the
stack and restore Mode::OBJECT so that we pretend the
trailing comma just didn't happen.
*/
if (loose) {
if (pop(json, Mode::KEY)) {
push(json, Mode::OBJECT);
}
}
/*** END Facebook: json_utf8_loose ***/
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::OBJECT) {
Variant mval;
json_create_zval(mval, *buf, type, options);
Variant &top = json->stack[json->top].val;
object_set(json, top, copy_and_clear(*key),
mval, assoc, container_type);
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key,
assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::OBJECT)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
break;
/*
[
*/
case -6:
if (!push(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 2;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
top = req::make<c_Vector>();
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateVec();
} else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) {
top = Array::CreateVArray();
} else if (container_type == JSONContainerType::DARRAYS) {
top = Array::CreateDArray();
} else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyVecArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
]
*/
case -5:
{
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::ARRAY) {
Variant mval;
json_create_zval(mval, *buf, type, options);
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc,
container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
}
break;
/*
"
*/
case -4:
switch (json->stack[json->top].mode) {
case Mode::KEY:
state = 27;
std::swap(buf, key);
reset_type();
break;
case Mode::ARRAY:
case Mode::OBJECT:
state = 9;
break;
case Mode::DONE:
if (type == KindOfString) {
z = copy_and_clear(*buf);
state = 9;
break;
}
/* fall through if not KindOfString */
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
break;
/*
,
*/
case -3:
{
Variant mval;
if (type != kInvalidDataType &&
(json->stack[json->top].mode == Mode::OBJECT ||
json->stack[json->top].mode == Mode::ARRAY)) {
json_create_zval(mval, *buf, type, options);
}
switch (json->stack[json->top].mode) {
case Mode::OBJECT:
if (pop(json, Mode::OBJECT) &&
push(json, Mode::KEY)) {
if (type != kInvalidDataType) {
Variant &top = json->stack[json->top].val;
object_set(
json,
top,
copy_and_clear(*key),
mval,
assoc,
container_type
);
}
state = 29;
}
break;
case Mode::ARRAY:
if (type != kInvalidDataType) {
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
}
state = 28;
break;
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
buf->clear();
reset_type();
check_non_safepoint_surprise();
}
break;
/*<fb>*/
/*
: (after unquoted string)
*/
case -10:
if (json->stack[json->top].mode == Mode::KEY) {
state = 27;
std::swap(buf, key);
reset_type();
s = -2;
} else {
s = 3;
break;
}
/*</fb>*/
/*
:
*/
case -2:
if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) {
state = 28;
break;
}
/*
syntax error
*/
case -1:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
/*
Change the state and iterate.
*/
bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON;
if (type == KindOfString) {
if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ &&
state != 8) {
if (state != 4) {
utf16_to_utf8(*buf, b);
} else {
switch (b) {
case 'b': buf->append('\b'); break;
case 't': buf->append('\t'); break;
case 'n': buf->append('\n'); break;
case 'f': buf->append('\f'); break;
case 'r': buf->append('\r'); break;
default:
utf16_to_utf8(*buf, b);
break;
}
}
} else if (s == 6) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
escaped_bytes = 0;
} else {
escaped_bytes = dehexchar(b) << 12;
}
} else if (s == 7) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
escaped_bytes += dehexchar(b) << 8;
}
} else if (s == 8) {
escaped_bytes += dehexchar(b) << 4;
} else if (s == 3 && state == 8) {
escaped_bytes += dehexchar(b);
if (UNLIKELY(is_tsimplejson)) {
buf->append((char)escaped_bytes);
} else {
utf16_to_utf8(*buf, escaped_bytes);
}
}
} else if ((type == kInvalidDataType || type == KindOfNull) &&
(c == S_DIG || c == S_ZER)) {
type = KindOfInt64;
buf->append((char)b);
} else if (type == KindOfInt64 && s == 24) {
type = KindOfDouble;
buf->append((char)b);
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64) &&
c == S_DOT) {
type = KindOfDouble;
buf->append((char)b);
} else if (type != KindOfString && c == S_QUO) {
type = KindOfString;
/*<fb>*/qchr = b;/*</fb>*/
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64 || type == KindOfDouble) &&
((state == 12 && s == 9) ||
(state == 16 && s == 9))) {
type = KindOfBoolean;
} else if (type == kInvalidDataType && state == 19 && s == 9) {
type = KindOfNull;
} else if (type != KindOfString && c > S_WSP) {
utf16_to_utf8(*buf, b);
}
state = s;
}
}
if (state == 9 && pop(json, Mode::DONE)) {
s_json_parser->error_code = JSON_ERROR_NONE;
return true;
}
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
} | bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
int depth, int64_t options) {
// No GC safepoints during JSON parsing, please. Code is not re-entrant.
NoHandleSurpriseScope no_surprise(SafepointFlags);
json_parser *json = s_json_parser.get(); /* the parser state */
// Clear and reuse the thread-local string buffers. They are only freed if
// they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
// is explicitly flushed (e.g., due to being idle).
json->initSb(length);
if (depth <= 0) {
json->error_code = json_error_codes::JSON_ERROR_DEPTH;
return false;
}
SCOPE_EXIT {
constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
};
// SimpleParser only handles the most common set of options. Also, only use it
// if its array nesting depth check is *more* restrictive than what the user
// asks for, to ensure that the precise semantics of the general case is
// applied for all nesting overflows.
if (assoc &&
options == (options & (k_JSON_FB_LOOSE |
k_JSON_FB_DARRAYS |
k_JSON_FB_DARRAYS_AND_VARRAYS |
k_JSON_FB_HACK_ARRAYS |
k_JSON_FB_THRIFT_SIMPLE_JSON |
k_JSON_FB_LEGACY_HACK_ARRAYS)) &&
depth >= SimpleParser::kMaxArrayDepth &&
length <= RuntimeOption::EvalSimpleJsonMaxLength &&
SimpleParser::TryParse(p, length, json->tl_buffer.tv, z,
get_container_type_from_options(options),
options & k_JSON_FB_THRIFT_SIMPLE_JSON)) {
return true;
}
int b; /* the next character */
int c; /* the next character class */
int s; /* the next state */
int state = 0;
/*<fb>*/
bool const loose = options & k_JSON_FB_LOOSE;
JSONContainerType const container_type =
get_container_type_from_options(options);
int qchr = 0;
int8_t const *byte_class;
int8_t const (*next_state_table)[32];
if (loose) {
byte_class = loose_ascii_class;
next_state_table = loose_state_transition_table;
} else {
byte_class = ascii_class;
next_state_table = state_transition_table;
}
/*</fb>*/
UncheckedBuffer *buf = &json->sb_buf;
UncheckedBuffer *key = &json->sb_key;
DataType type = kInvalidDataType;
unsigned short escaped_bytes = 0;
auto reset_type = [&] { type = kInvalidDataType; };
json->depth = depth;
// Since the stack is maintainined on a per request basis, for performance
// reasons, it only makes sense to expand if necessary and cycles are wasted
// contracting. Calls with a depth other than default should be rare.
if (depth > json->stack.size()) {
json->stack.resize(depth);
}
SCOPE_EXIT {
if (json->stack.empty()) return;
for (int i = 0; i <= json->mark; i++) {
json->stack[i].key.reset();
json->stack[i].val.unset();
}
json->mark = -1;
};
json->mark = json->top = -1;
push(json, Mode::DONE);
UTF8To16Decoder decoder(p, length, loose);
for (;;) {
b = decoder.decode();
// Fast-case most common transition: append a simple string character.
if (state == 3 && type == KindOfString) {
while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') {
buf->append((char)b);
b = decoder.decode();
}
}
if (b == UTF8_END) break; // UTF-8 decoding finishes successfully.
if (b == UTF8_ERROR) {
s_json_parser->error_code = JSON_ERROR_UTF8;
return false;
}
assertx(b >= 0);
if ((b & 127) == b) {
/*<fb>*/
c = byte_class[b];
/*</fb>*/
if (c <= S_ERR) {
s_json_parser->error_code = JSON_ERROR_CTRL_CHAR;
return false;
}
} else {
c = S_ETC;
}
/*
Get the next state from the transition table.
*/
/*<fb>*/
s = next_state_table[state][c];
if (s == -4) {
if (b != qchr) {
s = 3;
} else {
qchr = 0;
}
}
/*</fb>*/
if (s < 0) {
/*
Perform one of the predefined actions.
*/
switch (s) {
/*
empty }
*/
case -9:
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::KEY)) {
return false;
}
state = 9;
break;
/*
{
*/
case -8:
if (!push(json, Mode::KEY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 1;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
// stable_maps is meaningless
top = req::make<c_Map>();
} else {
/*</fb>*/
if (!assoc) {
top = SystemLib::AllocStdClassObject();
/* <fb> */
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateDict();
} else if (container_type == JSONContainerType::DARRAYS ||
container_type == JSONContainerType::DARRAYS_AND_VARRAYS)
{
top = Array::CreateDArray();
/* </fb> */
} else if (
container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyDictArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*<fb>*/
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
}
*/
case -7:
/*** BEGIN Facebook: json_utf8_loose ***/
/*
If this is a trailing comma in an object definition,
we're in Mode::KEY. In that case, throw that off the
stack and restore Mode::OBJECT so that we pretend the
trailing comma just didn't happen.
*/
if (loose) {
if (pop(json, Mode::KEY)) {
push(json, Mode::OBJECT);
}
}
/*** END Facebook: json_utf8_loose ***/
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::OBJECT) {
Variant mval;
json_create_zval(mval, *buf, type, options);
Variant &top = json->stack[json->top].val;
object_set(json, top, copy_and_clear(*key),
mval, assoc, container_type);
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key,
assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::OBJECT)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
break;
/*
[
*/
case -6:
if (!push(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 2;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
top = req::make<c_Vector>();
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateVec();
} else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) {
top = Array::CreateVArray();
} else if (container_type == JSONContainerType::DARRAYS) {
top = Array::CreateDArray();
} else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyVecArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
]
*/
case -5:
{
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::ARRAY) {
Variant mval;
json_create_zval(mval, *buf, type, options);
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc,
container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
}
break;
/*
"
*/
case -4:
switch (json->stack[json->top].mode) {
case Mode::KEY:
state = 27;
std::swap(buf, key);
reset_type();
break;
case Mode::ARRAY:
case Mode::OBJECT:
state = 9;
break;
case Mode::DONE:
if (type == KindOfString) {
z = copy_and_clear(*buf);
state = 9;
break;
}
/* fall through if not KindOfString */
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
break;
/*
,
*/
case -3:
{
Variant mval;
if (type != kInvalidDataType &&
(json->stack[json->top].mode == Mode::OBJECT ||
json->stack[json->top].mode == Mode::ARRAY)) {
json_create_zval(mval, *buf, type, options);
}
switch (json->stack[json->top].mode) {
case Mode::OBJECT:
if (pop(json, Mode::OBJECT) &&
push(json, Mode::KEY)) {
if (type != kInvalidDataType) {
Variant &top = json->stack[json->top].val;
object_set(
json,
top,
copy_and_clear(*key),
mval,
assoc,
container_type
);
}
state = 29;
}
break;
case Mode::ARRAY:
if (type != kInvalidDataType) {
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
}
state = 28;
break;
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
buf->clear();
reset_type();
check_non_safepoint_surprise();
}
break;
/*<fb>*/
/*
: (after unquoted string)
*/
case -10:
if (json->stack[json->top].mode == Mode::KEY) {
state = 27;
std::swap(buf, key);
reset_type();
s = -2;
} else {
s = 3;
break;
}
/*</fb>*/
/*
:
*/
case -2:
if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) {
state = 28;
break;
}
/*
syntax error
*/
case -1:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
/*
Change the state and iterate.
*/
bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON;
if (type == KindOfString) {
if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ &&
state != 8) {
if (state != 4) {
utf16_to_utf8(*buf, b);
} else {
switch (b) {
case 'b': buf->append('\b'); break;
case 't': buf->append('\t'); break;
case 'n': buf->append('\n'); break;
case 'f': buf->append('\f'); break;
case 'r': buf->append('\r'); break;
default:
utf16_to_utf8(*buf, b);
break;
}
}
} else if (s == 6) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
escaped_bytes = 0;
} else {
escaped_bytes = dehexchar(b) << 12;
}
} else if (s == 7) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
escaped_bytes += dehexchar(b) << 8;
}
} else if (s == 8) {
escaped_bytes += dehexchar(b) << 4;
} else if (s == 3 && state == 8) {
escaped_bytes += dehexchar(b);
if (UNLIKELY(is_tsimplejson)) {
buf->append((char)escaped_bytes);
} else {
utf16_to_utf8(*buf, escaped_bytes);
}
}
} else if ((type == kInvalidDataType || type == KindOfNull) &&
(c == S_DIG || c == S_ZER)) {
type = KindOfInt64;
buf->append((char)b);
} else if (type == KindOfInt64 && s == 24) {
type = KindOfDouble;
buf->append((char)b);
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64) &&
c == S_DOT) {
type = KindOfDouble;
buf->append((char)b);
} else if (type != KindOfString && c == S_QUO) {
type = KindOfString;
/*<fb>*/qchr = b;/*</fb>*/
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64 || type == KindOfDouble) &&
((state == 12 && s == 9) ||
(state == 16 && s == 9))) {
type = KindOfBoolean;
} else if (type == kInvalidDataType && state == 19 && s == 9) {
type = KindOfNull;
} else if (type != KindOfString && c > S_WSP) {
utf16_to_utf8(*buf, b);
}
state = s;
}
}
if (state == 9 && pop(json, Mode::DONE)) {
s_json_parser->error_code = JSON_ERROR_NONE;
return true;
}
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
} | {
"deleted": [],
"added": [
{
"line_no": 11,
"char_start": 548,
"char_end": 568,
"line": " if (depth <= 0) {\n"
},
{
"line_no": 12,
"char_start": 568,
"char_end": 627,
"line": " json->error_code = json_error_codes::JSON_ERROR_DEPTH;\n"
},
{
"line_no": 13,
"char_start": 627,
"char_end": 645,
"line": " return false;\n"
},
{
"line_no": 14,
"char_start": 645,
"char_end": 649,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 550,
"char_end": 651,
"chars": "if (depth <= 0) {\n json->error_code = json_error_codes::JSON_ERROR_DEPTH;\n return false;\n }\n "
}
]
} | github.com/facebook/hhvm/commit/dabd48caf74995e605f1700344f1ff4a5d83441d | hphp/runtime/ext/json/JSON_parser.cpp | cwe-125 |
jpc_pi_nextrpcl | static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
} | static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
} | {
"deleted": [
{
"line_no": 30,
"char_start": 656,
"char_end": 710,
"line": "\t\t\t\tif (pirlvl->prcwidthexpn + pi->picomp->numrlvls >\n"
},
{
"line_no": 32,
"char_start": 746,
"char_end": 799,
"line": "\t\t\t\t pirlvl->prcheightexpn + pi->picomp->numrlvls >\n"
}
],
"added": [
{
"line_no": 30,
"char_start": 656,
"char_end": 706,
"line": "\t\t\t\tif (pirlvl->prcwidthexpn + picomp->numrlvls >\n"
},
{
"line_no": 32,
"char_start": 742,
"char_end": 791,
"line": "\t\t\t\t pirlvl->prcheightexpn + picomp->numrlvls >\n"
}
]
} | {
"deleted": [
{
"char_start": 689,
"char_end": 693,
"chars": "->pi"
},
{
"char_start": 776,
"char_end": 780,
"chars": "pi->"
}
],
"added": []
} | github.com/mdadams/jasper/commit/f25486c3d4aa472fec79150f2c41ed4333395d3d | src/libjasper/jpc/jpc_t2cod.c | cwe-125 |
match_at | match_at(regex_t* reg, const UChar* str, const UChar* end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar* right_range,
#endif
const UChar* sstart, UChar* sprev, OnigMatchArg* msa)
{
static UChar FinishCode[] = { OP_FINISH };
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *sbegin;
int is_alloca;
char *alloc_base;
OnigStackType *stk_base, *stk, *stk_end;
OnigStackType *stkp; /* used as any purpose. */
OnigStackIndex si;
OnigStackIndex *repeat_stk;
OnigStackIndex *mem_start_stk, *mem_end_stk;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
int scv;
unsigned char* state_check_buff = msa->state_check_buff;
int num_comb_exp_check = reg->num_comb_exp_check;
#endif
UChar *p = reg->p;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
//n = reg->num_repeat + reg->num_mem * 2;
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n",
(int )str, (int )end, (int )sstart, (int )sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */
best_len = ONIG_MISMATCH;
s = (UChar* )sstart;
while (1) {
#ifdef ONIG_DEBUG_MATCH
{
UChar *q, *bp, buf[50];
int len;
fprintf(stderr, "%4d> \"", (int )(s - str));
bp = buf;
for (i = 0, q = s; i < 7 && q < end; i++) {
len = enclen(encode, q);
while (len-- > 0) *bp++ = *q++;
}
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }
else { xmemcpy(bp, "\"", 1); bp += 1; }
*bp = 0;
fputs((char* )buf, stderr);
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);
onig_print_compiled_byte_code(stderr, p, NULL, encode);
fprintf(stderr, "\n");
}
#endif
sbegin = s;
switch (*p++) {
case OP_END: MOP_IN(OP_END);
n = s - sstart;
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = sstart - str;
rmt[0].rm_eo = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str;
rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = sstart - str;
region->end[0] = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str;
region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = sstart - str;
node->end = s - str;
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
MOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
break;
case OP_EXACT1: MOP_IN(OP_EXACT1);
#if 0
DATA_ENSURE(1);
if (*p != *s) goto fail;
p++; s++;
#endif
if (*p != *s++) goto fail;
DATA_ENSURE(0);
p++;
MOP_OUT;
break;
case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC);
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) {
goto fail;
}
p++; q++;
}
}
MOP_OUT;
break;
case OP_EXACT2: MOP_IN(OP_EXACT2);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT3: MOP_IN(OP_EXACT3);
DATA_ENSURE(3);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT4: MOP_IN(OP_EXACT4);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT5: MOP_IN(OP_EXACT5);
DATA_ENSURE(5);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTN: MOP_IN(OP_EXACTN);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen);
while (tlen-- > 0) {
if (*p++ != *s++) goto fail;
}
sprev = s - 1;
MOP_OUT;
continue;
break;
case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC);
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
GET_LENGTH_INC(tlen, p);
endp = p + tlen;
while (p < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) goto fail;
p++; q++;
}
}
}
MOP_OUT;
continue;
break;
case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3);
DATA_ENSURE(6);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 2);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 2;
MOP_OUT;
continue;
break;
case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 3);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 3;
MOP_OUT;
continue;
break;
case OP_EXACTMBN: MOP_IN(OP_EXACTMBN);
GET_LENGTH_INC(tlen, p); /* mb-len */
GET_LENGTH_INC(tlen2, p); /* string len */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
while (tlen2-- > 0) {
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - tlen;
MOP_OUT;
continue;
break;
case OP_CCLASS: MOP_IN(OP_CCLASS);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */
MOP_OUT;
break;
case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (! onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (! onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
MOP_OUT;
break;
case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) == 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
GET_LENGTH_INC(tlen, p);
p += tlen;
goto cc_mb_not_success;
}
cclass_mb_not:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
p += tlen;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
cc_mb_not_success:
MOP_OUT;
break;
case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb_not;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) != 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE);
{
OnigCodePoint code;
void *node;
int mb_len;
UChar *ss;
DATA_ENSURE(1);
GET_POINTER_INC(node, p);
mb_len = enclen(encode, s);
ss = s;
s += mb_len;
DATA_ENSURE(0);
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail;
}
MOP_OUT;
break;
case OP_ANYCHAR: MOP_IN(OP_ANYCHAR);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
p++;
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
p++;
MOP_OUT;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_STATE_CHECK_ANYCHAR_ML_STAR:
MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_WORD: MOP_IN(OP_WORD);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_NOT_WORD: MOP_IN(OP_NOT_WORD);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (! ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
== ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
!= ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
#ifdef USE_WORD_BEGIN_END
case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN);
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) {
if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
case OP_WORD_END: MOP_IN(OP_WORD_END);
if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
#endif
case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF);
if (! ON_STR_BEGIN(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_END_BUF: MOP_IN(OP_END_BUF);
if (! ON_STR_END(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE);
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
MOP_OUT;
continue;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
MOP_OUT;
continue;
}
goto fail;
break;
case OP_END_LINE: MOP_IN(OP_END_LINE);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
MOP_OUT;
continue;
}
#endif
goto fail;
break;
case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
MOP_OUT;
continue;
}
}
#endif
goto fail;
break;
case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION);
if (s != msa->start)
goto fail;
MOP_OUT;
continue;
break;
case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_START(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_START: MOP_IN(OP_MEMORY_START);
GET_MEMNUM_INC(mem, p);
mem_start_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_END(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END: MOP_IN(OP_MEMORY_END);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
#ifdef USE_SUBEXP_CALL
case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC);
GET_MEMNUM_INC(mem, p);
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
MOP_OUT;
continue;
break;
#endif
case OP_BACKREF1: MOP_IN(OP_BACKREF1);
mem = 1;
goto backref;
break;
case OP_BACKREF2: MOP_IN(OP_BACKREF2);
mem = 2;
goto backref;
break;
case OP_BACKREFN: MOP_IN(OP_BACKREFN);
GET_MEMNUM_INC(mem, p);
backref:
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP(pstart, s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC);
GET_MEMNUM_INC(mem, p);
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(pstart, swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
{
int len;
OnigOptionType ic;
LengthType level;
GET_OPTION_INC(ic, p);
GET_LENGTH_INC(level, p);
GET_LENGTH_INC(tlen, p);
sprev = s;
if (backref_match_at_nested_level(reg, stk, stk_base, ic
, case_fold_flag, (int )level, (int )tlen, p, &s, end)) {
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * tlen);
}
else
goto fail;
MOP_OUT;
continue;
}
break;
#endif
#if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */
case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH);
GET_OPTION_INC(option, p);
STACK_PUSH_ALT(p, s, sprev);
p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL;
MOP_OUT;
continue;
break;
case OP_SET_OPTION: MOP_IN(OP_SET_OPTION);
GET_OPTION_INC(option, p);
MOP_OUT;
continue;
break;
#endif
case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START);
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_PUSH_NULL_CHECK_START(mem, s);
MOP_OUT;
continue;
break;
case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK(isnull, mem, s);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
null_check_found:
/* empty loop founded, skip next instruction */
switch (*p++) {
case OP_JUMP:
case OP_PUSH:
p += SIZE_RELADDR;
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
p += SIZE_MEMNUM;
break;
default:
goto unexpected_bytecode_error;
break;
}
}
}
MOP_OUT;
continue;
break;
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK_MEMST(isnull, mem, s, reg);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
}
MOP_OUT;
continue;
break;
#endif
#ifdef USE_SUBEXP_CALL
case OP_NULL_CHECK_END_MEMST_PUSH:
MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg);
#else
STACK_NULL_CHECK_REC(isnull, mem, s);
#endif
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
else {
STACK_PUSH_NULL_CHECK_END(mem);
}
}
MOP_OUT;
continue;
break;
#endif
case OP_JUMP: MOP_IN(OP_JUMP);
GET_RELADDR_INC(addr, p);
p += addr;
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_PUSH: MOP_IN(OP_PUSH);
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
MOP_OUT;
continue;
break;
case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP);
GET_STATE_CHECK_NUM_INC(mem, p);
GET_RELADDR_INC(addr, p);
STATE_CHECK_VAL(scv, mem);
if (scv) {
p += addr;
}
else {
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
}
MOP_OUT;
continue;
break;
case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_STATE_CHECK(s, mem);
MOP_OUT;
continue;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_POP: MOP_IN(OP_POP);
STACK_POP_ONE;
MOP_OUT;
continue;
break;
case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1);
GET_RELADDR_INC(addr, p);
if (*p == *s && DATA_ENSURE_CHECK1) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p += (addr + 1);
MOP_OUT;
continue;
break;
case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT);
GET_RELADDR_INC(addr, p);
if (*p == *s) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p++;
MOP_OUT;
continue;
break;
case OP_REPEAT: MOP_IN(OP_REPEAT);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p, s, sprev);
p += addr;
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
break;
case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
UChar* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
}
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
break;
case OP_PUSH_POS: MOP_IN(OP_PUSH_POS);
STACK_PUSH_POS(s, sprev);
MOP_OUT;
continue;
break;
case OP_POP_POS: MOP_IN(OP_POP_POS);
{
STACK_POS_END(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
}
MOP_OUT;
continue;
break;
case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT);
GET_RELADDR_INC(addr, p);
STACK_PUSH_POS_NOT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
case OP_FAIL_POS: MOP_IN(OP_FAIL_POS);
STACK_POP_TIL_POS_NOT;
goto fail;
break;
case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT);
STACK_PUSH_STOP_BT;
MOP_OUT;
continue;
break;
case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT);
STACK_STOP_BT_END;
MOP_OUT;
continue;
break;
case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND);
GET_LENGTH_INC(tlen, p);
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
MOP_OUT;
continue;
break;
case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT);
GET_RELADDR_INC(addr, p);
GET_LENGTH_INC(tlen, p);
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
}
MOP_OUT;
continue;
break;
case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT);
STACK_POP_TIL_LOOK_BEHIND_NOT;
goto fail;
break;
#ifdef USE_SUBEXP_CALL
case OP_CALL: MOP_IN(OP_CALL);
GET_ABSADDR_INC(addr, p);
STACK_PUSH_CALL_FRAME(p);
p = reg->p + addr;
MOP_OUT;
continue;
break;
case OP_RETURN: MOP_IN(OP_RETURN);
STACK_RETURN(p);
STACK_PUSH_RETURN;
MOP_OUT;
continue;
break;
#endif
case OP_FINISH:
goto finish;
break;
fail:
MOP_OUT;
/* fall */
case OP_FAIL: MOP_IN(OP_FAIL);
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
if (stk->u.state.state_check != 0) {
stk->type = STK_STATE_CHECK_MARK;
stk++;
}
#endif
MOP_OUT;
continue;
break;
default:
goto bytecode_error;
} /* end of switch */
sprev = sbegin;
} /* end of while(1) */
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
} | match_at(regex_t* reg, const UChar* str, const UChar* end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar* right_range,
#endif
const UChar* sstart, UChar* sprev, OnigMatchArg* msa)
{
static UChar FinishCode[] = { OP_FINISH };
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *sbegin;
int is_alloca;
char *alloc_base;
OnigStackType *stk_base, *stk, *stk_end;
OnigStackType *stkp; /* used as any purpose. */
OnigStackIndex si;
OnigStackIndex *repeat_stk;
OnigStackIndex *mem_start_stk, *mem_end_stk;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
int scv;
unsigned char* state_check_buff = msa->state_check_buff;
int num_comb_exp_check = reg->num_comb_exp_check;
#endif
UChar *p = reg->p;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
//n = reg->num_repeat + reg->num_mem * 2;
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n",
(int )str, (int )end, (int )sstart, (int )sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */
best_len = ONIG_MISMATCH;
s = (UChar* )sstart;
while (1) {
#ifdef ONIG_DEBUG_MATCH
{
UChar *q, *bp, buf[50];
int len;
fprintf(stderr, "%4d> \"", (int )(s - str));
bp = buf;
for (i = 0, q = s; i < 7 && q < end; i++) {
len = enclen(encode, q);
while (len-- > 0) *bp++ = *q++;
}
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }
else { xmemcpy(bp, "\"", 1); bp += 1; }
*bp = 0;
fputs((char* )buf, stderr);
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);
onig_print_compiled_byte_code(stderr, p, NULL, encode);
fprintf(stderr, "\n");
}
#endif
sbegin = s;
switch (*p++) {
case OP_END: MOP_IN(OP_END);
n = s - sstart;
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = sstart - str;
rmt[0].rm_eo = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str;
rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = sstart - str;
region->end[0] = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str;
region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = sstart - str;
node->end = s - str;
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
MOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
break;
case OP_EXACT1: MOP_IN(OP_EXACT1);
DATA_ENSURE(1);
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC);
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) {
goto fail;
}
p++; q++;
}
}
MOP_OUT;
break;
case OP_EXACT2: MOP_IN(OP_EXACT2);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT3: MOP_IN(OP_EXACT3);
DATA_ENSURE(3);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT4: MOP_IN(OP_EXACT4);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT5: MOP_IN(OP_EXACT5);
DATA_ENSURE(5);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTN: MOP_IN(OP_EXACTN);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen);
while (tlen-- > 0) {
if (*p++ != *s++) goto fail;
}
sprev = s - 1;
MOP_OUT;
continue;
break;
case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC);
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
GET_LENGTH_INC(tlen, p);
endp = p + tlen;
while (p < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) goto fail;
p++; q++;
}
}
}
MOP_OUT;
continue;
break;
case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3);
DATA_ENSURE(6);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 2);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 2;
MOP_OUT;
continue;
break;
case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 3);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 3;
MOP_OUT;
continue;
break;
case OP_EXACTMBN: MOP_IN(OP_EXACTMBN);
GET_LENGTH_INC(tlen, p); /* mb-len */
GET_LENGTH_INC(tlen2, p); /* string len */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
while (tlen2-- > 0) {
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - tlen;
MOP_OUT;
continue;
break;
case OP_CCLASS: MOP_IN(OP_CCLASS);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */
MOP_OUT;
break;
case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (! onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (! onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
MOP_OUT;
break;
case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) == 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
GET_LENGTH_INC(tlen, p);
p += tlen;
goto cc_mb_not_success;
}
cclass_mb_not:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
p += tlen;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
cc_mb_not_success:
MOP_OUT;
break;
case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb_not;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) != 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE);
{
OnigCodePoint code;
void *node;
int mb_len;
UChar *ss;
DATA_ENSURE(1);
GET_POINTER_INC(node, p);
mb_len = enclen(encode, s);
ss = s;
s += mb_len;
DATA_ENSURE(0);
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail;
}
MOP_OUT;
break;
case OP_ANYCHAR: MOP_IN(OP_ANYCHAR);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
p++;
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
p++;
MOP_OUT;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_STATE_CHECK_ANYCHAR_ML_STAR:
MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_WORD: MOP_IN(OP_WORD);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_NOT_WORD: MOP_IN(OP_NOT_WORD);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (! ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
== ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
!= ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
#ifdef USE_WORD_BEGIN_END
case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN);
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) {
if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
case OP_WORD_END: MOP_IN(OP_WORD_END);
if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
#endif
case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF);
if (! ON_STR_BEGIN(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_END_BUF: MOP_IN(OP_END_BUF);
if (! ON_STR_END(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE);
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
MOP_OUT;
continue;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
MOP_OUT;
continue;
}
goto fail;
break;
case OP_END_LINE: MOP_IN(OP_END_LINE);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
MOP_OUT;
continue;
}
#endif
goto fail;
break;
case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
MOP_OUT;
continue;
}
}
#endif
goto fail;
break;
case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION);
if (s != msa->start)
goto fail;
MOP_OUT;
continue;
break;
case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_START(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_START: MOP_IN(OP_MEMORY_START);
GET_MEMNUM_INC(mem, p);
mem_start_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_END(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END: MOP_IN(OP_MEMORY_END);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
#ifdef USE_SUBEXP_CALL
case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC);
GET_MEMNUM_INC(mem, p);
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
MOP_OUT;
continue;
break;
#endif
case OP_BACKREF1: MOP_IN(OP_BACKREF1);
mem = 1;
goto backref;
break;
case OP_BACKREF2: MOP_IN(OP_BACKREF2);
mem = 2;
goto backref;
break;
case OP_BACKREFN: MOP_IN(OP_BACKREFN);
GET_MEMNUM_INC(mem, p);
backref:
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP(pstart, s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC);
GET_MEMNUM_INC(mem, p);
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(pstart, swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
{
int len;
OnigOptionType ic;
LengthType level;
GET_OPTION_INC(ic, p);
GET_LENGTH_INC(level, p);
GET_LENGTH_INC(tlen, p);
sprev = s;
if (backref_match_at_nested_level(reg, stk, stk_base, ic
, case_fold_flag, (int )level, (int )tlen, p, &s, end)) {
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * tlen);
}
else
goto fail;
MOP_OUT;
continue;
}
break;
#endif
#if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */
case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH);
GET_OPTION_INC(option, p);
STACK_PUSH_ALT(p, s, sprev);
p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL;
MOP_OUT;
continue;
break;
case OP_SET_OPTION: MOP_IN(OP_SET_OPTION);
GET_OPTION_INC(option, p);
MOP_OUT;
continue;
break;
#endif
case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START);
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_PUSH_NULL_CHECK_START(mem, s);
MOP_OUT;
continue;
break;
case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK(isnull, mem, s);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
null_check_found:
/* empty loop founded, skip next instruction */
switch (*p++) {
case OP_JUMP:
case OP_PUSH:
p += SIZE_RELADDR;
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
p += SIZE_MEMNUM;
break;
default:
goto unexpected_bytecode_error;
break;
}
}
}
MOP_OUT;
continue;
break;
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK_MEMST(isnull, mem, s, reg);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
}
MOP_OUT;
continue;
break;
#endif
#ifdef USE_SUBEXP_CALL
case OP_NULL_CHECK_END_MEMST_PUSH:
MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg);
#else
STACK_NULL_CHECK_REC(isnull, mem, s);
#endif
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
else {
STACK_PUSH_NULL_CHECK_END(mem);
}
}
MOP_OUT;
continue;
break;
#endif
case OP_JUMP: MOP_IN(OP_JUMP);
GET_RELADDR_INC(addr, p);
p += addr;
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_PUSH: MOP_IN(OP_PUSH);
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
MOP_OUT;
continue;
break;
case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP);
GET_STATE_CHECK_NUM_INC(mem, p);
GET_RELADDR_INC(addr, p);
STATE_CHECK_VAL(scv, mem);
if (scv) {
p += addr;
}
else {
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
}
MOP_OUT;
continue;
break;
case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_STATE_CHECK(s, mem);
MOP_OUT;
continue;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_POP: MOP_IN(OP_POP);
STACK_POP_ONE;
MOP_OUT;
continue;
break;
case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1);
GET_RELADDR_INC(addr, p);
if (*p == *s && DATA_ENSURE_CHECK1) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p += (addr + 1);
MOP_OUT;
continue;
break;
case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT);
GET_RELADDR_INC(addr, p);
if (*p == *s) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p++;
MOP_OUT;
continue;
break;
case OP_REPEAT: MOP_IN(OP_REPEAT);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p, s, sprev);
p += addr;
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
break;
case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
UChar* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
}
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
break;
case OP_PUSH_POS: MOP_IN(OP_PUSH_POS);
STACK_PUSH_POS(s, sprev);
MOP_OUT;
continue;
break;
case OP_POP_POS: MOP_IN(OP_POP_POS);
{
STACK_POS_END(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
}
MOP_OUT;
continue;
break;
case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT);
GET_RELADDR_INC(addr, p);
STACK_PUSH_POS_NOT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
case OP_FAIL_POS: MOP_IN(OP_FAIL_POS);
STACK_POP_TIL_POS_NOT;
goto fail;
break;
case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT);
STACK_PUSH_STOP_BT;
MOP_OUT;
continue;
break;
case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT);
STACK_STOP_BT_END;
MOP_OUT;
continue;
break;
case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND);
GET_LENGTH_INC(tlen, p);
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
MOP_OUT;
continue;
break;
case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT);
GET_RELADDR_INC(addr, p);
GET_LENGTH_INC(tlen, p);
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
}
MOP_OUT;
continue;
break;
case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT);
STACK_POP_TIL_LOOK_BEHIND_NOT;
goto fail;
break;
#ifdef USE_SUBEXP_CALL
case OP_CALL: MOP_IN(OP_CALL);
GET_ABSADDR_INC(addr, p);
STACK_PUSH_CALL_FRAME(p);
p = reg->p + addr;
MOP_OUT;
continue;
break;
case OP_RETURN: MOP_IN(OP_RETURN);
STACK_RETURN(p);
STACK_PUSH_RETURN;
MOP_OUT;
continue;
break;
#endif
case OP_FINISH:
goto finish;
break;
fail:
MOP_OUT;
/* fall */
case OP_FAIL: MOP_IN(OP_FAIL);
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
if (stk->u.state.state_check != 0) {
stk->type = STK_STATE_CHECK_MARK;
stk++;
}
#endif
MOP_OUT;
continue;
break;
default:
goto bytecode_error;
} /* end of switch */
sprev = sbegin;
} /* end of while(1) */
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
} | {
"deleted": [
{
"line_no": 190,
"char_start": 6067,
"char_end": 6100,
"line": " if (*p != *s++) goto fail;\n"
},
{
"line_no": 191,
"char_start": 6100,
"char_end": 6122,
"line": " DATA_ENSURE(0);\n"
},
{
"line_no": 192,
"char_start": 6122,
"char_end": 6133,
"line": " p++;\n"
}
],
"added": []
} | {
"deleted": [
{
"char_start": 5985,
"char_end": 5991,
"chars": "#if 0\n"
},
{
"char_start": 6056,
"char_end": 6129,
"chars": "++;\n#endif\n if (*p != *s++) goto fail;\n DATA_ENSURE(0);\n p"
}
],
"added": []
} | github.com/kkos/oniguruma/commit/690313a061f7a4fa614ec5cc8368b4f2284e059b | src/regexec.c | cwe-125 |
ReadPSDImage | static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
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 image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
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 image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | {
"deleted": [],
"added": [
{
"line_no": 162,
"char_start": 5509,
"char_end": 5577,
"line": " if ((image->depth == 1) && (image->storage_class != PseudoClass))\n"
},
{
"line_no": 163,
"char_start": 5577,
"char_end": 5645,
"line": " ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 5511,
"char_end": 5647,
"chars": "if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n "
}
]
} | github.com/ImageMagick/ImageMagick/commit/198fffab4daf8aea88badd9c629350e5b26ec32f | coders/psd.c | cwe-125 |
decode_bundle | decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
}
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
} | decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
} else {
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port
= u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
} | {
"deleted": [
{
"line_no": 67,
"char_start": 2651,
"char_end": 2657,
"line": " }\n"
},
{
"line_no": 68,
"char_start": 2657,
"char_end": 2658,
"line": "\n"
},
{
"line_no": 69,
"char_start": 2658,
"char_end": 2703,
"line": " for (i = 0; i < bundle->n_slaves; i++) {\n"
},
{
"line_no": 70,
"char_start": 2703,
"char_end": 2780,
"line": " ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));\n"
},
{
"line_no": 71,
"char_start": 2780,
"char_end": 2837,
"line": " ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);\n"
},
{
"line_no": 72,
"char_start": 2837,
"char_end": 2871,
"line": " bundle = ofpacts->header;\n"
}
],
"added": [
{
"line_no": 67,
"char_start": 2651,
"char_end": 2664,
"line": " } else {\n"
},
{
"line_no": 68,
"char_start": 2664,
"char_end": 2713,
"line": " for (i = 0; i < bundle->n_slaves; i++) {\n"
},
{
"line_no": 69,
"char_start": 2713,
"char_end": 2745,
"line": " ofp_port_t ofp_port\n"
},
{
"line_no": 70,
"char_start": 2745,
"char_end": 2810,
"line": " = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));\n"
},
{
"line_no": 71,
"char_start": 2810,
"char_end": 2871,
"line": " ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);\n"
},
{
"line_no": 72,
"char_start": 2871,
"char_end": 2909,
"line": " bundle = ofpacts->header;\n"
},
{
"line_no": 73,
"char_start": 2909,
"char_end": 2919,
"line": " }\n"
}
]
} | {
"deleted": [
{
"char_start": 2656,
"char_end": 2657,
"chars": "\n"
}
],
"added": [
{
"char_start": 2656,
"char_end": 2663,
"chars": " else {"
},
{
"char_start": 2664,
"char_end": 2668,
"chars": " "
},
{
"char_start": 2721,
"char_end": 2725,
"chars": " "
},
{
"char_start": 2744,
"char_end": 2760,
"chars": "\n "
},
{
"char_start": 2818,
"char_end": 2822,
"chars": " "
},
{
"char_start": 2871,
"char_end": 2873,
"chars": " "
},
{
"char_start": 2881,
"char_end": 2883,
"chars": " "
},
{
"char_start": 2908,
"char_end": 2918,
"chars": "\n }"
}
]
} | github.com/openvswitch/ovs/commit/9237a63c47bd314b807cda0bd2216264e82edbe8 | lib/ofp-actions.c | cwe-125 |
SpliceImage | MagickExport Image *SpliceImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define SpliceImageTag "Splice/Image"
CacheView
*image_view,
*splice_view;
Image
*splice_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
splice_geometry;
ssize_t
y;
/*
Allocate splice image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
splice_geometry=(*geometry);
splice_image=CloneImage(image,image->columns+splice_geometry.width,
image->rows+splice_geometry.height,MagickTrue,exception);
if (splice_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse)
{
splice_image=DestroyImage(splice_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) &&
(IsGrayColorspace(splice_image->colorspace) != MagickFalse))
(void) SetImageColorspace(splice_image,sRGBColorspace,exception);
if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) &&
(splice_image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(splice_image,OpaqueAlpha,exception);
(void) SetImageBackgroundColor(splice_image,exception);
/*
Respect image geometry.
*/
switch (image->gravity)
{
default:
case UndefinedGravity:
case NorthWestGravity:
break;
case NorthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
break;
}
case NorthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
break;
}
case WestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.width/2;
break;
}
case CenterGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case EastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case SouthWestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
}
/*
Splice image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
splice_view=AcquireAuthenticCacheView(splice_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=0; y < (ssize_t) splice_geometry.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < splice_geometry.x; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
image->columns,1,exception);
if ((y < 0) || (y >= (ssize_t) splice_image->rows))
continue;
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < splice_geometry.x; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
} | MagickExport Image *SpliceImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define SpliceImageTag "Splice/Image"
CacheView
*image_view,
*splice_view;
Image
*splice_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
splice_geometry;
ssize_t
columns,
y;
/*
Allocate splice image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
splice_geometry=(*geometry);
splice_image=CloneImage(image,image->columns+splice_geometry.width,
image->rows+splice_geometry.height,MagickTrue,exception);
if (splice_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse)
{
splice_image=DestroyImage(splice_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) &&
(IsGrayColorspace(splice_image->colorspace) != MagickFalse))
(void) SetImageColorspace(splice_image,sRGBColorspace,exception);
if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) &&
(splice_image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(splice_image,OpaqueAlpha,exception);
(void) SetImageBackgroundColor(splice_image,exception);
/*
Respect image geometry.
*/
switch (image->gravity)
{
default:
case UndefinedGravity:
case NorthWestGravity:
break;
case NorthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
break;
}
case NorthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
break;
}
case WestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.width/2;
break;
}
case CenterGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case EastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case SouthWestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
}
/*
Splice image.
*/
status=MagickTrue;
progress=0;
columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
splice_view=AcquireAuthenticCacheView(splice_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=0; y < (ssize_t) splice_geometry.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
if ((y < 0) || (y >= (ssize_t)splice_image->rows))
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
splice_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
} | {
"deleted": [
{
"line_no": 130,
"char_start": 3435,
"char_end": 3511,
"line": " p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);\n"
},
{
"line_no": 138,
"char_start": 3734,
"char_end": 3776,
"line": " for (x=0; x < splice_geometry.x; x++)\n"
},
{
"line_no": 232,
"char_start": 6932,
"char_end": 7013,
"line": " p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,\n"
},
{
"line_no": 233,
"char_start": 7013,
"char_end": 7048,
"line": " image->columns,1,exception);\n"
},
{
"line_no": 234,
"char_start": 7048,
"char_end": 7104,
"line": " if ((y < 0) || (y >= (ssize_t) splice_image->rows))\n"
},
{
"line_no": 243,
"char_start": 7343,
"char_end": 7385,
"line": " for (x=0; x < splice_geometry.x; x++)\n"
}
],
"added": [
{
"line_no": 23,
"char_start": 343,
"char_end": 356,
"line": " columns,\n"
},
{
"line_no": 112,
"char_start": 2947,
"char_end": 3019,
"line": " columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);\n"
},
{
"line_no": 132,
"char_start": 3520,
"char_end": 3592,
"line": " p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1,\n"
},
{
"line_no": 133,
"char_start": 3592,
"char_end": 3610,
"line": " exception);\n"
},
{
"line_no": 141,
"char_start": 3833,
"char_end": 3865,
"line": " for (x=0; x < columns; x++)\n"
},
{
"line_no": 235,
"char_start": 7021,
"char_end": 7076,
"line": " if ((y < 0) || (y >= (ssize_t)splice_image->rows))\n"
},
{
"line_no": 237,
"char_start": 7092,
"char_end": 7173,
"line": " p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,\n"
},
{
"line_no": 238,
"char_start": 7173,
"char_end": 7215,
"line": " splice_image->columns,1,exception);\n"
},
{
"line_no": 246,
"char_start": 7438,
"char_end": 7470,
"line": " for (x=0; x < columns; x++)\n"
}
]
} | {
"deleted": [
{
"char_start": 3752,
"char_end": 3756,
"chars": "spli"
},
{
"char_start": 3757,
"char_end": 3761,
"chars": "e_ge"
},
{
"char_start": 3763,
"char_end": 3769,
"chars": "etry.x"
},
{
"char_start": 7046,
"char_end": 7118,
"chars": ";\n if ((y < 0) || (y >= (ssize_t) splice_image->rows))\n continue"
},
{
"char_start": 7361,
"char_end": 7365,
"chars": "spli"
},
{
"char_start": 7366,
"char_end": 7370,
"chars": "e_ge"
},
{
"char_start": 7372,
"char_end": 7378,
"chars": "etry.x"
}
],
"added": [
{
"char_start": 347,
"char_end": 360,
"chars": "columns,\n "
},
{
"char_start": 2947,
"char_end": 3019,
"chars": " columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);\n"
},
{
"char_start": 3567,
"char_end": 3574,
"chars": "splice_"
},
{
"char_start": 3591,
"char_end": 3598,
"chars": "\n "
},
{
"char_start": 3853,
"char_end": 3855,
"chars": "lu"
},
{
"char_start": 3856,
"char_end": 3858,
"chars": "ns"
},
{
"char_start": 7021,
"char_end": 7092,
"chars": " if ((y < 0) || (y >= (ssize_t)splice_image->rows))\n continue;\n"
},
{
"char_start": 7179,
"char_end": 7186,
"chars": "splice_"
},
{
"char_start": 7458,
"char_end": 7460,
"chars": "lu"
},
{
"char_start": 7461,
"char_end": 7463,
"chars": "ns"
}
]
} | github.com/ImageMagick/ImageMagick/commit/7b1cf5784b5bcd85aa9293ecf56769f68c037231 | MagickCore/transform.c | cwe-125 |
wrap_lines_smart | wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)
{
int i;
GlyphInfo *cur, *s1, *e1, *s2, *s3;
int last_space;
int break_type;
int exit;
double pen_shift_x;
double pen_shift_y;
int cur_line;
int run_offset;
TextInfo *text_info = &render_priv->text_info;
last_space = -1;
text_info->n_lines = 1;
break_type = 0;
s1 = text_info->glyphs; // current line start
for (i = 0; i < text_info->length; ++i) {
int break_at = -1;
double s_offset, len;
cur = text_info->glyphs + i;
s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;
if (cur->symbol == '\n') {
break_type = 2;
break_at = i;
ass_msg(render_priv->library, MSGL_DBG2,
"forced line break at %d", break_at);
} else if (cur->symbol == ' ') {
last_space = i;
} else if (len >= max_text_width
&& (render_priv->state.wrap_style != 2)) {
break_type = 1;
break_at = last_space;
if (break_at >= 0)
ass_msg(render_priv->library, MSGL_DBG2, "line break at %d",
break_at);
}
if (break_at != -1) {
// need to use one more line
// marking break_at+1 as start of a new line
int lead = break_at + 1; // the first symbol of the new line
if (text_info->n_lines >= text_info->max_lines) {
// Raise maximum number of lines
text_info->max_lines *= 2;
text_info->lines = realloc(text_info->lines,
sizeof(LineInfo) *
text_info->max_lines);
}
if (lead < text_info->length) {
text_info->glyphs[lead].linebreak = break_type;
last_space = -1;
s1 = text_info->glyphs + lead;
text_info->n_lines++;
}
}
}
#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
exit = 0;
while (!exit && render_priv->state.wrap_style != 1) {
exit = 1;
s3 = text_info->glyphs;
s1 = s2 = 0;
for (i = 0; i <= text_info->length; ++i) {
cur = text_info->glyphs + i;
if ((i == text_info->length) || cur->linebreak) {
s1 = s2;
s2 = s3;
s3 = cur;
if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
double l1, l2, l1_new, l2_new;
GlyphInfo *w = s2;
do {
--w;
} while ((w > s1) && (w->symbol == ' '));
while ((w > s1) && (w->symbol != ' ')) {
--w;
}
e1 = w;
while ((e1 > s1) && (e1->symbol == ' ')) {
--e1;
}
if (w->symbol == ' ')
++w;
l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(s2->bbox.xMin + s2->pos.x));
l1_new = d6_to_double(
(e1->bbox.xMax + e1->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2_new = d6_to_double(
((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(w->bbox.xMin + w->pos.x));
if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {
w->linebreak = 1;
s2->linebreak = 0;
exit = 0;
}
}
}
if (i == text_info->length)
break;
}
}
assert(text_info->n_lines >= 1);
#undef DIFF
measure_text(render_priv);
trim_whitespace(render_priv);
cur_line = 1;
run_offset = 0;
i = 0;
cur = text_info->glyphs + i;
while (i < text_info->length && cur->skip)
cur = text_info->glyphs + ++i;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y = 0.;
for (i = 0; i < text_info->length; ++i) {
cur = text_info->glyphs + i;
if (cur->linebreak) {
while (i < text_info->length && cur->skip && cur->symbol != '\n')
cur = text_info->glyphs + ++i;
double height =
text_info->lines[cur_line - 1].desc +
text_info->lines[cur_line].asc;
text_info->lines[cur_line - 1].len = i -
text_info->lines[cur_line - 1].offset;
text_info->lines[cur_line].offset = i;
cur_line++;
run_offset++;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y += height + render_priv->settings.line_spacing;
}
cur->pos.x += double_to_d6(pen_shift_x);
cur->pos.y += double_to_d6(pen_shift_y);
}
text_info->lines[cur_line - 1].len =
text_info->length - text_info->lines[cur_line - 1].offset;
#if 0
// print line info
for (i = 0; i < text_info->n_lines; i++) {
printf("line %d offset %d length %d\n", i, text_info->lines[i].offset,
text_info->lines[i].len);
}
#endif
} | wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)
{
int i;
GlyphInfo *cur, *s1, *e1, *s2, *s3;
int last_space;
int break_type;
int exit;
double pen_shift_x;
double pen_shift_y;
int cur_line;
int run_offset;
TextInfo *text_info = &render_priv->text_info;
last_space = -1;
text_info->n_lines = 1;
break_type = 0;
s1 = text_info->glyphs; // current line start
for (i = 0; i < text_info->length; ++i) {
int break_at = -1;
double s_offset, len;
cur = text_info->glyphs + i;
s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;
if (cur->symbol == '\n') {
break_type = 2;
break_at = i;
ass_msg(render_priv->library, MSGL_DBG2,
"forced line break at %d", break_at);
} else if (cur->symbol == ' ') {
last_space = i;
} else if (len >= max_text_width
&& (render_priv->state.wrap_style != 2)) {
break_type = 1;
break_at = last_space;
if (break_at >= 0)
ass_msg(render_priv->library, MSGL_DBG2, "line break at %d",
break_at);
}
if (break_at != -1) {
// need to use one more line
// marking break_at+1 as start of a new line
int lead = break_at + 1; // the first symbol of the new line
if (text_info->n_lines >= text_info->max_lines) {
// Raise maximum number of lines
text_info->max_lines *= 2;
text_info->lines = realloc(text_info->lines,
sizeof(LineInfo) *
text_info->max_lines);
}
if (lead < text_info->length) {
text_info->glyphs[lead].linebreak = break_type;
last_space = -1;
s1 = text_info->glyphs + lead;
text_info->n_lines++;
}
}
}
#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
exit = 0;
while (!exit && render_priv->state.wrap_style != 1) {
exit = 1;
s3 = text_info->glyphs;
s1 = s2 = 0;
for (i = 0; i <= text_info->length; ++i) {
cur = text_info->glyphs + i;
if ((i == text_info->length) || cur->linebreak) {
s1 = s2;
s2 = s3;
s3 = cur;
if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
double l1, l2, l1_new, l2_new;
GlyphInfo *w = s2;
do {
--w;
} while ((w > s1) && (w->symbol == ' '));
while ((w > s1) && (w->symbol != ' ')) {
--w;
}
e1 = w;
while ((e1 > s1) && (e1->symbol == ' ')) {
--e1;
}
if (w->symbol == ' ')
++w;
l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(s2->bbox.xMin + s2->pos.x));
l1_new = d6_to_double(
(e1->bbox.xMax + e1->pos.x) -
(s1->bbox.xMin + s1->pos.x));
l2_new = d6_to_double(
((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
(w->bbox.xMin + w->pos.x));
if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) {
if (w->linebreak)
text_info->n_lines--;
w->linebreak = 1;
s2->linebreak = 0;
exit = 0;
}
}
}
if (i == text_info->length)
break;
}
}
assert(text_info->n_lines >= 1);
#undef DIFF
measure_text(render_priv);
trim_whitespace(render_priv);
cur_line = 1;
run_offset = 0;
i = 0;
cur = text_info->glyphs + i;
while (i < text_info->length && cur->skip)
cur = text_info->glyphs + ++i;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y = 0.;
for (i = 0; i < text_info->length; ++i) {
cur = text_info->glyphs + i;
if (cur->linebreak) {
while (i < text_info->length && cur->skip && cur->symbol != '\n')
cur = text_info->glyphs + ++i;
double height =
text_info->lines[cur_line - 1].desc +
text_info->lines[cur_line].asc;
text_info->lines[cur_line - 1].len = i -
text_info->lines[cur_line - 1].offset;
text_info->lines[cur_line].offset = i;
cur_line++;
run_offset++;
pen_shift_x = d6_to_double(-cur->pos.x);
pen_shift_y += height + render_priv->settings.line_spacing;
}
cur->pos.x += double_to_d6(pen_shift_x);
cur->pos.y += double_to_d6(pen_shift_y);
}
text_info->lines[cur_line - 1].len =
text_info->length - text_info->lines[cur_line - 1].offset;
#if 0
// print line info
for (i = 0; i < text_info->n_lines; i++) {
printf("line %d offset %d length %d\n", i, text_info->lines[i].offset,
text_info->lines[i].len);
}
#endif
} | {
"deleted": [
{
"line_no": 100,
"char_start": 3756,
"char_end": 3819,
"line": " if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {\n"
}
],
"added": [
{
"line_no": 100,
"char_start": 3756,
"char_end": 3844,
"line": " if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) {\n"
},
{
"line_no": 101,
"char_start": 3844,
"char_end": 3886,
"line": " if (w->linebreak)\n"
},
{
"line_no": 102,
"char_start": 3886,
"char_end": 3936,
"line": " text_info->n_lines--;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 3815,
"char_end": 3840,
"chars": " && w > text_info->glyphs"
},
{
"char_start": 3843,
"char_end": 3935,
"chars": "\n if (w->linebreak)\n text_info->n_lines--;"
}
]
} | github.com/libass/libass/commit/b72b283b936a600c730e00875d7d067bded3fc26 | libass/ass_render.c | cwe-125 |
repodata_schema2id | repodata_schema2id(Repodata *data, Id *schema, int create)
{
int h, len, i;
Id *sp, cid;
Id *schematahash;
if (!*schema)
return 0; /* XXX: allow empty schema? */
if ((schematahash = data->schematahash) == 0)
{
data->schematahash = schematahash = solv_calloc(256, sizeof(Id));
for (i = 1; i < data->nschemata; i++)
{
for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)
h = h * 7 + *sp++;
h &= 255;
schematahash[h] = i;
}
data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);
}
for (sp = schema, len = 0, h = 0; *sp; len++)
h = h * 7 + *sp++;
h &= 255;
len++;
cid = schematahash[h];
if (cid)
{
if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
/* cache conflict, do a slow search */
for (cid = 1; cid < data->nschemata; cid++)
if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
}
/* a new one */
if (!create)
return 0;
data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);
/* add schema */
memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));
data->schemata[data->nschemata] = data->schemadatalen;
data->schemadatalen += len;
schematahash[h] = data->nschemata;
#if 0
fprintf(stderr, "schema2id: new schema\n");
#endif
return data->nschemata++;
} | repodata_schema2id(Repodata *data, Id *schema, int create)
{
int h, len, i;
Id *sp, cid;
Id *schematahash;
if (!*schema)
return 0; /* XXX: allow empty schema? */
if ((schematahash = data->schematahash) == 0)
{
data->schematahash = schematahash = solv_calloc(256, sizeof(Id));
for (i = 1; i < data->nschemata; i++)
{
for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)
h = h * 7 + *sp++;
h &= 255;
schematahash[h] = i;
}
data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);
}
for (sp = schema, len = 0, h = 0; *sp; len++)
h = h * 7 + *sp++;
h &= 255;
len++;
cid = schematahash[h];
if (cid)
{
if ((data->schemata[cid] + len <= data->schemadatalen) &&
!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
/* cache conflict, do a slow search */
for (cid = 1; cid < data->nschemata; cid++)
if ((data->schemata[cid] + len <= data->schemadatalen) &&
!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
}
/* a new one */
if (!create)
return 0;
data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);
/* add schema */
memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));
data->schemata[data->nschemata] = data->schemadatalen;
data->schemadatalen += len;
schematahash[h] = data->nschemata;
#if 0
fprintf(stderr, "schema2id: new schema\n");
#endif
return data->nschemata++;
} | {
"deleted": [
{
"line_no": 31,
"char_start": 838,
"char_end": 923,
"line": " if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n"
},
{
"line_no": 35,
"char_start": 1038,
"char_end": 1125,
"line": " if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n"
}
],
"added": [
{
"line_no": 31,
"char_start": 838,
"char_end": 902,
"line": " if ((data->schemata[cid] + len <= data->schemadatalen) &&\n"
},
{
"line_no": 32,
"char_start": 902,
"char_end": 982,
"line": "\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n"
},
{
"line_no": 36,
"char_start": 1097,
"char_end": 1163,
"line": " if ((data->schemata[cid] + len <= data->schemadatalen) &&\n"
},
{
"line_no": 37,
"char_start": 1163,
"char_end": 1242,
"line": "\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 848,
"char_end": 907,
"chars": "(data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t "
},
{
"char_start": 1109,
"char_end": 1167,
"chars": "(data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t\t"
}
]
} | github.com/openSUSE/libsolv/commit/fdb9c9c03508990e4583046b590c30d958f272da | src/repodata.c | cwe-125 |
ComplexImages | MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
} | MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
number_channels;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
number_channels=MagickMin(MagickMin(MagickMin(
Ar_image->number_channels,Ai_image->number_channels),MagickMin(
Br_image->number_channels,Bi_image->number_channels)),MagickMin(
Cr_image->number_channels,Ci_image->number_channels));
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_channels; i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
} | {
"deleted": [
{
"line_no": 137,
"char_start": 3900,
"char_end": 3963,
"line": " for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n"
}
],
"added": [
{
"line_no": 38,
"char_start": 511,
"char_end": 520,
"line": " size_t\n"
},
{
"line_no": 39,
"char_start": 520,
"char_end": 541,
"line": " number_channels;\n"
},
{
"line_no": 40,
"char_start": 541,
"char_end": 542,
"line": "\n"
},
{
"line_no": 93,
"char_start": 2196,
"char_end": 2245,
"line": " number_channels=MagickMin(MagickMin(MagickMin(\n"
},
{
"line_no": 94,
"char_start": 2245,
"char_end": 2313,
"line": " Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n"
},
{
"line_no": 95,
"char_start": 2313,
"char_end": 2382,
"line": " Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n"
},
{
"line_no": 96,
"char_start": 2382,
"char_end": 2441,
"line": " Cr_image->number_channels,Ci_image->number_channels));\n"
},
{
"line_no": 144,
"char_start": 4176,
"char_end": 4228,
"line": " for (i=0; i < (ssize_t) number_channels; i++)\n"
}
]
} | {
"deleted": [
{
"char_start": 521,
"char_end": 521,
"chars": ""
},
{
"char_start": 3930,
"char_end": 3931,
"chars": "G"
},
{
"char_start": 3932,
"char_end": 3939,
"chars": "tPixelC"
},
{
"char_start": 3946,
"char_end": 3956,
"chars": "(Cr_image)"
}
],
"added": [
{
"char_start": 514,
"char_end": 545,
"chars": "ize_t\n number_channels;\n\n s"
},
{
"char_start": 2196,
"char_end": 2441,
"chars": " number_channels=MagickMin(MagickMin(MagickMin(\n Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n Cr_image->number_channels,Ci_image->number_channels));\n"
},
{
"char_start": 4206,
"char_end": 4210,
"chars": "numb"
},
{
"char_start": 4211,
"char_end": 4214,
"chars": "r_c"
}
]
} | github.com/ImageMagick/ImageMagick/commit/d5089971bd792311aaab5cb73460326d7ef7f32d | MagickCore/fourier.c | cwe-125 |
ttm_put_pages | static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
unsigned long irq_flags;
unsigned i;
if (pool == NULL) {
/* No pool for this memory type so free the pages */
i = 0;
while (i < npages) {
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct page *p = pages[i];
#endif
unsigned order = 0, j;
if (!pages[i]) {
++i;
continue;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(flags & TTM_PAGE_FLAG_DMA32) &&
(npages - i) >= HPAGE_PMD_NR) {
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j == HPAGE_PMD_NR)
order = HPAGE_PMD_ORDER;
}
#endif
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
__free_pages(pages[i], order);
j = 1 << order;
while (j) {
pages[i++] = NULL;
--j;
}
}
return;
}
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge) {
unsigned max_size, n2free;
spin_lock_irqsave(&huge->lock, irq_flags);
while ((npages - i) >= HPAGE_PMD_NR) {
struct page *p = pages[i];
unsigned j;
if (!p)
break;
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j != HPAGE_PMD_NR)
break;
list_add_tail(&pages[i]->lru, &huge->list);
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = NULL;
huge->npages++;
}
/* Check that we don't go over the pool limit */
max_size = _manager->options.max_size;
max_size /= HPAGE_PMD_NR;
if (huge->npages > max_size)
n2free = huge->npages - max_size;
else
n2free = 0;
spin_unlock_irqrestore(&huge->lock, irq_flags);
if (n2free)
ttm_page_pool_free(huge, n2free, false);
}
#endif
spin_lock_irqsave(&pool->lock, irq_flags);
while (i < npages) {
if (pages[i]) {
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
list_add_tail(&pages[i]->lru, &pool->list);
pages[i] = NULL;
pool->npages++;
}
++i;
}
/* Check that we don't go over the pool limit */
npages = 0;
if (pool->npages > _manager->options.max_size) {
npages = pool->npages - _manager->options.max_size;
/* free at least NUM_PAGES_TO_ALLOC number of pages
* to reduce calls to set_memory_wb */
if (npages < NUM_PAGES_TO_ALLOC)
npages = NUM_PAGES_TO_ALLOC;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (npages)
ttm_page_pool_free(pool, npages, false);
} | static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
unsigned long irq_flags;
unsigned i;
if (pool == NULL) {
/* No pool for this memory type so free the pages */
i = 0;
while (i < npages) {
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct page *p = pages[i];
#endif
unsigned order = 0, j;
if (!pages[i]) {
++i;
continue;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(flags & TTM_PAGE_FLAG_DMA32) &&
(npages - i) >= HPAGE_PMD_NR) {
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (++p != pages[i + j])
break;
if (j == HPAGE_PMD_NR)
order = HPAGE_PMD_ORDER;
}
#endif
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
__free_pages(pages[i], order);
j = 1 << order;
while (j) {
pages[i++] = NULL;
--j;
}
}
return;
}
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge) {
unsigned max_size, n2free;
spin_lock_irqsave(&huge->lock, irq_flags);
while ((npages - i) >= HPAGE_PMD_NR) {
struct page *p = pages[i];
unsigned j;
if (!p)
break;
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (++p != pages[i + j])
break;
if (j != HPAGE_PMD_NR)
break;
list_add_tail(&pages[i]->lru, &huge->list);
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = NULL;
huge->npages++;
}
/* Check that we don't go over the pool limit */
max_size = _manager->options.max_size;
max_size /= HPAGE_PMD_NR;
if (huge->npages > max_size)
n2free = huge->npages - max_size;
else
n2free = 0;
spin_unlock_irqrestore(&huge->lock, irq_flags);
if (n2free)
ttm_page_pool_free(huge, n2free, false);
}
#endif
spin_lock_irqsave(&pool->lock, irq_flags);
while (i < npages) {
if (pages[i]) {
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
list_add_tail(&pages[i]->lru, &pool->list);
pages[i] = NULL;
pool->npages++;
}
++i;
}
/* Check that we don't go over the pool limit */
npages = 0;
if (pool->npages > _manager->options.max_size) {
npages = pool->npages - _manager->options.max_size;
/* free at least NUM_PAGES_TO_ALLOC number of pages
* to reduce calls to set_memory_wb */
if (npages < NUM_PAGES_TO_ALLOC)
npages = NUM_PAGES_TO_ALLOC;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (npages)
ttm_page_pool_free(pool, npages, false);
} | {
"deleted": [
{
"line_no": 29,
"char_start": 736,
"char_end": 766,
"line": "\t\t\t\t\tif (p++ != pages[i + j])\n"
},
{
"line_no": 64,
"char_start": 1344,
"char_end": 1373,
"line": "\t\t\t\tif (p++ != pages[i + j])\n"
}
],
"added": [
{
"line_no": 29,
"char_start": 736,
"char_end": 766,
"line": "\t\t\t\t\tif (++p != pages[i + j])\n"
},
{
"line_no": 64,
"char_start": 1344,
"char_end": 1373,
"line": "\t\t\t\tif (++p != pages[i + j])\n"
}
]
} | {
"deleted": [
{
"char_start": 745,
"char_end": 746,
"chars": "p"
},
{
"char_start": 1352,
"char_end": 1353,
"chars": "p"
}
],
"added": [
{
"char_start": 747,
"char_end": 748,
"chars": "p"
},
{
"char_start": 1354,
"char_end": 1355,
"chars": "p"
}
]
} | github.com/torvalds/linux/commit/453393369dc9806d2455151e329c599684762428 | drivers/gpu/drm/ttm/ttm_page_alloc.c | cwe-125 |
matchCurrentInput | matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
} | matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2;
((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));
k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
} | {
"deleted": [
{
"line_no": 5,
"char_start": 124,
"char_end": 198,
"line": "\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 124,
"char_end": 146,
"line": "\tfor (k = passIC + 2;\n"
},
{
"line_no": 6,
"char_start": 146,
"char_end": 224,
"line": "\t\t\t((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));\n"
},
{
"line_no": 7,
"char_start": 224,
"char_end": 232,
"line": "\t\t\tk++)\n"
}
]
} | {
"deleted": [
{
"char_start": 145,
"char_end": 146,
"chars": " "
},
{
"char_start": 192,
"char_end": 193,
"chars": " "
}
],
"added": [
{
"char_start": 145,
"char_end": 151,
"chars": "\n\t\t\t(("
},
{
"char_start": 196,
"char_end": 206,
"chars": ") && (kk <"
},
{
"char_start": 207,
"char_end": 227,
"chars": "input->length));\n\t\t\t"
}
]
} | github.com/liblouis/liblouis/commit/5e4089659bb49b3095fa541fa6387b4c40d7396e | liblouis/lou_translateString.c | cwe-125 |
ims_pcu_get_cdc_union_desc | static const struct usb_cdc_union_desc *
ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
{
const void *buf = intf->altsetting->extra;
size_t buflen = intf->altsetting->extralen;
struct usb_cdc_union_desc *union_desc;
if (!buf) {
dev_err(&intf->dev, "Missing descriptor data\n");
return NULL;
}
if (!buflen) {
dev_err(&intf->dev, "Zero length descriptor\n");
return NULL;
}
while (buflen > 0) {
union_desc = (struct usb_cdc_union_desc *)buf;
if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
dev_dbg(&intf->dev, "Found union header\n");
return union_desc;
}
buflen -= union_desc->bLength;
buf += union_desc->bLength;
}
dev_err(&intf->dev, "Missing CDC union descriptor\n");
return NULL; | static const struct usb_cdc_union_desc *
ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
{
const void *buf = intf->altsetting->extra;
size_t buflen = intf->altsetting->extralen;
struct usb_cdc_union_desc *union_desc;
if (!buf) {
dev_err(&intf->dev, "Missing descriptor data\n");
return NULL;
}
if (!buflen) {
dev_err(&intf->dev, "Zero length descriptor\n");
return NULL;
}
while (buflen >= sizeof(*union_desc)) {
union_desc = (struct usb_cdc_union_desc *)buf;
if (union_desc->bLength > buflen) {
dev_err(&intf->dev, "Too large descriptor\n");
return NULL;
}
if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
dev_dbg(&intf->dev, "Found union header\n");
if (union_desc->bLength >= sizeof(*union_desc))
return union_desc;
dev_err(&intf->dev,
"Union descriptor to short (%d vs %zd\n)",
union_desc->bLength, sizeof(*union_desc));
return NULL;
}
buflen -= union_desc->bLength;
buf += union_desc->bLength;
}
dev_err(&intf->dev, "Missing CDC union descriptor\n");
return NULL; | {
"deleted": [
{
"line_no": 18,
"char_start": 398,
"char_end": 420,
"line": "\twhile (buflen > 0) {\n"
},
{
"line_no": 24,
"char_start": 640,
"char_end": 662,
"line": "\t\t\treturn union_desc;\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 398,
"char_end": 439,
"line": "\twhile (buflen >= sizeof(*union_desc)) {\n"
},
{
"line_no": 21,
"char_start": 489,
"char_end": 527,
"line": "\t\tif (union_desc->bLength > buflen) {\n"
},
{
"line_no": 22,
"char_start": 527,
"char_end": 577,
"line": "\t\t\tdev_err(&intf->dev, \"Too large descriptor\\n\");\n"
},
{
"line_no": 23,
"char_start": 577,
"char_end": 593,
"line": "\t\t\treturn NULL;\n"
},
{
"line_no": 24,
"char_start": 593,
"char_end": 597,
"line": "\t\t}\n"
},
{
"line_no": 25,
"char_start": 597,
"char_end": 598,
"line": "\n"
},
{
"line_no": 29,
"char_start": 768,
"char_end": 769,
"line": "\n"
},
{
"line_no": 30,
"char_start": 769,
"char_end": 820,
"line": "\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n"
},
{
"line_no": 31,
"char_start": 820,
"char_end": 843,
"line": "\t\t\t\treturn union_desc;\n"
},
{
"line_no": 32,
"char_start": 843,
"char_end": 844,
"line": "\n"
},
{
"line_no": 33,
"char_start": 844,
"char_end": 867,
"line": "\t\t\tdev_err(&intf->dev,\n"
},
{
"line_no": 34,
"char_start": 867,
"char_end": 914,
"line": "\t\t\t\t\"Union descriptor to short (%d vs %zd\\n)\",\n"
},
{
"line_no": 35,
"char_start": 914,
"char_end": 961,
"line": "\t\t\t\tunion_desc->bLength, sizeof(*union_desc));\n"
},
{
"line_no": 36,
"char_start": 961,
"char_end": 977,
"line": "\t\t\treturn NULL;\n"
}
]
} | {
"deleted": [
{
"char_start": 415,
"char_end": 416,
"chars": "0"
}
],
"added": [
{
"char_start": 414,
"char_end": 415,
"chars": "="
},
{
"char_start": 416,
"char_end": 435,
"chars": "sizeof(*union_desc)"
},
{
"char_start": 489,
"char_end": 598,
"chars": "\t\tif (union_desc->bLength > buflen) {\n\t\t\tdev_err(&intf->dev, \"Too large descriptor\\n\");\n\t\t\treturn NULL;\n\t\t}\n\n"
},
{
"char_start": 768,
"char_end": 821,
"chars": "\n\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n\t"
},
{
"char_start": 841,
"char_end": 975,
"chars": ";\n\n\t\t\tdev_err(&intf->dev,\n\t\t\t\t\"Union descriptor to short (%d vs %zd\\n)\",\n\t\t\t\tunion_desc->bLength, sizeof(*union_desc));\n\t\t\treturn NULL"
}
]
} | github.com/torvalds/linux/commit/ea04efee7635c9120d015dcdeeeb6988130cb67a | drivers/input/misc/ims-pcu.c | cwe-125 |
tensorflow::QuantizeAndDequantizeV2Op::Compute | void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);
Tensor input_min_tensor;
Tensor input_max_tensor;
Tensor* output = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));
if (range_given_) {
input_min_tensor = ctx->input(1);
input_max_tensor = ctx->input(2);
if (axis_ == -1) {
auto min_val = input_min_tensor.scalar<T>()();
auto max_val = input_max_tensor.scalar<T>()();
OP_REQUIRES(ctx, min_val <= max_val,
errors::InvalidArgument("Invalid range: input_min ",
min_val, " > input_max ", max_val));
} else {
OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_min_tensor has incorrect size, was ",
input_min_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_min_tensor.shape()));
OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_max_tensor has incorrect size, was ",
input_max_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_max_tensor.shape()));
}
} else {
auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_min_tensor));
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_max_tensor));
}
if (axis_ == -1) {
functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_,
range_given_, &input_min_tensor, &input_max_tensor, round_mode_,
narrow_range_, output->flat<T>());
} else {
functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;
f(ctx->eigen_device<Device>(),
input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,
num_bits_, range_given_, &input_min_tensor, &input_max_tensor,
round_mode_, narrow_range_,
output->template flat_inner_outer_dims<T, 3>(axis_ - 1));
}
} | void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
OP_REQUIRES(
ctx, (axis_ == -1 || axis_ < input.shape().dims()),
errors::InvalidArgument("Shape must be at least rank ", axis_ + 1,
" but is rank ", input.shape().dims()));
const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);
Tensor input_min_tensor;
Tensor input_max_tensor;
Tensor* output = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));
if (range_given_) {
input_min_tensor = ctx->input(1);
input_max_tensor = ctx->input(2);
if (axis_ == -1) {
auto min_val = input_min_tensor.scalar<T>()();
auto max_val = input_max_tensor.scalar<T>()();
OP_REQUIRES(ctx, min_val <= max_val,
errors::InvalidArgument("Invalid range: input_min ",
min_val, " > input_max ", max_val));
} else {
OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_min_tensor has incorrect size, was ",
input_min_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_min_tensor.shape()));
OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_max_tensor has incorrect size, was ",
input_max_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_max_tensor.shape()));
}
} else {
auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_min_tensor));
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_max_tensor));
}
if (axis_ == -1) {
functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_,
range_given_, &input_min_tensor, &input_max_tensor, round_mode_,
narrow_range_, output->flat<T>());
} else {
functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;
f(ctx->eigen_device<Device>(),
input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,
num_bits_, range_given_, &input_min_tensor, &input_max_tensor,
round_mode_, narrow_range_,
output->template flat_inner_outer_dims<T, 3>(axis_ - 1));
}
} | {
"deleted": [],
"added": [
{
"line_no": 3,
"char_start": 89,
"char_end": 106,
"line": " OP_REQUIRES(\n"
},
{
"line_no": 4,
"char_start": 106,
"char_end": 166,
"line": " ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n"
},
{
"line_no": 5,
"char_start": 166,
"char_end": 241,
"line": " errors::InvalidArgument(\"Shape must be at least rank \", axis_ + 1,\n"
},
{
"line_no": 6,
"char_start": 241,
"char_end": 314,
"line": " \" but is rank \", input.shape().dims()));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 93,
"char_end": 318,
"chars": "OP_REQUIRES(\n ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(\"Shape must be at least rank \", axis_ + 1,\n \" but is rank \", input.shape().dims()));\n "
}
]
} | github.com/tensorflow/tensorflow/commit/eccb7ec454e6617738554a255d77f08e60ee0808 | tensorflow/core/kernels/quantize_and_dequantize_op.cc | cwe-125 |
_bson_iter_next_internal | _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */
uint32_t next_keylen, /* IN */
const char **key, /* OUT */
uint32_t *bson_type, /* OUT */
bool *unsupported) /* OUT */
{
const uint8_t *data;
uint32_t o;
unsigned int len;
BSON_ASSERT (iter);
*unsupported = false;
if (!iter->raw) {
*key = NULL;
*bson_type = BSON_TYPE_EOD;
return false;
}
data = iter->raw;
len = iter->len;
iter->off = iter->next_off;
iter->type = iter->off;
iter->key = iter->off + 1;
iter->d1 = 0;
iter->d2 = 0;
iter->d3 = 0;
iter->d4 = 0;
if (next_keylen == 0) {
/* iterate from start to end of NULL-terminated key string */
for (o = iter->key; o < len; o++) {
if (!data[o]) {
iter->d1 = ++o;
goto fill_data_fields;
}
}
} else {
o = iter->key + next_keylen + 1;
iter->d1 = o;
goto fill_data_fields;
}
goto mark_invalid;
fill_data_fields:
*key = bson_iter_key_unsafe (iter);
*bson_type = ITER_TYPE (iter);
switch (*bson_type) {
case BSON_TYPE_DATE_TIME:
case BSON_TYPE_DOUBLE:
case BSON_TYPE_INT64:
case BSON_TYPE_TIMESTAMP:
iter->next_off = o + 8;
break;
case BSON_TYPE_CODE:
case BSON_TYPE_SYMBOL:
case BSON_TYPE_UTF8: {
uint32_t l;
if ((o + 4) >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l > (len - (o + 4))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 4 + l;
/*
* Make sure the string length includes the NUL byte.
*/
if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) {
iter->err_off = o;
goto mark_invalid;
}
/*
* Make sure the last byte is a NUL byte.
*/
if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) {
iter->err_off = o + 4 + l - 1;
goto mark_invalid;
}
} break;
case BSON_TYPE_BINARY: {
bson_subtype_t subtype;
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 5;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l >= (len - o)) {
iter->err_off = o;
goto mark_invalid;
}
subtype = *(iter->raw + iter->d2);
if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
int32_t binary_len;
if (l < 4) {
iter->err_off = o;
goto mark_invalid;
}
/* subtype 2 has a redundant length header in the data */
memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len));
binary_len = BSON_UINT32_FROM_LE (binary_len);
if (binary_len + 4 != l) {
iter->err_off = iter->d3;
goto mark_invalid;
}
}
iter->next_off = o + 5 + l;
} break;
case BSON_TYPE_ARRAY:
case BSON_TYPE_DOCUMENT: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l > len) || (l > (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
} break;
case BSON_TYPE_OID:
iter->next_off = o + 12;
break;
case BSON_TYPE_BOOL: {
char val;
if (iter->d1 >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&val, iter->raw + iter->d1, 1);
if (val != 0x00 && val != 0x01) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_REGEX: {
bool eor = false;
bool eoo = false;
for (; o < len; o++) {
if (!data[o]) {
iter->d2 = ++o;
eor = true;
break;
}
}
if (!eor) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
for (; o < len; o++) {
if (!data[o]) {
eoo = true;
break;
}
}
if (!eoo) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_DBPOINTER: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
/* Check valid string length. l counts '\0' but not 4 bytes for itself. */
if (l == 0 || l > (len - o - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if (*(iter->raw + o + l + 3)) {
/* not null terminated */
iter->err_off = o + l + 3;
goto mark_invalid;
}
iter->d3 = o + 4 + l;
iter->next_off = o + 4 + l + 12;
} break;
case BSON_TYPE_CODEWSCOPE: {
uint32_t l;
uint32_t doclen;
if ((len < 19) || (o >= (len - 14))) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 8;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l < 14) || (l >= (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d2, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l == 0 || l >= (len - o - 4 - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if ((o + 4 + 4 + l + 4) >= iter->next_off) {
iter->err_off = o + 4;
goto mark_invalid;
}
iter->d4 = o + 4 + 4 + l;
memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen));
doclen = BSON_UINT32_FROM_LE (doclen);
if ((o + 4 + 4 + l + doclen) != iter->next_off) {
iter->err_off = o + 4 + 4 + l;
goto mark_invalid;
}
} break;
case BSON_TYPE_INT32:
iter->next_off = o + 4;
break;
case BSON_TYPE_DECIMAL128:
iter->next_off = o + 16;
break;
case BSON_TYPE_MAXKEY:
case BSON_TYPE_MINKEY:
case BSON_TYPE_NULL:
case BSON_TYPE_UNDEFINED:
iter->next_off = o;
break;
default:
*unsupported = true;
/* FALL THROUGH */
case BSON_TYPE_EOD:
iter->err_off = o;
goto mark_invalid;
}
/*
* Check to see if any of the field locations would overflow the
* current BSON buffer. If so, set the error location to the offset
* of where the field starts.
*/
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->err_off = 0;
return true;
mark_invalid:
iter->raw = NULL;
iter->len = 0;
iter->next_off = 0;
return false;
} | _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */
uint32_t next_keylen, /* IN */
const char **key, /* OUT */
uint32_t *bson_type, /* OUT */
bool *unsupported) /* OUT */
{
const uint8_t *data;
uint32_t o;
unsigned int len;
BSON_ASSERT (iter);
*unsupported = false;
if (!iter->raw) {
*key = NULL;
*bson_type = BSON_TYPE_EOD;
return false;
}
data = iter->raw;
len = iter->len;
iter->off = iter->next_off;
iter->type = iter->off;
iter->key = iter->off + 1;
iter->d1 = 0;
iter->d2 = 0;
iter->d3 = 0;
iter->d4 = 0;
if (next_keylen == 0) {
/* iterate from start to end of NULL-terminated key string */
for (o = iter->key; o < len; o++) {
if (!data[o]) {
iter->d1 = ++o;
goto fill_data_fields;
}
}
} else {
o = iter->key + next_keylen + 1;
iter->d1 = o;
goto fill_data_fields;
}
goto mark_invalid;
fill_data_fields:
*key = bson_iter_key_unsafe (iter);
*bson_type = ITER_TYPE (iter);
switch (*bson_type) {
case BSON_TYPE_DATE_TIME:
case BSON_TYPE_DOUBLE:
case BSON_TYPE_INT64:
case BSON_TYPE_TIMESTAMP:
iter->next_off = o + 8;
break;
case BSON_TYPE_CODE:
case BSON_TYPE_SYMBOL:
case BSON_TYPE_UTF8: {
uint32_t l;
if ((o + 4) >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l > (len - (o + 4))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 4 + l;
/*
* Make sure the string length includes the NUL byte.
*/
if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) {
iter->err_off = o;
goto mark_invalid;
}
/*
* Make sure the last byte is a NUL byte.
*/
if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) {
iter->err_off = o + 4 + l - 1;
goto mark_invalid;
}
} break;
case BSON_TYPE_BINARY: {
bson_subtype_t subtype;
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 5;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l >= (len - o - 4)) {
iter->err_off = o;
goto mark_invalid;
}
subtype = *(iter->raw + iter->d2);
if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
int32_t binary_len;
if (l < 4) {
iter->err_off = o;
goto mark_invalid;
}
/* subtype 2 has a redundant length header in the data */
memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len));
binary_len = BSON_UINT32_FROM_LE (binary_len);
if (binary_len + 4 != l) {
iter->err_off = iter->d3;
goto mark_invalid;
}
}
iter->next_off = o + 5 + l;
} break;
case BSON_TYPE_ARRAY:
case BSON_TYPE_DOCUMENT: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l > len) || (l > (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
} break;
case BSON_TYPE_OID:
iter->next_off = o + 12;
break;
case BSON_TYPE_BOOL: {
char val;
if (iter->d1 >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&val, iter->raw + iter->d1, 1);
if (val != 0x00 && val != 0x01) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_REGEX: {
bool eor = false;
bool eoo = false;
for (; o < len; o++) {
if (!data[o]) {
iter->d2 = ++o;
eor = true;
break;
}
}
if (!eor) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
for (; o < len; o++) {
if (!data[o]) {
eoo = true;
break;
}
}
if (!eoo) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_DBPOINTER: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
/* Check valid string length. l counts '\0' but not 4 bytes for itself. */
if (l == 0 || l > (len - o - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if (*(iter->raw + o + l + 3)) {
/* not null terminated */
iter->err_off = o + l + 3;
goto mark_invalid;
}
iter->d3 = o + 4 + l;
iter->next_off = o + 4 + l + 12;
} break;
case BSON_TYPE_CODEWSCOPE: {
uint32_t l;
uint32_t doclen;
if ((len < 19) || (o >= (len - 14))) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 8;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l < 14) || (l >= (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d2, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l == 0 || l >= (len - o - 4 - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if ((o + 4 + 4 + l + 4) >= iter->next_off) {
iter->err_off = o + 4;
goto mark_invalid;
}
iter->d4 = o + 4 + 4 + l;
memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen));
doclen = BSON_UINT32_FROM_LE (doclen);
if ((o + 4 + 4 + l + doclen) != iter->next_off) {
iter->err_off = o + 4 + 4 + l;
goto mark_invalid;
}
} break;
case BSON_TYPE_INT32:
iter->next_off = o + 4;
break;
case BSON_TYPE_DECIMAL128:
iter->next_off = o + 16;
break;
case BSON_TYPE_MAXKEY:
case BSON_TYPE_MINKEY:
case BSON_TYPE_NULL:
case BSON_TYPE_UNDEFINED:
iter->next_off = o;
break;
default:
*unsupported = true;
/* FALL THROUGH */
case BSON_TYPE_EOD:
iter->err_off = o;
goto mark_invalid;
}
/*
* Check to see if any of the field locations would overflow the
* current BSON buffer. If so, set the error location to the offset
* of where the field starts.
*/
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->err_off = 0;
return true;
mark_invalid:
iter->raw = NULL;
iter->len = 0;
iter->next_off = 0;
return false;
} | {
"deleted": [
{
"line_no": 112,
"char_start": 2519,
"char_end": 2547,
"line": " if (l >= (len - o)) {\n"
}
],
"added": [
{
"line_no": 112,
"char_start": 2519,
"char_end": 2551,
"line": " if (l >= (len - o - 4)) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2542,
"char_end": 2546,
"chars": " - 4"
}
]
} | github.com/mongodb/mongo-c-driver/commit/0d9a4d98bfdf4acd2c0138d4aaeb4e2e0934bd84 | src/libbson/src/bson/bson-iter.c | cwe-125 |
enc_untrusted_inet_pton | int enc_untrusted_inet_pton(int af, const char *src, void *dst) {
if (!src || !dst) {
return 0;
}
MessageWriter input;
input.Push<int>(TokLinuxAfFamily(af));
input.PushByReference(Extent{
src, std::min(strlen(src) + 1, static_cast<size_t>(INET6_ADDRSTRLEN))});
MessageReader output;
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kInetPtonHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_inet_pton", 3);
int result = output.next<int>();
int klinux_errno = output.next<int>();
if (result == -1) {
errno = FromkLinuxErrorNumber(klinux_errno);
return -1;
}
auto klinux_addr_buffer = output.next();
size_t max_size = 0;
if (af == AF_INET) {
max_size = sizeof(struct in_addr);
} else if (af == AF_INET6) {
max_size = sizeof(struct in6_addr);
}
memcpy(dst, klinux_addr_buffer.data(),
std::min(klinux_addr_buffer.size(), max_size));
return result;
} | int enc_untrusted_inet_pton(int af, const char *src, void *dst) {
if (!src || !dst) {
return 0;
}
MessageWriter input;
input.Push<int>(TokLinuxAfFamily(af));
input.PushByReference(Extent{
src, std::min(strlen(src) + 1, static_cast<size_t>(INET6_ADDRSTRLEN))});
MessageReader output;
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kInetPtonHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_inet_pton", 3);
int result = output.next<int>();
int klinux_errno = output.next<int>();
if (result == -1) {
errno = FromkLinuxErrorNumber(klinux_errno);
return -1;
}
auto klinux_addr_buffer = output.next();
size_t max_size = 0;
if (af == AF_INET) {
if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {
::asylo::primitives::TrustedPrimitives::BestEffortAbort(
"enc_untrusted_inet_pton: unexpected output size");
}
max_size = sizeof(struct in_addr);
} else if (af == AF_INET6) {
if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {
::asylo::primitives::TrustedPrimitives::BestEffortAbort(
"enc_untrusted_inet_pton: unexpected output size");
}
max_size = sizeof(struct in6_addr);
}
memcpy(dst, klinux_addr_buffer.data(),
std::min(klinux_addr_buffer.size(), max_size));
return result;
} | {
"deleted": [],
"added": [
{
"line_no": 26,
"char_start": 747,
"char_end": 810,
"line": " if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n"
},
{
"line_no": 27,
"char_start": 810,
"char_end": 873,
"line": " ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n"
},
{
"line_no": 28,
"char_start": 873,
"char_end": 935,
"line": " \"enc_untrusted_inet_pton: unexpected output size\");\n"
},
{
"line_no": 29,
"char_start": 935,
"char_end": 941,
"line": " }\n"
},
{
"line_no": 32,
"char_start": 1011,
"char_end": 1075,
"line": " if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n"
},
{
"line_no": 33,
"char_start": 1075,
"char_end": 1138,
"line": " ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n"
},
{
"line_no": 34,
"char_start": 1138,
"char_end": 1200,
"line": " \"enc_untrusted_inet_pton: unexpected output size\");\n"
},
{
"line_no": 35,
"char_start": 1200,
"char_end": 1206,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 751,
"char_end": 945,
"chars": "if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }\n "
},
{
"char_start": 1010,
"char_end": 1205,
"chars": "\n if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }"
}
]
} | github.com/google/asylo/commit/8fed5e334131abaf9c5e17307642fbf6ce4a57ec | asylo/platform/host_call/trusted/host_calls.cc | cwe-125 |
tensorflow::GraphConstructor::MakeEdge | Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,
int input_index) {
DataType src_out = src->output_type(output_index);
DataType dst_in = dst->input_type(input_index);
if (!TypesCompatible(dst_in, src_out)) {
return errors::InvalidArgument(
"Input ", input_index, " of node ", dst->name(), " was passed ",
DataTypeString(src_out), " from ", src->name(), ":", output_index,
" incompatible with expected ", DataTypeString(dst_in), ".");
}
g_->AddEdge(src, output_index, dst, input_index);
return Status::OK();
} | Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,
int input_index) {
if (output_index >= src->num_outputs()) {
return errors::InvalidArgument(
"Output ", output_index, " of node ", src->name(),
" does not exist. Node only has ", src->num_outputs(), " outputs.");
}
if (input_index >= dst->num_inputs()) {
return errors::InvalidArgument(
"Input ", input_index, " of node ", dst->name(),
" does not exist. Node only has ", dst->num_inputs(), " inputs.");
}
DataType src_out = src->output_type(output_index);
DataType dst_in = dst->input_type(input_index);
if (!TypesCompatible(dst_in, src_out)) {
return errors::InvalidArgument(
"Input ", input_index, " of node ", dst->name(), " was passed ",
DataTypeString(src_out), " from ", src->name(), ":", output_index,
" incompatible with expected ", DataTypeString(dst_in), ".");
}
g_->AddEdge(src, output_index, dst, input_index);
return Status::OK();
} | {
"deleted": [],
"added": [
{
"line_no": 3,
"char_start": 127,
"char_end": 171,
"line": " if (output_index >= src->num_outputs()) {\n"
},
{
"line_no": 4,
"char_start": 171,
"char_end": 207,
"line": " return errors::InvalidArgument(\n"
},
{
"line_no": 5,
"char_start": 207,
"char_end": 266,
"line": " \"Output \", output_index, \" of node \", src->name(),\n"
},
{
"line_no": 6,
"char_start": 266,
"char_end": 343,
"line": " \" does not exist. Node only has \", src->num_outputs(), \" outputs.\");\n"
},
{
"line_no": 7,
"char_start": 343,
"char_end": 347,
"line": " }\n"
},
{
"line_no": 8,
"char_start": 347,
"char_end": 389,
"line": " if (input_index >= dst->num_inputs()) {\n"
},
{
"line_no": 9,
"char_start": 389,
"char_end": 425,
"line": " return errors::InvalidArgument(\n"
},
{
"line_no": 10,
"char_start": 425,
"char_end": 482,
"line": " \"Input \", input_index, \" of node \", dst->name(),\n"
},
{
"line_no": 11,
"char_start": 482,
"char_end": 557,
"line": " \" does not exist. Node only has \", dst->num_inputs(), \" inputs.\");\n"
},
{
"line_no": 12,
"char_start": 557,
"char_end": 561,
"line": " }\n"
},
{
"line_no": 13,
"char_start": 561,
"char_end": 562,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 129,
"char_end": 564,
"chars": "if (output_index >= src->num_outputs()) {\n return errors::InvalidArgument(\n \"Output \", output_index, \" of node \", src->name(),\n \" does not exist. Node only has \", src->num_outputs(), \" outputs.\");\n }\n if (input_index >= dst->num_inputs()) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(),\n \" does not exist. Node only has \", dst->num_inputs(), \" inputs.\");\n }\n\n "
}
]
} | github.com/tensorflow/tensorflow/commit/0cc38aaa4064fd9e79101994ce9872c6d91f816b | tensorflow/core/common_runtime/graph_constructor.cc | cwe-125 |
DecompressRTF | BYTE *DecompressRTF(variableLength *p, int *size) {
BYTE *dst; // destination for uncompressed bytes
BYTE *src;
unsigned int in;
unsigned int out;
variableLength comp_Prebuf;
ULONG compressedSize, uncompressedSize, magic;
comp_Prebuf.size = strlen(RTF_PREBUF);
comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);
ALLOCCHECK_CHAR(comp_Prebuf.data);
memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);
src = p->data;
in = 0;
if (p->size < 20) {
printf("File too small\n");
return(NULL);
}
compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
in += 4;
in += 4;
// check size excluding the size field itself
if (compressedSize != p->size - 4) {
printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4);
free(comp_Prebuf.data);
return NULL;
}
// process the data
if (magic == 0x414c454d) {
// magic number that identifies the stream as a uncompressed stream
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + 4, uncompressedSize);
} else if (magic == 0x75465a4c) {
// magic number that identifies the stream as a compressed stream
int flagCount = 0;
int flags = 0;
// Prevent overflow on 32 Bit Systems
if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {
printf("Corrupted file\n");
exit(-1);
}
dst = calloc(comp_Prebuf.size + uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);
out = comp_Prebuf.size;
while (out < (comp_Prebuf.size + uncompressedSize)) {
// each flag byte flags 8 literals/references, 1 per bit
flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;
if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal
unsigned int offset = src[in++];
unsigned int length = src[in++];
unsigned int end;
offset = (offset << 4) | (length >> 4); // the offset relative to block start
length = (length & 0xF) + 2; // the number of bytes to copy
// the decompression buffer is supposed to wrap around back
// to the beginning when the end is reached. we save the
// need for such a buffer by pointing straight into the data
// buffer, and simulating this behaviour by modifying the
// pointers appropriately.
offset = (out / 4096) * 4096 + offset;
if (offset >= out) // take from previous block
offset -= 4096;
// note: can't use System.arraycopy, because the referenced
// bytes can cross through the current out position.
end = offset + length;
while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))
&& (offset < (comp_Prebuf.size + uncompressedSize)))
dst[out++] = dst[offset++];
} else { // literal
if ((out >= (comp_Prebuf.size + uncompressedSize)) ||
(in >= p->size)) {
printf("Corrupted stream\n");
exit(-1);
}
dst[out++] = src[in++];
}
}
// copy it back without the prebuffered data
src = dst;
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + comp_Prebuf.size, uncompressedSize);
free(src);
*size = uncompressedSize;
free(comp_Prebuf.data);
return dst;
} else { // unknown magic number
printf("Unknown compression type (magic number %x)\n", magic);
}
free(comp_Prebuf.data);
return NULL;
} | BYTE *DecompressRTF(variableLength *p, int *size) {
BYTE *dst; // destination for uncompressed bytes
BYTE *src;
unsigned int in;
unsigned int out;
variableLength comp_Prebuf;
ULONG compressedSize, uncompressedSize, magic;
comp_Prebuf.size = strlen(RTF_PREBUF);
comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);
ALLOCCHECK_CHAR(comp_Prebuf.data);
memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);
src = p->data;
in = 0;
if (p->size < 20) {
printf("File too small\n");
return(NULL);
}
compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
in += 4;
in += 4;
// check size excluding the size field itself
if (compressedSize != p->size - 4) {
printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4);
free(comp_Prebuf.data);
return NULL;
}
// process the data
if (magic == 0x414c454d) {
// magic number that identifies the stream as a uncompressed stream
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + 4, uncompressedSize);
} else if (magic == 0x75465a4c) {
// magic number that identifies the stream as a compressed stream
int flagCount = 0;
int flags = 0;
// Prevent overflow on 32 Bit Systems
if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {
printf("Corrupted file\n");
exit(-1);
}
dst = calloc(comp_Prebuf.size + uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);
out = comp_Prebuf.size;
while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) {
// each flag byte flags 8 literals/references, 1 per bit
flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;
if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal
unsigned int offset = src[in++];
unsigned int length = src[in++];
unsigned int end;
offset = (offset << 4) | (length >> 4); // the offset relative to block start
length = (length & 0xF) + 2; // the number of bytes to copy
// the decompression buffer is supposed to wrap around back
// to the beginning when the end is reached. we save the
// need for such a buffer by pointing straight into the data
// buffer, and simulating this behaviour by modifying the
// pointers appropriately.
offset = (out / 4096) * 4096 + offset;
if (offset >= out) // take from previous block
offset -= 4096;
// note: can't use System.arraycopy, because the referenced
// bytes can cross through the current out position.
end = offset + length;
while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))
&& (offset < (comp_Prebuf.size + uncompressedSize)))
dst[out++] = dst[offset++];
} else { // literal
if ((out >= (comp_Prebuf.size + uncompressedSize)) ||
(in >= p->size)) {
printf("Corrupted stream\n");
exit(-1);
}
dst[out++] = src[in++];
}
}
// copy it back without the prebuffered data
src = dst;
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + comp_Prebuf.size, uncompressedSize);
free(src);
*size = uncompressedSize;
free(comp_Prebuf.data);
return dst;
} else { // unknown magic number
printf("Unknown compression type (magic number %x)\n", magic);
}
free(comp_Prebuf.data);
return NULL;
} | {
"deleted": [
{
"line_no": 55,
"char_start": 1641,
"char_end": 1699,
"line": " while (out < (comp_Prebuf.size + uncompressedSize)) {\n"
}
],
"added": [
{
"line_no": 55,
"char_start": 1641,
"char_end": 1719,
"line": " while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1652,
"char_end": 1653,
"chars": "("
},
{
"char_start": 1692,
"char_end": 1711,
"chars": "ize)) && (in < p->s"
}
]
} | github.com/Yeraze/ytnef/commit/22f8346c8d4f0020a40d9f258fdb3bfc097359cc | lib/ytnef.c | cwe-125 |
ReadSGIImage | static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
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 SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*
iris_info.bytes_per_pixel,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
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 SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | {
"deleted": [
{
"line_no": 102,
"char_start": 2912,
"char_end": 2962,
"line": " image->depth=(size_t) MagickMin((size_t) 8*\n"
},
{
"line_no": 103,
"char_start": 2962,
"char_end": 3023,
"line": " iris_info.bytes_per_pixel,MAGICKCORE_QUANTUM_DEPTH);\n"
}
],
"added": [
{
"line_no": 102,
"char_start": 2912,
"char_end": 2988,
"line": " image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,\n"
},
{
"line_no": 103,
"char_start": 2988,
"char_end": 3023,
"line": " MAGICKCORE_QUANTUM_DEPTH);\n"
},
{
"line_no": 109,
"char_start": 3177,
"char_end": 3216,
"line": " if (EOFBlob(image) != MagickFalse)\n"
},
{
"line_no": 110,
"char_start": 3216,
"char_end": 3285,
"line": " ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n"
}
]
} | {
"deleted": [
{
"char_start": 2961,
"char_end": 2970,
"chars": "\n "
}
],
"added": [
{
"char_start": 2987,
"char_end": 2996,
"chars": "\n "
},
{
"char_start": 3176,
"char_end": 3284,
"chars": "\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");"
}
]
} | github.com/ImageMagick/ImageMagick/commit/7afcf9f71043df15508e46f079387bd4689a738d | coders/sgi.c | cwe-125 |
dnxhd_decode_header | static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
// make sure profile size constraints are respected
// DNx100 allows 1920->1440 and 1280->960 subsampling
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
// Newer format supports variable mb_scan_index sizes
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68 ||
(ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
} | static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
// make sure profile size constraints are respected
// DNx100 allows 1920->1440 and 1280->960 subsampling
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
// Newer format supports variable mb_scan_index sizes
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
} | {
"deleted": [
{
"line_no": 126,
"char_start": 4820,
"char_end": 4855,
"line": " if (ctx->mb_height > 68 ||\n"
},
{
"line_no": 127,
"char_start": 4855,
"char_end": 4940,
"line": " (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n"
}
],
"added": [
{
"line_no": 126,
"char_start": 4820,
"char_end": 4855,
"line": " if (ctx->mb_height > 68) {\n"
},
{
"line_no": 133,
"char_start": 5053,
"char_end": 5134,
"line": " if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n"
},
{
"line_no": 134,
"char_start": 5134,
"char_end": 5175,
"line": " av_log(ctx->avctx, AV_LOG_ERROR,\n"
},
{
"line_no": 135,
"char_start": 5175,
"char_end": 5235,
"line": " \"mb height too big: %d\\n\", ctx->mb_height);\n"
},
{
"line_no": 136,
"char_start": 5235,
"char_end": 5271,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 137,
"char_start": 5271,
"char_end": 5277,
"line": " }\n"
}
]
} | {
"deleted": [
{
"char_start": 4851,
"char_end": 4936,
"chars": " ||\n (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4"
},
{
"char_start": 5098,
"char_end": 5098,
"chars": ""
}
],
"added": [
{
"char_start": 4855,
"char_end": 4855,
"chars": ""
},
{
"char_start": 5045,
"char_end": 5269,
"chars": ";\n }\n if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n av_log(ctx->avctx, AV_LOG_ERROR,\n \"mb height too big: %d\\n\", ctx->mb_height);\n return AVERROR_INVALIDDATA"
}
]
} | github.com/FFmpeg/FFmpeg/commit/296debd213bd6dce7647cedd34eb64e5b94cdc92 | libavcodec/dnxhddec.c | cwe-125 |
WriteHDRImage | static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MagickPathExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MagickPathExtent);
length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MagickPathExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
} | static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MagickPathExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MagickPathExtent);
length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",
image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MagickPathExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels));
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
} | {
"deleted": [
{
"line_no": 69,
"char_start": 1901,
"char_end": 1984,
"line": " count=FormatLocaleString(header,MagickPathExtent,\"GAMMA=%g\\n\",image->gamma);\n"
},
{
"line_no": 87,
"char_start": 2886,
"char_end": 2952,
"line": " pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*\n"
}
],
"added": [
{
"line_no": 69,
"char_start": 1901,
"char_end": 1970,
"line": " count=FormatLocaleString(header,MagickPathExtent,\"GAMMA=%g\\n\",\n"
},
{
"line_no": 70,
"char_start": 1970,
"char_end": 1993,
"line": " image->gamma);\n"
},
{
"line_no": 88,
"char_start": 2895,
"char_end": 2965,
"line": " pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4*\n"
},
{
"line_no": 92,
"char_start": 3098,
"char_end": 3175,
"line": " (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1969,
"char_end": 1978,
"chars": "\n "
},
{
"char_start": 2957,
"char_end": 2961,
"chars": "+128"
},
{
"char_start": 3095,
"char_end": 3172,
"chars": ");\n (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels)"
}
]
} | github.com/ImageMagick/ImageMagick/commit/14e606db148d6ebcaae20f1e1d6d71903ca4a556 | coders/hdr.c | cwe-125 |
voutf | static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
} | static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut + 1;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
} | {
"deleted": [
{
"line_no": 35,
"char_start": 890,
"char_end": 910,
"line": " len -= cut;\n"
}
],
"added": [
{
"line_no": 35,
"char_start": 890,
"char_end": 914,
"line": " len -= cut + 1;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 908,
"char_end": 912,
"chars": " + 1"
}
]
} | github.com/curl/curl/commit/d530e92f59ae9bb2d47066c3c460b25d2ffeb211 | src/tool_msgs.c | cwe-125 |
pure_strcmp | int pure_strcmp(const char * const s1, const char * const s2)
{
return pure_memcmp(s1, s2, strlen(s1) + 1U);
} | int pure_strcmp(const char * const s1, const char * const s2)
{
const size_t s1_len = strlen(s1);
const size_t s2_len = strlen(s2);
if (s1_len != s2_len) {
return -1;
}
return pure_memcmp(s1, s2, s1_len);
} | {
"deleted": [
{
"line_no": 3,
"char_start": 64,
"char_end": 113,
"line": " return pure_memcmp(s1, s2, strlen(s1) + 1U);\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 64,
"char_end": 102,
"line": " const size_t s1_len = strlen(s1);\n"
},
{
"line_no": 4,
"char_start": 102,
"char_end": 140,
"line": " const size_t s2_len = strlen(s2);\n"
},
{
"line_no": 5,
"char_start": 140,
"char_end": 141,
"line": "\n"
},
{
"line_no": 6,
"char_start": 141,
"char_end": 169,
"line": " if (s1_len != s2_len) {\n"
},
{
"line_no": 7,
"char_start": 169,
"char_end": 188,
"line": " return -1;\n"
},
{
"line_no": 8,
"char_start": 188,
"char_end": 194,
"line": " }\n"
},
{
"line_no": 9,
"char_start": 194,
"char_end": 234,
"line": " return pure_memcmp(s1, s2, s1_len);\n"
}
]
} | {
"deleted": [
{
"char_start": 96,
"char_end": 98,
"chars": "tr"
},
{
"char_start": 101,
"char_end": 110,
"chars": "(s1) + 1U"
}
],
"added": [
{
"char_start": 68,
"char_end": 198,
"chars": "const size_t s1_len = strlen(s1);\n const size_t s2_len = strlen(s2);\n\n if (s1_len != s2_len) {\n return -1;\n }\n "
},
{
"char_start": 226,
"char_end": 228,
"chars": "1_"
}
]
} | github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e | src/utils.c | cwe-125 |
read_quant_matrix_ext | static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
} | static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
return 0;
} | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 72,
"line": "static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 71,
"line": "static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n"
},
{
"line_no": 6,
"char_start": 116,
"char_end": 154,
"line": " if (get_bits_left(gb) < 64*8)\n"
},
{
"line_no": 7,
"char_start": 154,
"char_end": 194,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 18,
"char_start": 490,
"char_end": 528,
"line": " if (get_bits_left(gb) < 64*8)\n"
},
{
"line_no": 19,
"char_start": 528,
"char_end": 568,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 27,
"char_start": 715,
"char_end": 753,
"line": " if (get_bits_left(gb) < 64*8)\n"
},
{
"line_no": 28,
"char_start": 753,
"char_end": 793,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 38,
"char_start": 1053,
"char_end": 1091,
"line": " if (get_bits_left(gb) < 64*8)\n"
},
{
"line_no": 39,
"char_start": 1091,
"char_end": 1131,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 47,
"char_start": 1292,
"char_end": 1306,
"line": " return 0;\n"
}
]
} | {
"deleted": [
{
"char_start": 7,
"char_end": 9,
"chars": "vo"
},
{
"char_start": 10,
"char_end": 11,
"chars": "d"
}
],
"added": [
{
"char_start": 8,
"char_end": 10,
"chars": "nt"
},
{
"char_start": 115,
"char_end": 193,
"chars": "\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;"
},
{
"char_start": 490,
"char_end": 568,
"chars": " if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n"
},
{
"char_start": 715,
"char_end": 793,
"chars": " if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n"
},
{
"char_start": 1053,
"char_end": 1131,
"chars": " if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n"
},
{
"char_start": 1290,
"char_end": 1304,
"chars": ";\n return 0"
}
]
} | github.com/FFmpeg/FFmpeg/commit/5aba5b89d0b1d73164d3b81764828bb8b20ff32a | libavcodec/mpeg4videodec.c | cwe-125 |
Cipher::blowfishECB | QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
//do padding ourselves
if (direction)
{
while ((temp.length() % 8) != 0) temp.append('\0');
}
else
{
temp = b64ToByte(temp);
while ((temp.length() % 8) != 0) temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
temp2 += cipher.final().toByteArray();
if (!cipher.ok())
return cipherText;
if (direction)
temp2 = byteToB64(temp2);
return temp2;
} | QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
//do padding ourselves
if (direction)
{
while ((temp.length() % 8) != 0) temp.append('\0');
}
else
{
// ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
if ((temp.length() % 12) != 0)
return cipherText;
temp = b64ToByte(temp);
while ((temp.length() % 8) != 0) temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
temp2 += cipher.final().toByteArray();
if (!cipher.ok())
return cipherText;
if (direction) {
// Sanity check
if ((temp2.length() % 8) != 0)
return cipherText;
temp2 = byteToB64(temp2);
}
return temp2;
} | {
"deleted": [
{
"line_no": 25,
"char_start": 689,
"char_end": 708,
"line": " if (direction)\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 358,
"char_end": 397,
"line": " if ((temp.length() % 12) != 0)\n"
},
{
"line_no": 15,
"char_start": 397,
"char_end": 428,
"line": " return cipherText;\n"
},
{
"line_no": 16,
"char_start": 428,
"char_end": 429,
"line": "\n"
},
{
"line_no": 29,
"char_start": 851,
"char_end": 872,
"line": " if (direction) {\n"
},
{
"line_no": 31,
"char_start": 896,
"char_end": 935,
"line": " if ((temp2.length() % 8) != 0)\n"
},
{
"line_no": 32,
"char_start": 935,
"char_end": 966,
"line": " return cipherText;\n"
},
{
"line_no": 33,
"char_start": 966,
"char_end": 967,
"line": "\n"
},
{
"line_no": 35,
"char_start": 1001,
"char_end": 1007,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 275,
"char_end": 437,
"chars": "// ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input\n if ((temp.length() % 12) != 0)\n return cipherText;\n\n "
},
{
"char_start": 869,
"char_end": 966,
"chars": " {\n // Sanity check\n if ((temp2.length() % 8) != 0)\n return cipherText;\n"
},
{
"char_start": 1000,
"char_end": 1006,
"chars": "\n }"
}
]
} | github.com/quassel/quassel/commit/8b5ecd226f9208af3074b33d3b7cf5e14f55b138 | src/core/cipher.cpp | cwe-125 |
java_switch_op | static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
// handle a table switch condition
if (pos + 8 > len) {
return op->size;
}
int min_val = (ut32)(UINT (data, pos + 4)),
max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
//ut32 value = (ut32)(UINT (data, pos));
if (pos + 4 >= len) {
// switch is too big cant read further
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
} | static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
// handle a table switch condition
if (pos + 8 + 8 > len) {
return op->size;
}
const int min_val = (ut32)(UINT (data, pos + 4));
const int max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
//ut32 value = (ut32)(UINT (data, pos));
if (pos + 4 >= len) {
// switch is too big cant read further
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
} | {
"deleted": [
{
"line_no": 8,
"char_start": 277,
"char_end": 300,
"line": "\t\tif (pos + 8 > len) {\n"
},
{
"line_no": 11,
"char_start": 324,
"char_end": 370,
"line": "\t\tint min_val = (ut32)(UINT (data, pos + 4)),\n"
},
{
"line_no": 12,
"char_start": 370,
"char_end": 413,
"line": "\t\t\tmax_val = (ut32)(UINT (data, pos + 8));\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 277,
"char_end": 304,
"line": "\t\tif (pos + 8 + 8 > len) {\n"
},
{
"line_no": 11,
"char_start": 328,
"char_end": 380,
"line": "\t\tconst int min_val = (ut32)(UINT (data, pos + 4));\n"
},
{
"line_no": 12,
"char_start": 380,
"char_end": 432,
"line": "\t\tconst int max_val = (ut32)(UINT (data, pos + 8));\n"
}
]
} | {
"deleted": [
{
"char_start": 368,
"char_end": 369,
"chars": ","
},
{
"char_start": 372,
"char_end": 373,
"chars": "\t"
}
],
"added": [
{
"char_start": 291,
"char_end": 295,
"chars": "+ 8 "
},
{
"char_start": 330,
"char_end": 336,
"chars": "const "
},
{
"char_start": 378,
"char_end": 379,
"chars": ";"
},
{
"char_start": 382,
"char_end": 392,
"chars": "const int "
}
]
} | github.com/radare/radare2/commit/224e6bc13fa353dd3b7f7a2334588f1c4229e58d | libr/anal/p/anal_java.c | cwe-125 |
ntlm_read_NegotiateMessage | SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
} | SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
} | {
"deleted": [],
"added": [
{
"line_no": 25,
"char_start": 592,
"char_end": 631,
"line": "\tif (Stream_GetRemainingLength(s) < 4)\n"
},
{
"line_no": 26,
"char_start": 631,
"char_end": 634,
"line": "\t{\n"
},
{
"line_no": 27,
"char_start": 634,
"char_end": 659,
"line": "\t\tStream_Free(s, FALSE);\n"
},
{
"line_no": 28,
"char_start": 659,
"char_end": 689,
"line": "\t\treturn SEC_E_INVALID_TOKEN;\n"
},
{
"line_no": 29,
"char_start": 689,
"char_end": 692,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 593,
"char_end": 693,
"chars": "if (Stream_GetRemainingLength(s) < 4)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\t"
}
]
} | github.com/FreeRDP/FreeRDP/commit/8fa38359634a9910b91719818ab02f23c320dbae | winpr/libwinpr/sspi/NTLM/ntlm_message.c | cwe-125 |
enc_untrusted_inet_ntop | const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,
socklen_t size) {
if (!src || !dst) {
errno = EFAULT;
return nullptr;
}
size_t src_size = 0;
if (af == AF_INET) {
src_size = sizeof(struct in_addr);
} else if (af == AF_INET6) {
src_size = sizeof(struct in6_addr);
} else {
errno = EAFNOSUPPORT;
return nullptr;
}
MessageWriter input;
input.Push<int>(TokLinuxAfFamily(af));
input.PushByReference(Extent{reinterpret_cast<const char *>(src), src_size});
input.Push(size);
MessageReader output;
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kInetNtopHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_inet_ntop", 2);
auto result = output.next();
int klinux_errno = output.next<int>();
if (result.empty()) {
errno = FromkLinuxErrorNumber(klinux_errno);
return nullptr;
}
memcpy(dst, result.data(),
std::min(static_cast<size_t>(size),
static_cast<size_t>(INET6_ADDRSTRLEN)));
return dst;
} | const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,
socklen_t size) {
if (!src || !dst) {
errno = EFAULT;
return nullptr;
}
size_t src_size = 0;
if (af == AF_INET) {
src_size = sizeof(struct in_addr);
} else if (af == AF_INET6) {
src_size = sizeof(struct in6_addr);
} else {
errno = EAFNOSUPPORT;
return nullptr;
}
MessageWriter input;
input.Push<int>(TokLinuxAfFamily(af));
input.PushByReference(Extent{reinterpret_cast<const char *>(src), src_size});
input.Push(size);
MessageReader output;
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kInetNtopHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_inet_ntop", 2);
auto result = output.next();
int klinux_errno = output.next<int>();
if (result.empty()) {
errno = FromkLinuxErrorNumber(klinux_errno);
return nullptr;
}
memcpy(
dst, result.data(),
std::min({static_cast<size_t>(size), static_cast<size_t>(result.size()),
static_cast<size_t>(INET6_ADDRSTRLEN)}));
return dst;
} | {
"deleted": [
{
"line_no": 34,
"char_start": 953,
"char_end": 982,
"line": " memcpy(dst, result.data(),\n"
},
{
"line_no": 35,
"char_start": 982,
"char_end": 1027,
"line": " std::min(static_cast<size_t>(size),\n"
},
{
"line_no": 36,
"char_start": 1027,
"char_end": 1086,
"line": " static_cast<size_t>(INET6_ADDRSTRLEN)));\n"
}
],
"added": [
{
"line_no": 34,
"char_start": 953,
"char_end": 963,
"line": " memcpy(\n"
},
{
"line_no": 35,
"char_start": 963,
"char_end": 989,
"line": " dst, result.data(),\n"
},
{
"line_no": 36,
"char_start": 989,
"char_end": 1068,
"line": " std::min({static_cast<size_t>(size), static_cast<size_t>(result.size()),\n"
},
{
"line_no": 37,
"char_start": 1068,
"char_end": 1126,
"line": " static_cast<size_t>(INET6_ADDRSTRLEN)}));\n"
}
]
} | {
"deleted": [
{
"char_start": 988,
"char_end": 991,
"chars": " "
},
{
"char_start": 1026,
"char_end": 1027,
"chars": "\n"
},
{
"char_start": 1028,
"char_end": 1029,
"chars": " "
}
],
"added": [
{
"char_start": 962,
"char_end": 969,
"chars": "\n "
},
{
"char_start": 1004,
"char_end": 1005,
"chars": "{"
},
{
"char_start": 1031,
"char_end": 1067,
"chars": " static_cast<size_t>(result.size()),"
},
{
"char_start": 1121,
"char_end": 1122,
"chars": "}"
}
]
} | github.com/google/asylo/commit/6ff3b77ffe110a33a2f93848a6333f33616f02c4 | asylo/platform/host_call/trusted/host_calls.cc | cwe-125 |
ndpi_search_oracle | void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)
{
struct ndpi_packet_struct *packet = &flow->packet;
u_int16_t dport = 0, sport = 0;
NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n");
if(packet->tcp != NULL) {
sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);
NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n");
/* Oracle Database 9g,10g,11g */
if ((dport == 1521 || sport == 1521)
&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))
|| ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01))
&& (packet->payload[1] != 0x00)
&& (packet->payload[2] == 0x00)
&& (packet->payload[3] == 0x00)))) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
} else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&
packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&
packet->payload[3] == 0x00 ) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
}
} else {
NDPI_EXCLUDE_PROTO(ndpi_struct, flow);
}
} | void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)
{
struct ndpi_packet_struct *packet = &flow->packet;
u_int16_t dport = 0, sport = 0;
NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n");
if(packet->tcp != NULL) {
sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);
NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n");
/* Oracle Database 9g,10g,11g */
if ((dport == 1521 || sport == 1521)
&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))
|| ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01))
&& (packet->payload[1] != 0x00)
&& (packet->payload[2] == 0x00)
&& (packet->payload[3] == 0x00)))) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
} else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&
packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&
packet->payload[3] == 0x00 ) {
NDPI_LOG_INFO(ndpi_struct, "found oracle\n");
ndpi_int_oracle_add_connection(ndpi_struct, flow);
}
} else {
NDPI_EXCLUDE_PROTO(ndpi_struct, flow);
}
} | {
"deleted": [
{
"line_no": 13,
"char_start": 489,
"char_end": 590,
"line": "\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 489,
"char_end": 625,
"line": "\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 512,
"char_end": 547,
"chars": "_packet_len >= 3 && packet->payload"
}
]
} | github.com/ntop/nDPI/commit/b69177be2fbe01c2442239a61832c44e40136c05 | src/lib/protocols/oracle.c | cwe-125 |
rtc_irq_eoi_tracking_reset | static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)
{
ioapic->rtc_status.pending_eoi = 0;
bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);
} | static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)
{
ioapic->rtc_status.pending_eoi = 0;
bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);
} | {
"deleted": [
{
"line_no": 4,
"char_start": 105,
"char_end": 167,
"line": "\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 105,
"char_end": 169,
"line": "\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);\n"
}
]
} | {
"deleted": [
{
"char_start": 163,
"char_end": 164,
"chars": "S"
}
],
"added": [
{
"char_start": 163,
"char_end": 166,
"chars": "_ID"
}
]
} | github.com/torvalds/linux/commit/81cdb259fb6d8c1c4ecfeea389ff5a73c07f5755 | arch/x86/kvm/ioapic.c | cwe-125 |
concat_hash_string | static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet,
char *buf, u_int8_t client_hash) {
u_int16_t offset = 22, buf_out_len = 0;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4;
/* -1 for ';' */
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
/* ssh.kex_algorithms [C/S] */
strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len);
buf[buf_out_len++] = ';';
offset += len;
/* ssh.server_host_key_algorithms [None] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4 + len;
/* ssh.encryption_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.encryption_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.mac_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.mac_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.compression_algorithms_client_to_server [C] */
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
/* ssh.compression_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
/* ssh.languages_client_to_server [None] */
/* ssh.languages_server_to_client [None] */
#ifdef SSH_DEBUG
printf("[SSH] %s\n", buf);
#endif
return(buf_out_len);
invalid_payload:
#ifdef SSH_DEBUG
printf("[SSH] Invalid packet payload\n");
#endif
return(0);
} | static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet,
char *buf, u_int8_t client_hash) {
u_int16_t offset = 22, buf_out_len = 0;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4;
/* -1 for ';' */
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
/* ssh.kex_algorithms [C/S] */
strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len);
buf[buf_out_len++] = ';';
offset += len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.server_host_key_algorithms [None] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4 + len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.encryption_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.encryption_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.mac_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.mac_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.compression_algorithms_client_to_server [C] */
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
/* ssh.compression_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
/* ssh.languages_client_to_server [None] */
/* ssh.languages_server_to_client [None] */
#ifdef SSH_DEBUG
printf("[SSH] %s\n", buf);
#endif
return(buf_out_len);
invalid_payload:
#ifdef SSH_DEBUG
printf("[SSH] Invalid packet payload\n");
#endif
return(0);
} | {
"deleted": [],
"added": [
{
"line_no": 18,
"char_start": 615,
"char_end": 676,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 19,
"char_start": 676,
"char_end": 702,
"line": " goto invalid_payload;\n"
},
{
"line_no": 24,
"char_start": 824,
"char_end": 885,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 25,
"char_start": 885,
"char_end": 911,
"line": " goto invalid_payload;\n"
},
{
"line_no": 42,
"char_start": 1366,
"char_end": 1427,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 43,
"char_start": 1427,
"char_end": 1453,
"line": " goto invalid_payload;\n"
},
{
"line_no": 60,
"char_start": 1909,
"char_end": 1970,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 61,
"char_start": 1970,
"char_end": 1996,
"line": " goto invalid_payload;\n"
},
{
"line_no": 78,
"char_start": 2444,
"char_end": 2505,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 79,
"char_start": 2505,
"char_end": 2531,
"line": " goto invalid_payload;\n"
},
{
"line_no": 113,
"char_start": 3493,
"char_end": 3554,
"line": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n"
},
{
"line_no": 114,
"char_start": 3554,
"char_end": 3580,
"line": " goto invalid_payload;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 617,
"char_end": 704,
"chars": "if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n "
},
{
"char_start": 823,
"char_end": 910,
"chars": "\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;"
},
{
"char_start": 1366,
"char_end": 1453,
"chars": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n"
},
{
"char_start": 1909,
"char_end": 1996,
"chars": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n"
},
{
"char_start": 2444,
"char_end": 2531,
"chars": " if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n"
},
{
"char_start": 3492,
"char_end": 3579,
"chars": "\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;"
}
]
} | github.com/ntop/nDPI/commit/3bbb0cd3296023f6f922c71d21a1c374d2b0a435 | src/lib/protocols/ssh.c | cwe-125 |
DecodePSDPixels | static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
CheckNumberCompactPixels;
compact_pixels++;
}
}
return(i);
} | static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
} | {
"deleted": [
{
"line_no": 124,
"char_start": 3556,
"char_end": 3588,
"line": " CheckNumberCompactPixels;\n"
}
],
"added": [
{
"line_no": 86,
"char_start": 2325,
"char_end": 2357,
"line": " CheckNumberCompactPixels;\n"
}
]
} | {
"deleted": [
{
"char_start": 3555,
"char_end": 3587,
"chars": "\n CheckNumberCompactPixels;"
}
],
"added": [
{
"char_start": 2331,
"char_end": 2363,
"chars": "CheckNumberCompactPixels;\n "
}
]
} | github.com/ImageMagick/ImageMagick/commit/30eec879c8b446b0ea9a3bb0da1a441cc8482bc4 | coders/psd.c | cwe-125 |
_6502_op | static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
// undocumented or not-implemented opcodes for 6502.
// some of them might be implemented in 65816
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
// BRK
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
// override 65816 code which seems to be wrong: size is 1, but pc = pc + 2
op->size = 1;
// PC + 2 to Stack, P to Stack B=1 D=0 I=1. "B" is not a flag. Only its bit is pushed on the stack
// PC was already incremented by one at this point. Needs to incremented once more
// New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502)
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
// FLAGS
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
// FIXME: what opcode for this?
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
// BIT
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
// ADC
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
// fix Z
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
// SBC
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// fix Z and revert C
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
// ORA
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// AND
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// EOR
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ASL
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LSR
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROL
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROR
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
// uses N as temporary to hold C value. but in fact,
// it is not temporary since in all ROR ops, N will have the value of C
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INC
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// DEC
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INX, INY
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
// DEX, DEY
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
// CMP
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPX
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPY
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// BRANCHES
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
// FIXME: Add 1 if branch occurs to same page.
// FIXME: Add 2 if branch occurs to different page
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (data[1] <= 127)
op->jump = addr + data[1] + op->size;
else op->jump = addr - (256 - data[1]) + op->size;
op->fail = addr + op->size;
// FIXME: add a type of conditional
// op->cond = R_ANAL_COND_LE;
_6502_anal_esil_ccall (op, data[0]);
break;
// JSR
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
// JSR pushes the address-1 of the next operation on to the stack before transferring program
// control to the following address
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
// JMP
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
// FIXME: how to read memory?
// op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
// RTS
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
// Operation: PC from Stack, PC + 1 -> PC
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
// RTI
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
// Operation: P from Stack, PC from Stack
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
// NOP
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
// LDA
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDX
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDY
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// STA
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
// STX
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
// STY
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
// PHP/PHA
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
// PLP,PLA
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
// TAX,TYA,...
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
// FIXME: should I get register X a place it here?
// op->stackptr = get_register_x();
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
} | static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
// undocumented or not-implemented opcodes for 6502.
// some of them might be implemented in 65816
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
// BRK
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
// override 65816 code which seems to be wrong: size is 1, but pc = pc + 2
op->size = 1;
// PC + 2 to Stack, P to Stack B=1 D=0 I=1. "B" is not a flag. Only its bit is pushed on the stack
// PC was already incremented by one at this point. Needs to incremented once more
// New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502)
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
// FLAGS
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
// FIXME: what opcode for this?
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
// BIT
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
// ADC
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
// fix Z
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
// SBC
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// fix Z and revert C
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
// ORA
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// AND
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// EOR
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ASL
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LSR
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROL
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROR
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
// uses N as temporary to hold C value. but in fact,
// it is not temporary since in all ROR ops, N will have the value of C
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INC
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// DEC
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INX, INY
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
// DEX, DEY
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
// CMP
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPX
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPY
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// BRANCHES
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
// FIXME: Add 1 if branch occurs to same page.
// FIXME: Add 2 if branch occurs to different page
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (len > 1) {
if (data[1] <= 127) {
op->jump = addr + data[1] + op->size;
} else {
op->jump = addr - (256 - data[1]) + op->size;
}
} else {
op->jump = addr;
}
op->fail = addr + op->size;
// FIXME: add a type of conditional
// op->cond = R_ANAL_COND_LE;
_6502_anal_esil_ccall (op, data[0]);
break;
// JSR
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
// JSR pushes the address-1 of the next operation on to the stack before transferring program
// control to the following address
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
// JMP
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
// FIXME: how to read memory?
// op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
// RTS
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
// Operation: PC from Stack, PC + 1 -> PC
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
// RTI
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
// Operation: P from Stack, PC from Stack
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
// NOP
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
// LDA
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDX
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDY
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// STA
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
// STX
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
// STY
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
// PHP/PHA
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
// PLP,PLA
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
// TAX,TYA,...
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
// FIXME: should I get register X a place it here?
// op->stackptr = get_register_x();
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
} | {
"deleted": [
{
"line_no": 397,
"char_start": 10823,
"char_end": 10845,
"line": "\t\tif (data[1] <= 127)\n"
},
{
"line_no": 398,
"char_start": 10845,
"char_end": 10886,
"line": "\t\t\top->jump = addr + data[1] + op->size;\n"
},
{
"line_no": 399,
"char_start": 10886,
"char_end": 10939,
"line": "\t\telse\top->jump = addr - (256 - data[1]) + op->size;\n"
}
],
"added": [
{
"line_no": 397,
"char_start": 10823,
"char_end": 10840,
"line": "\t\tif (len > 1) {\n"
},
{
"line_no": 398,
"char_start": 10840,
"char_end": 10865,
"line": "\t\t\tif (data[1] <= 127) {\n"
},
{
"line_no": 399,
"char_start": 10865,
"char_end": 10907,
"line": "\t\t\t\top->jump = addr + data[1] + op->size;\n"
},
{
"line_no": 400,
"char_start": 10907,
"char_end": 10919,
"line": "\t\t\t} else {\n"
},
{
"line_no": 401,
"char_start": 10919,
"char_end": 10969,
"line": "\t\t\t\top->jump = addr - (256 - data[1]) + op->size;\n"
},
{
"line_no": 402,
"char_start": 10969,
"char_end": 10974,
"line": "\t\t\t}\n"
},
{
"line_no": 403,
"char_start": 10974,
"char_end": 10985,
"line": "\t\t} else {\n"
},
{
"line_no": 404,
"char_start": 10985,
"char_end": 11005,
"line": "\t\t\top->jump = addr;\n"
},
{
"line_no": 405,
"char_start": 11005,
"char_end": 11009,
"line": "\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 10829,
"char_end": 10847,
"chars": "len > 1) {\n\t\t\tif ("
},
{
"char_start": 10862,
"char_end": 10864,
"chars": " {"
},
{
"char_start": 10865,
"char_end": 10866,
"chars": "\t"
},
{
"char_start": 10909,
"char_end": 10912,
"chars": "\t} "
},
{
"char_start": 10916,
"char_end": 10922,
"chars": " {\n\t\t\t"
},
{
"char_start": 10968,
"char_end": 11008,
"chars": "\n\t\t\t}\n\t\t} else {\n\t\t\top->jump = addr;\n\t\t}"
}
]
} | github.com/radare/radare2/commit/bbb4af56003c1afdad67af0c4339267ca38b1017 | libr/anal/p/anal_6502.c | cwe-125 |
string_scan_range | static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
ut8 *buf = calloc (to - from, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, to - from);
// may oobread
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
// string too long
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
// reduce false positives
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
// TODO: move into adjust_offset
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
} | static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
int len = to - from;
ut8 *buf = calloc (len, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, len);
// may oobread
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5 + rc) {
bool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
// string too long
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
// reduce false positives
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
// TODO: move into adjust_offset
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
} | {
"deleted": [
{
"line_no": 15,
"char_start": 418,
"char_end": 453,
"line": "\tut8 *buf = calloc (to - from, 1);\n"
},
{
"line_no": 19,
"char_start": 490,
"char_end": 538,
"line": "\tr_buf_read_at (bf->buf, from, buf, to - from);\n"
},
{
"line_no": 29,
"char_start": 768,
"char_end": 796,
"line": "\t\t\tif ((to - needle) > 5) {\n"
},
{
"line_no": 30,
"char_start": 796,
"char_end": 883,
"line": "\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 418,
"char_end": 440,
"line": "\tint len = to - from;\n"
},
{
"line_no": 16,
"char_start": 440,
"char_end": 469,
"line": "\tut8 *buf = calloc (len, 1);\n"
},
{
"line_no": 20,
"char_start": 506,
"char_end": 548,
"line": "\tr_buf_read_at (bf->buf, from, buf, len);\n"
},
{
"line_no": 30,
"char_start": 778,
"char_end": 811,
"line": "\t\t\tif ((to - needle) > 5 + rc) {\n"
},
{
"line_no": 31,
"char_start": 811,
"char_end": 902,
"line": "\t\t\t\tbool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);\n"
}
]
} | {
"deleted": [
{
"char_start": 438,
"char_end": 447,
"chars": "to - from"
},
{
"char_start": 526,
"char_end": 535,
"chars": "to - from"
}
],
"added": [
{
"char_start": 419,
"char_end": 441,
"chars": "int len = to - from;\n\t"
},
{
"char_start": 460,
"char_end": 463,
"chars": "len"
},
{
"char_start": 542,
"char_end": 545,
"chars": "len"
},
{
"char_start": 802,
"char_end": 807,
"chars": " + rc"
},
{
"char_start": 832,
"char_end": 833,
"chars": "("
},
{
"char_start": 853,
"char_end": 854,
"chars": ")"
},
{
"char_start": 858,
"char_end": 859,
"chars": "("
},
{
"char_start": 899,
"char_end": 900,
"chars": ")"
}
]
} | github.com/radare/radare2/commit/3fcf41ed96ffa25b38029449520c8d0a198745f3 | libr/bin/file.c | cwe-125 |
cx24116_send_diseqc_msg | static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* Validate length */
if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))
return -EINVAL;
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
} | static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Validate length */
if (d->msg_len > sizeof(d->msg))
return -EINVAL;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
} | {
"deleted": [
{
"line_no": 18,
"char_start": 429,
"char_end": 452,
"line": "\t/* Validate length */\n"
},
{
"line_no": 19,
"char_start": 452,
"char_end": 512,
"line": "\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n"
},
{
"line_no": 20,
"char_start": 512,
"char_end": 530,
"line": "\t\treturn -EINVAL;\n"
},
{
"line_no": 21,
"char_start": 530,
"char_end": 531,
"line": "\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 163,
"char_end": 186,
"line": "\t/* Validate length */\n"
},
{
"line_no": 8,
"char_start": 186,
"char_end": 220,
"line": "\tif (d->msg_len > sizeof(d->msg))\n"
},
{
"line_no": 9,
"char_start": 220,
"char_end": 252,
"line": " return -EINVAL;\n"
},
{
"line_no": 10,
"char_start": 252,
"char_end": 253,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 427,
"char_end": 529,
"chars": "\n\n\t/* Validate length */\n\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n\t\treturn -EINVAL;"
}
],
"added": [
{
"char_start": 167,
"char_end": 257,
"chars": "Validate length */\n\tif (d->msg_len > sizeof(d->msg))\n return -EINVAL;\n\n\t/* "
}
]
} | github.com/torvalds/linux/commit/1fa2337a315a2448c5434f41e00d56b01a22283c | drivers/media/dvb-frontends/cx24116.c | cwe-125 |
MAPIPrint | void MAPIPrint(MAPIProps *p) {
int j, i, index, h, x;
DDWORD *ddword_ptr;
DDWORD ddword_tmp;
dtr thedate;
MAPIProperty *mapi;
variableLength *mapidata;
variableLength vlTemp;
int found;
for (j = 0; j < p->count; j++) {
mapi = &(p->properties[j]);
printf(" #%i: Type: [", j);
switch (PROP_TYPE(mapi->id)) {
case PT_UNSPECIFIED:
printf(" NONE "); break;
case PT_NULL:
printf(" NULL "); break;
case PT_I2:
printf(" I2 "); break;
case PT_LONG:
printf(" LONG "); break;
case PT_R4:
printf(" R4 "); break;
case PT_DOUBLE:
printf(" DOUBLE "); break;
case PT_CURRENCY:
printf("CURRENCY "); break;
case PT_APPTIME:
printf("APP TIME "); break;
case PT_ERROR:
printf(" ERROR "); break;
case PT_BOOLEAN:
printf(" BOOLEAN "); break;
case PT_OBJECT:
printf(" OBJECT "); break;
case PT_I8:
printf(" I8 "); break;
case PT_STRING8:
printf(" STRING8 "); break;
case PT_UNICODE:
printf(" UNICODE "); break;
case PT_SYSTIME:
printf("SYS TIME "); break;
case PT_CLSID:
printf("OLE GUID "); break;
case PT_BINARY:
printf(" BINARY "); break;
default:
printf("<%x>", PROP_TYPE(mapi->id)); break;
}
printf("] Code: [");
if (mapi->custom == 1) {
printf("UD:x%04x", PROP_ID(mapi->id));
} else {
found = 0;
for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {
if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {
printf("%s", MPList[index].name);
found = 1;
}
}
if (found == 0) {
printf("0x%04x", PROP_ID(mapi->id));
}
}
printf("]\n");
if (mapi->namedproperty > 0) {
for (i = 0; i < mapi->namedproperty; i++) {
printf(" Name: %s\n", mapi->propnames[i].data);
}
}
for (i = 0; i < mapi->count; i++) {
mapidata = &(mapi->data[i]);
if (mapi->count > 1) {
printf(" [%i/%u] ", i, mapi->count);
} else {
printf(" ");
}
printf("Size: %i", mapidata->size);
switch (PROP_TYPE(mapi->id)) {
case PT_SYSTIME:
MAPISysTimetoDTR(mapidata->data, &thedate);
printf(" Value: ");
ddword_tmp = *((DDWORD *)mapidata->data);
TNEFPrintDate(thedate);
printf(" [HEX: ");
for (x = 0; x < sizeof(ddword_tmp); x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("] (%llu)\n", ddword_tmp);
break;
case PT_LONG:
printf(" Value: %li\n", *((long*)mapidata->data));
break;
case PT_I2:
printf(" Value: %hi\n", *((short int*)mapidata->data));
break;
case PT_BOOLEAN:
if (mapi->data->data[0] != 0) {
printf(" Value: True\n");
} else {
printf(" Value: False\n");
}
break;
case PT_OBJECT:
printf("\n");
break;
case PT_BINARY:
if (IsCompressedRTF(mapidata) == 1) {
printf(" Detected Compressed RTF. ");
printf("Decompressed text follows\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {
printf("%s\n", vlTemp.data);
free(vlTemp.data);
}
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
} else {
printf(" Value: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_STRING8:
printf(" Value: [%s]\n", mapidata->data);
if (strlen((char*)mapidata->data) != mapidata->size - 1) {
printf("Detected Hidden data: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_CLSID:
printf(" Value: ");
printf("[HEX: ");
for(x=0; x< 16; x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("]\n");
break;
default:
printf(" Value: [%s]\n", mapidata->data);
}
}
}
} | void MAPIPrint(MAPIProps *p) {
int j, i, index, h, x;
DDWORD *ddword_ptr;
DDWORD ddword_tmp;
dtr thedate;
MAPIProperty *mapi;
variableLength *mapidata;
variableLength vlTemp;
int found;
for (j = 0; j < p->count; j++) {
mapi = &(p->properties[j]);
printf(" #%i: Type: [", j);
switch (PROP_TYPE(mapi->id)) {
case PT_UNSPECIFIED:
printf(" NONE "); break;
case PT_NULL:
printf(" NULL "); break;
case PT_I2:
printf(" I2 "); break;
case PT_LONG:
printf(" LONG "); break;
case PT_R4:
printf(" R4 "); break;
case PT_DOUBLE:
printf(" DOUBLE "); break;
case PT_CURRENCY:
printf("CURRENCY "); break;
case PT_APPTIME:
printf("APP TIME "); break;
case PT_ERROR:
printf(" ERROR "); break;
case PT_BOOLEAN:
printf(" BOOLEAN "); break;
case PT_OBJECT:
printf(" OBJECT "); break;
case PT_I8:
printf(" I8 "); break;
case PT_STRING8:
printf(" STRING8 "); break;
case PT_UNICODE:
printf(" UNICODE "); break;
case PT_SYSTIME:
printf("SYS TIME "); break;
case PT_CLSID:
printf("OLE GUID "); break;
case PT_BINARY:
printf(" BINARY "); break;
default:
printf("<%x>", PROP_TYPE(mapi->id)); break;
}
printf("] Code: [");
if (mapi->custom == 1) {
printf("UD:x%04x", PROP_ID(mapi->id));
} else {
found = 0;
for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {
if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {
printf("%s", MPList[index].name);
found = 1;
}
}
if (found == 0) {
printf("0x%04x", PROP_ID(mapi->id));
}
}
printf("]\n");
if (mapi->namedproperty > 0) {
for (i = 0; i < mapi->namedproperty; i++) {
printf(" Name: %s\n", mapi->propnames[i].data);
}
}
for (i = 0; i < mapi->count; i++) {
mapidata = &(mapi->data[i]);
if (mapi->count > 1) {
printf(" [%i/%u] ", i, mapi->count);
} else {
printf(" ");
}
printf("Size: %i", mapidata->size);
switch (PROP_TYPE(mapi->id)) {
case PT_SYSTIME:
MAPISysTimetoDTR(mapidata->data, &thedate);
printf(" Value: ");
ddword_tmp = *((DDWORD *)mapidata->data);
TNEFPrintDate(thedate);
printf(" [HEX: ");
for (x = 0; x < sizeof(ddword_tmp); x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("] (%llu)\n", ddword_tmp);
break;
case PT_LONG:
printf(" Value: %i\n", *((int*)mapidata->data));
break;
case PT_I2:
printf(" Value: %hi\n", *((short int*)mapidata->data));
break;
case PT_BOOLEAN:
if (mapi->data->data[0] != 0) {
printf(" Value: True\n");
} else {
printf(" Value: False\n");
}
break;
case PT_OBJECT:
printf("\n");
break;
case PT_BINARY:
if (IsCompressedRTF(mapidata) == 1) {
printf(" Detected Compressed RTF. ");
printf("Decompressed text follows\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {
printf("%s\n", vlTemp.data);
free(vlTemp.data);
}
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
} else {
printf(" Value: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_STRING8:
printf(" Value: [%s]\n", mapidata->data);
if (strlen((char*)mapidata->data) != mapidata->size - 1) {
printf("Detected Hidden data: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_CLSID:
printf(" Value: ");
printf("[HEX: ");
for(x=0; x< 16; x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("]\n");
break;
default:
printf(" Value: [%s]\n", mapidata->data);
}
}
}
} | {
"deleted": [
{
"line_no": 95,
"char_start": 2731,
"char_end": 2795,
"line": " printf(\" Value: %li\\n\", *((long*)mapidata->data));\n"
}
],
"added": [
{
"line_no": 95,
"char_start": 2731,
"char_end": 2793,
"line": " printf(\" Value: %i\\n\", *((int*)mapidata->data));\n"
}
]
} | {
"deleted": [
{
"char_start": 2761,
"char_end": 2762,
"chars": "l"
},
{
"char_start": 2771,
"char_end": 2773,
"chars": "lo"
},
{
"char_start": 2774,
"char_end": 2775,
"chars": "g"
}
],
"added": [
{
"char_start": 2770,
"char_end": 2771,
"chars": "i"
},
{
"char_start": 2772,
"char_end": 2773,
"chars": "t"
}
]
} | github.com/Yeraze/ytnef/commit/f98f5d4adc1c4bd4033638f6167c1bb95d642f89 | lib/ytnef.c | cwe-125 |
readContigTilesIntoBuffer | static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
uint32 tile_rowsize = TIFFTileRowSize(in);
uint32 src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(-1);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
}
tilebuf = _TIFFmalloc(tile_buffsize);
if (tilebuf == 0)
return 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
} | static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
uint32 tile_rowsize = TIFFTileRowSize(in);
uint32 src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(-1);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if( tile_buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
tilebuf = _TIFFmalloc(tile_buffsize + 3);
if (tilebuf == 0)
return 0;
tilebuf[tile_buffsize] = 0;
tilebuf[tile_buffsize+1] = 0;
tilebuf[tile_buffsize+2] = 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
} | {
"deleted": [
{
"line_no": 60,
"char_start": 1763,
"char_end": 1803,
"line": " tilebuf = _TIFFmalloc(tile_buffsize);\n"
}
],
"added": [
{
"line_no": 60,
"char_start": 1763,
"char_end": 1829,
"line": " /* Add 3 padding bytes for extractContigSamplesShifted32bits */\n"
},
{
"line_no": 61,
"char_start": 1829,
"char_end": 1869,
"line": " if( tile_buffsize > 0xFFFFFFFFU - 3 )\n"
},
{
"line_no": 62,
"char_start": 1869,
"char_end": 1873,
"line": " {\n"
},
{
"line_no": 63,
"char_start": 1873,
"char_end": 1969,
"line": " TIFFError(\"readContigTilesIntoBuffer\", \"Integer overflow when calculating buffer size.\");\n"
},
{
"line_no": 64,
"char_start": 1969,
"char_end": 1985,
"line": " exit(-1);\n"
},
{
"line_no": 65,
"char_start": 1985,
"char_end": 1989,
"line": " }\n"
},
{
"line_no": 66,
"char_start": 1989,
"char_end": 2033,
"line": " tilebuf = _TIFFmalloc(tile_buffsize + 3);\n"
},
{
"line_no": 69,
"char_start": 2067,
"char_end": 2097,
"line": " tilebuf[tile_buffsize] = 0;\n"
},
{
"line_no": 70,
"char_start": 2097,
"char_end": 2129,
"line": " tilebuf[tile_buffsize+1] = 0;\n"
},
{
"line_no": 71,
"char_start": 2129,
"char_end": 2161,
"line": " tilebuf[tile_buffsize+2] = 0;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1765,
"char_end": 1991,
"chars": "/* Add 3 padding bytes for extractContigSamplesShifted32bits */\n if( tile_buffsize > 0xFFFFFFFFU - 3 )\n {\n TIFFError(\"readContigTilesIntoBuffer\", \"Integer overflow when calculating buffer size.\");\n exit(-1);\n }\n "
},
{
"char_start": 2026,
"char_end": 2030,
"chars": " + 3"
},
{
"char_start": 2063,
"char_end": 2157,
"chars": " 0;\n tilebuf[tile_buffsize] = 0;\n tilebuf[tile_buffsize+1] = 0;\n tilebuf[tile_buffsize+2] ="
}
]
} | github.com/vadz/libtiff/commit/ae9365db1b271b62b35ce018eac8799b1d5e8a53 | tools/tiffcrop.c | cwe-125 |
TNEFParse | int TNEFParse(TNEFStruct *TNEF) {
WORD key;
DWORD type;
DWORD size;
DWORD signature;
BYTE *data;
WORD checksum, header_checksum;
int i;
if (TNEF->IO.ReadProc == NULL) {
printf("ERROR: Setup incorrectly: No ReadProc\n");
return YTNEF_INCORRECT_SETUP;
}
if (TNEF->IO.InitProc != NULL) {
DEBUG(TNEF->Debug, 2, "About to initialize");
if (TNEF->IO.InitProc(&TNEF->IO) != 0) {
return YTNEF_CANNOT_INIT_DATA;
}
DEBUG(TNEF->Debug, 2, "Initialization finished");
}
DEBUG(TNEF->Debug, 2, "Reading Signature");
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {
printf("ERROR: Error reading signature\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "Checking Signature");
if (TNEFCheckForSignature(signature) < 0) {
printf("ERROR: Signature does not match. Not TNEF.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NOT_TNEF_STREAM;
}
DEBUG(TNEF->Debug, 2, "Reading Key.");
if (TNEFGetKey(TNEF, &key) < 0) {
printf("ERROR: Unable to retrieve key.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NO_KEY;
}
DEBUG(TNEF->Debug, 2, "Starting Full Processing.");
while (TNEFGetHeader(TNEF, &type, &size) == 0) {
DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size);
DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size);
data = calloc(size, sizeof(BYTE));
ALLOCCHECK(data);
if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {
printf("ERROR: Unable to read data.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {
printf("ERROR: Unable to read checksum.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));
if (checksum != header_checksum) {
printf("ERROR: Checksum mismatch. Data corruption?:\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_BAD_CHECKSUM;
}
for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {
if (TNEFList[i].id == type) {
if (TNEFList[i].handler != NULL) {
if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {
free(data);
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_IN_HANDLER;
} else {
// Found our handler and processed it. now time to get out
break;
}
} else {
DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes",
TNEFList[i].name, size);
}
}
}
free(data);
}
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return 0;
} | int TNEFParse(TNEFStruct *TNEF) {
WORD key;
DWORD type;
DWORD size;
DWORD signature;
BYTE *data;
WORD checksum, header_checksum;
int i;
if (TNEF->IO.ReadProc == NULL) {
printf("ERROR: Setup incorrectly: No ReadProc\n");
return YTNEF_INCORRECT_SETUP;
}
if (TNEF->IO.InitProc != NULL) {
DEBUG(TNEF->Debug, 2, "About to initialize");
if (TNEF->IO.InitProc(&TNEF->IO) != 0) {
return YTNEF_CANNOT_INIT_DATA;
}
DEBUG(TNEF->Debug, 2, "Initialization finished");
}
DEBUG(TNEF->Debug, 2, "Reading Signature");
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {
printf("ERROR: Error reading signature\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "Checking Signature");
if (TNEFCheckForSignature(signature) < 0) {
printf("ERROR: Signature does not match. Not TNEF.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NOT_TNEF_STREAM;
}
DEBUG(TNEF->Debug, 2, "Reading Key.");
if (TNEFGetKey(TNEF, &key) < 0) {
printf("ERROR: Unable to retrieve key.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NO_KEY;
}
DEBUG(TNEF->Debug, 2, "Starting Full Processing.");
while (TNEFGetHeader(TNEF, &type, &size) == 0) {
DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size);
DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size);
if(size == 0) {
printf("ERROR: Field with size of 0\n");
return YTNEF_ERROR_READING_DATA;
}
data = calloc(size, sizeof(BYTE));
ALLOCCHECK(data);
if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {
printf("ERROR: Unable to read data.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {
printf("ERROR: Unable to read checksum.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));
if (checksum != header_checksum) {
printf("ERROR: Checksum mismatch. Data corruption?:\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_BAD_CHECKSUM;
}
for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {
if (TNEFList[i].id == type) {
if (TNEFList[i].handler != NULL) {
if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {
free(data);
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_IN_HANDLER;
} else {
// Found our handler and processed it. now time to get out
break;
}
} else {
DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes",
TNEFList[i].name, size);
}
}
}
free(data);
}
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 56,
"char_start": 1563,
"char_end": 1583,
"line": " if(size == 0) {\n"
},
{
"line_no": 57,
"char_start": 1583,
"char_end": 1630,
"line": " printf(\"ERROR: Field with size of 0\\n\");\n"
},
{
"line_no": 58,
"char_start": 1630,
"char_end": 1669,
"line": " return YTNEF_ERROR_READING_DATA;\n"
},
{
"line_no": 59,
"char_start": 1669,
"char_end": 1675,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1567,
"char_end": 1679,
"chars": "if(size == 0) {\n printf(\"ERROR: Field with size of 0\\n\");\n return YTNEF_ERROR_READING_DATA;\n }\n "
}
]
} | github.com/Yeraze/ytnef/commit/3cb0f914d6427073f262e1b2b5fd973e3043cdf7 | lib/ytnef.c | cwe-125 |
ssl_parse_server_key_exchange | static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
} | static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( p != end - sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
} | {
"deleted": [
{
"line_no": 229,
"char_start": 9573,
"char_end": 9606,
"line": " if( end != p + sig_len )\n"
}
],
"added": [
{
"line_no": 229,
"char_start": 9573,
"char_end": 9606,
"line": " if( p != end - sig_len )\n"
}
]
} | {
"deleted": [
{
"char_start": 9585,
"char_end": 9588,
"chars": "end"
},
{
"char_start": 9592,
"char_end": 9593,
"chars": "p"
},
{
"char_start": 9594,
"char_end": 9595,
"chars": "+"
}
],
"added": [
{
"char_start": 9585,
"char_end": 9586,
"chars": "p"
},
{
"char_start": 9590,
"char_end": 9593,
"chars": "end"
},
{
"char_start": 9594,
"char_end": 9595,
"chars": "-"
}
]
} | github.com/ARMmbed/mbedtls/commit/027f84c69f4ef30c0693832a6c396ef19e563ca1 | library/ssl_cli.c | cwe-125 |
HPHP::exif_scan_JPEG_header | static int exif_scan_JPEG_header(image_info_type *ImageInfo) {
int section, sn;
int marker = 0, last_marker = M_PSEUDO, comment_correction=1;
int ll, lh;
unsigned char *Data;
size_t fpos, size, got, itemlen;
jpeg_sof_info sof_info;
for(section=0;;section++) {
// get marker byte, swallowing possible padding
// some software does not count the length bytes of COM section
// one company doing so is very much envolved in JPEG...
// so we accept too
if (last_marker==M_COM && comment_correction) {
comment_correction = 2;
}
do {
if ((marker = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
if (last_marker==M_COM && comment_correction>0) {
if (marker!=0xFF) {
marker = 0xff;
comment_correction--;
} else {
last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */
}
}
} while (marker == 0xff);
if (last_marker==M_COM && !comment_correction) {
raise_notice("Image has corrupt COM section: some software set "
"wrong length information");
}
if (last_marker==M_COM && comment_correction)
return M_EOI; /* ah illegal: char after COM section not 0xFF */
fpos = ImageInfo->infile->tell();
if (marker == 0xff) {
// 0xff is legal padding, but if we get that many, something's wrong.
raise_warning("To many padding bytes");
return 0;
}
/* Read the length of the section. */
if ((lh = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
if ((ll = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
itemlen = (lh << 8) | ll;
if (itemlen < 2) {
raise_warning("File structure corrupted");
return 0;
}
sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr);
if (sn == -1) return 0;
Data = ImageInfo->file.list[sn].data;
/* Store first two pre-read bytes. */
Data[0] = (unsigned char)lh;
Data[1] = (unsigned char)ll;
String str = ImageInfo->infile->read(itemlen-2);
got = str.length();
if (got != itemlen-2) {
raise_warning("Error reading from file: "
"got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)",
got, got, itemlen-2, itemlen-2);
return 0;
}
memcpy(Data+2, str.c_str(), got);
switch(marker) {
case M_SOS: /* stop before hitting compressed data */
// If reading entire image is requested, read the rest of the data.
if (ImageInfo->read_all) {
/* Determine how much file is left. */
fpos = ImageInfo->infile->tell();
size = ImageInfo->FileSize - fpos;
sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr);
if (sn == -1) return 0;
Data = ImageInfo->file.list[sn].data;
str = ImageInfo->infile->read(size);
got = str.length();
if (got != size) {
raise_warning("Unexpected end of file reached");
return 0;
}
memcpy(Data, str.c_str(), got);
}
return 1;
case M_EOI: /* in case it's a tables-only JPEG stream */
raise_warning("No image in jpeg!");
return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0;
case M_COM: /* Comment section */
exif_process_COM(ImageInfo, (char *)Data, itemlen);
break;
case M_EXIF:
if (!(ImageInfo->sections_found&FOUND_IFD0)) {
/*ImageInfo->sections_found |= FOUND_EXIF;*/
/* Seen files from some 'U-lead' software with Vivitar scanner
that uses marker 31 later in the file (no clue what for!) */
exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos);
}
break;
case M_APP12:
exif_process_APP12(ImageInfo, (char *)Data, itemlen);
break;
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
exif_process_SOFn(Data, marker, &sof_info);
ImageInfo->Width = sof_info.width;
ImageInfo->Height = sof_info.height;
if (sof_info.num_components == 3) {
ImageInfo->IsColor = 1;
} else {
ImageInfo->IsColor = 0;
}
break;
default:
/* skip any other marker silently. */
break;
}
/* keep track of last marker */
last_marker = marker;
}
return 1;
} | static int exif_scan_JPEG_header(image_info_type *ImageInfo) {
int section, sn;
int marker = 0, last_marker = M_PSEUDO, comment_correction=1;
int ll, lh;
unsigned char *Data;
size_t fpos, size, got, itemlen;
jpeg_sof_info sof_info;
for(section=0;;section++) {
// get marker byte, swallowing possible padding
// some software does not count the length bytes of COM section
// one company doing so is very much envolved in JPEG...
// so we accept too
if (last_marker==M_COM && comment_correction) {
comment_correction = 2;
}
do {
if ((marker = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
if (last_marker==M_COM && comment_correction>0) {
if (marker!=0xFF) {
marker = 0xff;
comment_correction--;
} else {
last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */
}
}
} while (marker == 0xff);
if (last_marker==M_COM && !comment_correction) {
raise_notice("Image has corrupt COM section: some software set "
"wrong length information");
}
if (last_marker==M_COM && comment_correction)
return M_EOI; /* ah illegal: char after COM section not 0xFF */
fpos = ImageInfo->infile->tell();
if (marker == 0xff) {
// 0xff is legal padding, but if we get that many, something's wrong.
raise_warning("To many padding bytes");
return 0;
}
/* Read the length of the section. */
if ((lh = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
if ((ll = ImageInfo->infile->getc()) == EOF) {
raise_warning("File structure corrupted");
return 0;
}
itemlen = (lh << 8) | ll;
if (itemlen < 2) {
raise_warning("File structure corrupted");
return 0;
}
sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr);
if (sn == -1) return 0;
Data = ImageInfo->file.list[sn].data;
/* Store first two pre-read bytes. */
Data[0] = (unsigned char)lh;
Data[1] = (unsigned char)ll;
String str = ImageInfo->infile->read(itemlen-2);
got = str.length();
if (got != itemlen-2) {
raise_warning("Error reading from file: "
"got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)",
got, got, itemlen-2, itemlen-2);
return 0;
}
memcpy(Data+2, str.c_str(), got);
switch(marker) {
case M_SOS: /* stop before hitting compressed data */
// If reading entire image is requested, read the rest of the data.
if (ImageInfo->read_all) {
/* Determine how much file is left. */
fpos = ImageInfo->infile->tell();
size = ImageInfo->FileSize - fpos;
sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr);
if (sn == -1) return 0;
Data = ImageInfo->file.list[sn].data;
str = ImageInfo->infile->read(size);
got = str.length();
if (got != size) {
raise_warning("Unexpected end of file reached");
return 0;
}
memcpy(Data, str.c_str(), got);
}
return 1;
case M_EOI: /* in case it's a tables-only JPEG stream */
raise_warning("No image in jpeg!");
return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0;
case M_COM: /* Comment section */
exif_process_COM(ImageInfo, (char *)Data, itemlen);
break;
case M_EXIF:
if (!(ImageInfo->sections_found&FOUND_IFD0)) {
/*ImageInfo->sections_found |= FOUND_EXIF;*/
/* Seen files from some 'U-lead' software with Vivitar scanner
that uses marker 31 later in the file (no clue what for!) */
exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos);
}
break;
case M_APP12:
exif_process_APP12(ImageInfo, (char *)Data, itemlen);
break;
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
if ((itemlen - 2) < 6) {
return 0;
}
exif_process_SOFn(Data, marker, &sof_info);
ImageInfo->Width = sof_info.width;
ImageInfo->Height = sof_info.height;
if (sof_info.num_components == 3) {
ImageInfo->IsColor = 1;
} else {
ImageInfo->IsColor = 0;
}
break;
default:
/* skip any other marker silently. */
break;
}
/* keep track of last marker */
last_marker = marker;
}
return 1;
} | {
"deleted": [],
"added": [
{
"line_no": 137,
"char_start": 4277,
"char_end": 4310,
"line": " if ((itemlen - 2) < 6) {\n"
},
{
"line_no": 138,
"char_start": 4310,
"char_end": 4330,
"line": " return 0;\n"
},
{
"line_no": 139,
"char_start": 4330,
"char_end": 4340,
"line": " }\n"
},
{
"line_no": 140,
"char_start": 4340,
"char_end": 4341,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 4285,
"char_end": 4349,
"chars": "if ((itemlen - 2) < 6) {\n return 0;\n }\n\n "
}
]
} | github.com/facebook/hhvm/commit/f9680d21beaa9eb39d166e8810e29fbafa51ad15 | hphp/runtime/ext/gd/ext_gd.cpp | cwe-125 |
forward_search_range | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
} | forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
} | {
"deleted": [],
"added": [
{
"line_no": 18,
"char_start": 493,
"char_end": 494,
"line": "\n"
},
{
"line_no": 19,
"char_start": 494,
"char_end": 535,
"line": " if (q >= end) return 0; /* fail */\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 493,
"char_end": 535,
"chars": "\n if (q >= end) return 0; /* fail */\n"
}
]
} | github.com/kkos/oniguruma/commit/9690d3ab1f9bcd2db8cbe1fe3ee4a5da606b8814 | src/regexec.c | cwe-125 |
mpeg4_decode_studio_block | static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
} | static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
if (idx > 63)
return AVERROR_INVALIDDATA;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
if (idx > 63)
return AVERROR_INVALIDDATA;
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
if (idx > 63)
return AVERROR_INVALIDDATA;
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 86,
"char_start": 2920,
"char_end": 2946,
"line": " if (idx > 63)\n"
},
{
"line_no": 87,
"char_start": 2946,
"char_end": 2990,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 92,
"char_start": 3154,
"char_end": 3180,
"line": " if (idx > 63)\n"
},
{
"line_no": 93,
"char_start": 3180,
"char_end": 3224,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 98,
"char_start": 3380,
"char_end": 3406,
"line": " if (idx > 63)\n"
},
{
"line_no": 99,
"char_start": 3406,
"char_end": 3450,
"line": " return AVERROR_INVALIDDATA;\n"
}
]
} | {
"deleted": [
{
"char_start": 2954,
"char_end": 2954,
"chars": ""
},
{
"char_start": 3215,
"char_end": 3215,
"chars": ""
}
],
"added": [
{
"char_start": 2932,
"char_end": 3002,
"chars": "if (idx > 63)\n return AVERROR_INVALIDDATA;\n "
},
{
"char_start": 3154,
"char_end": 3224,
"chars": " if (idx > 63)\n return AVERROR_INVALIDDATA;\n"
},
{
"char_start": 3379,
"char_end": 3449,
"chars": "\n if (idx > 63)\n return AVERROR_INVALIDDATA;"
}
]
} | github.com/FFmpeg/FFmpeg/commit/d227ed5d598340e719eff7156b1aa0a4469e9a6a | libavcodec/mpeg4videodec.c | cwe-125 |
S_grok_bslash_N | S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
regnode ** node_p,
UV * code_point_p,
int * cp_count,
I32 * flagp,
const bool strict,
const U32 depth
)
{
/* This routine teases apart the various meanings of \N and returns
* accordingly. The input parameters constrain which meaning(s) is/are valid
* in the current context.
*
* Exactly one of <node_p> and <code_point_p> must be non-NULL.
*
* If <code_point_p> is not NULL, the context is expecting the result to be a
* single code point. If this \N instance turns out to a single code point,
* the function returns TRUE and sets *code_point_p to that code point.
*
* If <node_p> is not NULL, the context is expecting the result to be one of
* the things representable by a regnode. If this \N instance turns out to be
* one such, the function generates the regnode, returns TRUE and sets *node_p
* to point to that regnode.
*
* If this instance of \N isn't legal in any context, this function will
* generate a fatal error and not return.
*
* On input, RExC_parse should point to the first char following the \N at the
* time of the call. On successful return, RExC_parse will have been updated
* to point to just after the sequence identified by this routine. Also
* *flagp has been updated as needed.
*
* When there is some problem with the current context and this \N instance,
* the function returns FALSE, without advancing RExC_parse, nor setting
* *node_p, nor *code_point_p, nor *flagp.
*
* If <cp_count> is not NULL, the caller wants to know the length (in code
* points) that this \N sequence matches. This is set even if the function
* returns FALSE, as detailed below.
*
* There are 5 possibilities here, as detailed in the next 5 paragraphs.
*
* Probably the most common case is for the \N to specify a single code point.
* *cp_count will be set to 1, and *code_point_p will be set to that code
* point.
*
* Another possibility is for the input to be an empty \N{}, which for
* backwards compatibility we accept. *cp_count will be set to 0. *node_p
* will be set to a generated NOTHING node.
*
* Still another possibility is for the \N to mean [^\n]. *cp_count will be
* set to 0. *node_p will be set to a generated REG_ANY node.
*
* The fourth possibility is that \N resolves to a sequence of more than one
* code points. *cp_count will be set to the number of code points in the
* sequence. *node_p * will be set to a generated node returned by this
* function calling S_reg().
*
* The final possibility is that it is premature to be calling this function;
* that pass1 needs to be restarted. This can happen when this changes from
* /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
* latter occurs only when the fourth possibility would otherwise be in
* effect, and is because one of those code points requires the pattern to be
* recompiled as UTF-8. The function returns FALSE, and sets the
* RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate. When this
* happens, the caller needs to desist from continuing parsing, and return
* this information to its caller. This is not set for when there is only one
* code point, as this can be called as part of an ANYOF node, and they can
* store above-Latin1 code points without the pattern having to be in UTF-8.
*
* For non-single-quoted regexes, the tokenizer has resolved character and
* sequence names inside \N{...} into their Unicode values, normalizing the
* result into what we should see here: '\N{U+c1.c2...}', where c1... are the
* hex-represented code points in the sequence. This is done there because
* the names can vary based on what charnames pragma is in scope at the time,
* so we need a way to take a snapshot of what they resolve to at the time of
* the original parse. [perl #56444].
*
* That parsing is skipped for single-quoted regexes, so we may here get
* '\N{NAME}'. This is a fatal error. These names have to be resolved by the
* parser. But if the single-quoted regex is something like '\N{U+41}', that
* is legal and handled here. The code point is Unicode, and has to be
* translated into the native character set for non-ASCII platforms.
*/
char * endbrace; /* points to '}' following the name */
char *endchar; /* Points to '.' or '}' ending cur char in the input
stream */
char* p = RExC_parse; /* Temporary */
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_GROK_BSLASH_N;
GET_RE_DEBUG_FLAGS;
assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
assert(! (node_p && cp_count)); /* At most 1 should be set */
if (cp_count) { /* Initialize return for the most common case */
*cp_count = 1;
}
/* The [^\n] meaning of \N ignores spaces and comments under the /x
* modifier. The other meanings do not, so use a temporary until we find
* out which we are being called with */
skip_to_be_ignored_text(pRExC_state, &p,
FALSE /* Don't force to /x */ );
/* Disambiguate between \N meaning a named character versus \N meaning
* [^\n]. The latter is assumed when the {...} following the \N is a legal
* quantifier, or there is no '{' at all */
if (*p != '{' || regcurly(p)) {
RExC_parse = p;
if (cp_count) {
*cp_count = -1;
}
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
Set_Node_Length(*node_p, 1); /* MJD */
return TRUE;
}
/* Here, we have decided it should be a named character or sequence */
/* The test above made sure that the next real character is a '{', but
* under the /x modifier, it could be separated by space (or a comment and
* \n) and this is not allowed (for consistency with \x{...} and the
* tokenizer handling of \N{NAME}). */
if (*RExC_parse != '{') {
vFAIL("Missing braces on \\N{}");
}
RExC_parse++; /* Skip past the '{' */
endbrace = strchr(RExC_parse, '}');
if (! endbrace) { /* no trailing brace */
vFAIL2("Missing right brace on \\%c{}", 'N');
}
else if (!( endbrace == RExC_parse /* nothing between the {} */
|| memBEGINs(RExC_parse, /* U+ (bad hex is checked below
for a better error msg) */
(STRLEN) (RExC_end - RExC_parse),
"U+")))
{
RExC_parse = endbrace; /* position msg's '<--HERE' */
vFAIL("\\N{NAME} must be resolved by the lexer");
}
REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
semantics */
if (endbrace == RExC_parse) { /* empty: \N{} */
if (strict) {
RExC_parse++; /* Position after the "}" */
vFAIL("Zero length \\N{}");
}
if (cp_count) {
*cp_count = 0;
}
nextchar(pRExC_state);
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state,NOTHING);
return TRUE;
}
RExC_parse += 2; /* Skip past the 'U+' */
/* Because toke.c has generated a special construct for us guaranteed not
* to have NULs, we can use a str function */
endchar = RExC_parse + strcspn(RExC_parse, ".}");
/* Code points are separated by dots. If none, there is only one code
* point, and is terminated by the brace */
if (endchar >= endbrace) {
STRLEN length_of_hex;
I32 grok_hex_flags;
/* Here, exactly one code point. If that isn't what is wanted, fail */
if (! code_point_p) {
RExC_parse = p;
return FALSE;
}
/* Convert code point from hex */
length_of_hex = (STRLEN)(endchar - RExC_parse);
grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX
/* No errors in the first pass (See [perl
* #122671].) We let the code below find the
* errors when there are multiple chars. */
| ((SIZE_ONLY)
? PERL_SCAN_SILENT_ILLDIGIT
: 0);
/* This routine is the one place where both single- and double-quotish
* \N{U+xxxx} are evaluated. The value is a Unicode code point which
* must be converted to native. */
*code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse,
&length_of_hex,
&grok_hex_flags,
NULL));
/* The tokenizer should have guaranteed validity, but it's possible to
* bypass it by using single quoting, so check. Don't do the check
* here when there are multiple chars; we do it below anyway. */
if (length_of_hex == 0
|| length_of_hex != (STRLEN)(endchar - RExC_parse) )
{
RExC_parse += length_of_hex; /* Includes all the valid */
RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
? UTF8SKIP(RExC_parse)
: 1;
/* Guard against malformed utf8 */
if (RExC_parse >= endchar) {
RExC_parse = endchar;
}
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
RExC_parse = endbrace + 1;
return TRUE;
}
else { /* Is a multiple character sequence */
SV * substitute_parse;
STRLEN len;
char *orig_end = RExC_end;
char *save_start = RExC_start;
I32 flags;
/* Count the code points, if desired, in the sequence */
if (cp_count) {
*cp_count = 0;
while (RExC_parse < endbrace) {
/* Point to the beginning of the next character in the sequence. */
RExC_parse = endchar + 1;
endchar = RExC_parse + strcspn(RExC_parse, ".}");
(*cp_count)++;
}
}
/* Fail if caller doesn't want to handle a multi-code-point sequence.
* But don't backup up the pointer if the caller wants to know how many
* code points there are (they can then handle things) */
if (! node_p) {
if (! cp_count) {
RExC_parse = p;
}
return FALSE;
}
/* What is done here is to convert this to a sub-pattern of the form
* \x{char1}\x{char2}... and then call reg recursively to parse it
* (enclosing in "(?: ... )" ). That way, it retains its atomicness,
* while not having to worry about special handling that some code
* points may have. */
substitute_parse = newSVpvs("?:");
while (RExC_parse < endbrace) {
/* Convert to notation the rest of the code understands */
sv_catpv(substitute_parse, "\\x{");
sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
sv_catpv(substitute_parse, "}");
/* Point to the beginning of the next character in the sequence. */
RExC_parse = endchar + 1;
endchar = RExC_parse + strcspn(RExC_parse, ".}");
}
sv_catpv(substitute_parse, ")");
len = SvCUR(substitute_parse);
/* Don't allow empty number */
if (len < (STRLEN) 8) {
RExC_parse = endbrace;
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
RExC_parse = RExC_start = RExC_adjusted_start
= SvPV_nolen(substitute_parse);
RExC_end = RExC_parse + len;
/* The values are Unicode, and therefore not subject to recoding, but
* have to be converted to native on a non-Unicode (meaning non-ASCII)
* platform. */
#ifdef EBCDIC
RExC_recode_x_to_native = 1;
#endif
*node_p = reg(pRExC_state, 1, &flags, depth+1);
/* Restore the saved values */
RExC_start = RExC_adjusted_start = save_start;
RExC_parse = endbrace;
RExC_end = orig_end;
#ifdef EBCDIC
RExC_recode_x_to_native = 0;
#endif
SvREFCNT_dec_NN(substitute_parse);
if (! *node_p) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return FALSE;
}
FAIL2("panic: reg returned NULL to grok_bslash_N, flags=%#" UVxf,
(UV) flags);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
nextchar(pRExC_state);
return TRUE;
}
} | S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
regnode ** node_p,
UV * code_point_p,
int * cp_count,
I32 * flagp,
const bool strict,
const U32 depth
)
{
/* This routine teases apart the various meanings of \N and returns
* accordingly. The input parameters constrain which meaning(s) is/are valid
* in the current context.
*
* Exactly one of <node_p> and <code_point_p> must be non-NULL.
*
* If <code_point_p> is not NULL, the context is expecting the result to be a
* single code point. If this \N instance turns out to a single code point,
* the function returns TRUE and sets *code_point_p to that code point.
*
* If <node_p> is not NULL, the context is expecting the result to be one of
* the things representable by a regnode. If this \N instance turns out to be
* one such, the function generates the regnode, returns TRUE and sets *node_p
* to point to that regnode.
*
* If this instance of \N isn't legal in any context, this function will
* generate a fatal error and not return.
*
* On input, RExC_parse should point to the first char following the \N at the
* time of the call. On successful return, RExC_parse will have been updated
* to point to just after the sequence identified by this routine. Also
* *flagp has been updated as needed.
*
* When there is some problem with the current context and this \N instance,
* the function returns FALSE, without advancing RExC_parse, nor setting
* *node_p, nor *code_point_p, nor *flagp.
*
* If <cp_count> is not NULL, the caller wants to know the length (in code
* points) that this \N sequence matches. This is set even if the function
* returns FALSE, as detailed below.
*
* There are 5 possibilities here, as detailed in the next 5 paragraphs.
*
* Probably the most common case is for the \N to specify a single code point.
* *cp_count will be set to 1, and *code_point_p will be set to that code
* point.
*
* Another possibility is for the input to be an empty \N{}, which for
* backwards compatibility we accept. *cp_count will be set to 0. *node_p
* will be set to a generated NOTHING node.
*
* Still another possibility is for the \N to mean [^\n]. *cp_count will be
* set to 0. *node_p will be set to a generated REG_ANY node.
*
* The fourth possibility is that \N resolves to a sequence of more than one
* code points. *cp_count will be set to the number of code points in the
* sequence. *node_p * will be set to a generated node returned by this
* function calling S_reg().
*
* The final possibility is that it is premature to be calling this function;
* that pass1 needs to be restarted. This can happen when this changes from
* /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
* latter occurs only when the fourth possibility would otherwise be in
* effect, and is because one of those code points requires the pattern to be
* recompiled as UTF-8. The function returns FALSE, and sets the
* RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate. When this
* happens, the caller needs to desist from continuing parsing, and return
* this information to its caller. This is not set for when there is only one
* code point, as this can be called as part of an ANYOF node, and they can
* store above-Latin1 code points without the pattern having to be in UTF-8.
*
* For non-single-quoted regexes, the tokenizer has resolved character and
* sequence names inside \N{...} into their Unicode values, normalizing the
* result into what we should see here: '\N{U+c1.c2...}', where c1... are the
* hex-represented code points in the sequence. This is done there because
* the names can vary based on what charnames pragma is in scope at the time,
* so we need a way to take a snapshot of what they resolve to at the time of
* the original parse. [perl #56444].
*
* That parsing is skipped for single-quoted regexes, so we may here get
* '\N{NAME}'. This is a fatal error. These names have to be resolved by the
* parser. But if the single-quoted regex is something like '\N{U+41}', that
* is legal and handled here. The code point is Unicode, and has to be
* translated into the native character set for non-ASCII platforms.
*/
char * endbrace; /* points to '}' following the name */
char *endchar; /* Points to '.' or '}' ending cur char in the input
stream */
char* p = RExC_parse; /* Temporary */
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_GROK_BSLASH_N;
GET_RE_DEBUG_FLAGS;
assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
assert(! (node_p && cp_count)); /* At most 1 should be set */
if (cp_count) { /* Initialize return for the most common case */
*cp_count = 1;
}
/* The [^\n] meaning of \N ignores spaces and comments under the /x
* modifier. The other meanings do not, so use a temporary until we find
* out which we are being called with */
skip_to_be_ignored_text(pRExC_state, &p,
FALSE /* Don't force to /x */ );
/* Disambiguate between \N meaning a named character versus \N meaning
* [^\n]. The latter is assumed when the {...} following the \N is a legal
* quantifier, or there is no '{' at all */
if (*p != '{' || regcurly(p)) {
RExC_parse = p;
if (cp_count) {
*cp_count = -1;
}
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
Set_Node_Length(*node_p, 1); /* MJD */
return TRUE;
}
/* Here, we have decided it should be a named character or sequence */
/* The test above made sure that the next real character is a '{', but
* under the /x modifier, it could be separated by space (or a comment and
* \n) and this is not allowed (for consistency with \x{...} and the
* tokenizer handling of \N{NAME}). */
if (*RExC_parse != '{') {
vFAIL("Missing braces on \\N{}");
}
RExC_parse++; /* Skip past the '{' */
endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
if (! endbrace) { /* no trailing brace */
vFAIL2("Missing right brace on \\%c{}", 'N');
}
else if (!( endbrace == RExC_parse /* nothing between the {} */
|| memBEGINs(RExC_parse, /* U+ (bad hex is checked below
for a better error msg) */
(STRLEN) (RExC_end - RExC_parse),
"U+")))
{
RExC_parse = endbrace; /* position msg's '<--HERE' */
vFAIL("\\N{NAME} must be resolved by the lexer");
}
REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
semantics */
if (endbrace == RExC_parse) { /* empty: \N{} */
if (strict) {
RExC_parse++; /* Position after the "}" */
vFAIL("Zero length \\N{}");
}
if (cp_count) {
*cp_count = 0;
}
nextchar(pRExC_state);
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state,NOTHING);
return TRUE;
}
RExC_parse += 2; /* Skip past the 'U+' */
/* Because toke.c has generated a special construct for us guaranteed not
* to have NULs, we can use a str function */
endchar = RExC_parse + strcspn(RExC_parse, ".}");
/* Code points are separated by dots. If none, there is only one code
* point, and is terminated by the brace */
if (endchar >= endbrace) {
STRLEN length_of_hex;
I32 grok_hex_flags;
/* Here, exactly one code point. If that isn't what is wanted, fail */
if (! code_point_p) {
RExC_parse = p;
return FALSE;
}
/* Convert code point from hex */
length_of_hex = (STRLEN)(endchar - RExC_parse);
grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX
/* No errors in the first pass (See [perl
* #122671].) We let the code below find the
* errors when there are multiple chars. */
| ((SIZE_ONLY)
? PERL_SCAN_SILENT_ILLDIGIT
: 0);
/* This routine is the one place where both single- and double-quotish
* \N{U+xxxx} are evaluated. The value is a Unicode code point which
* must be converted to native. */
*code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse,
&length_of_hex,
&grok_hex_flags,
NULL));
/* The tokenizer should have guaranteed validity, but it's possible to
* bypass it by using single quoting, so check. Don't do the check
* here when there are multiple chars; we do it below anyway. */
if (length_of_hex == 0
|| length_of_hex != (STRLEN)(endchar - RExC_parse) )
{
RExC_parse += length_of_hex; /* Includes all the valid */
RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
? UTF8SKIP(RExC_parse)
: 1;
/* Guard against malformed utf8 */
if (RExC_parse >= endchar) {
RExC_parse = endchar;
}
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
RExC_parse = endbrace + 1;
return TRUE;
}
else { /* Is a multiple character sequence */
SV * substitute_parse;
STRLEN len;
char *orig_end = RExC_end;
char *save_start = RExC_start;
I32 flags;
/* Count the code points, if desired, in the sequence */
if (cp_count) {
*cp_count = 0;
while (RExC_parse < endbrace) {
/* Point to the beginning of the next character in the sequence. */
RExC_parse = endchar + 1;
endchar = RExC_parse + strcspn(RExC_parse, ".}");
(*cp_count)++;
}
}
/* Fail if caller doesn't want to handle a multi-code-point sequence.
* But don't backup up the pointer if the caller wants to know how many
* code points there are (they can then handle things) */
if (! node_p) {
if (! cp_count) {
RExC_parse = p;
}
return FALSE;
}
/* What is done here is to convert this to a sub-pattern of the form
* \x{char1}\x{char2}... and then call reg recursively to parse it
* (enclosing in "(?: ... )" ). That way, it retains its atomicness,
* while not having to worry about special handling that some code
* points may have. */
substitute_parse = newSVpvs("?:");
while (RExC_parse < endbrace) {
/* Convert to notation the rest of the code understands */
sv_catpv(substitute_parse, "\\x{");
sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
sv_catpv(substitute_parse, "}");
/* Point to the beginning of the next character in the sequence. */
RExC_parse = endchar + 1;
endchar = RExC_parse + strcspn(RExC_parse, ".}");
}
sv_catpv(substitute_parse, ")");
len = SvCUR(substitute_parse);
/* Don't allow empty number */
if (len < (STRLEN) 8) {
RExC_parse = endbrace;
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
RExC_parse = RExC_start = RExC_adjusted_start
= SvPV_nolen(substitute_parse);
RExC_end = RExC_parse + len;
/* The values are Unicode, and therefore not subject to recoding, but
* have to be converted to native on a non-Unicode (meaning non-ASCII)
* platform. */
#ifdef EBCDIC
RExC_recode_x_to_native = 1;
#endif
*node_p = reg(pRExC_state, 1, &flags, depth+1);
/* Restore the saved values */
RExC_start = RExC_adjusted_start = save_start;
RExC_parse = endbrace;
RExC_end = orig_end;
#ifdef EBCDIC
RExC_recode_x_to_native = 0;
#endif
SvREFCNT_dec_NN(substitute_parse);
if (! *node_p) {
if (flags & (RESTART_PASS1|NEED_UTF8)) {
*flagp = flags & (RESTART_PASS1|NEED_UTF8);
return FALSE;
}
FAIL2("panic: reg returned NULL to grok_bslash_N, flags=%#" UVxf,
(UV) flags);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
nextchar(pRExC_state);
return TRUE;
}
} | {
"deleted": [
{
"line_no": 142,
"char_start": 6253,
"char_end": 6293,
"line": " endbrace = strchr(RExC_parse, '}');\n"
}
],
"added": [
{
"line_no": 142,
"char_start": 6253,
"char_end": 6325,
"line": " endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);\n"
}
]
} | {
"deleted": [
{
"char_start": 6268,
"char_end": 6270,
"chars": "st"
}
],
"added": [
{
"char_start": 6268,
"char_end": 6272,
"chars": "(cha"
},
{
"char_start": 6273,
"char_end": 6280,
"chars": " *) mem"
},
{
"char_start": 6299,
"char_end": 6322,
"chars": ", RExC_end - RExC_parse"
}
]
} | github.com/Perl/perl5/commit/43b2f4ef399e2fd7240b4eeb0658686ad95f8e62 | regcomp.c | cwe-125 |
enc_untrusted_read | ssize_t enc_untrusted_read(int fd, void *buf, size_t count) {
return static_cast<ssize_t>(EnsureInitializedAndDispatchSyscall(
asylo::system_call::kSYS_read, fd, buf, count));
} | ssize_t enc_untrusted_read(int fd, void *buf, size_t count) {
ssize_t ret = static_cast<ssize_t>(EnsureInitializedAndDispatchSyscall(
asylo::system_call::kSYS_read, fd, buf, count));
if (ret != -1 && ret > count) {
::asylo::primitives::TrustedPrimitives::BestEffortAbort(
"enc_untrusted_read: read result exceeds requested");
}
return ret;
} | {
"deleted": [
{
"line_no": 2,
"char_start": 62,
"char_end": 129,
"line": " return static_cast<ssize_t>(EnsureInitializedAndDispatchSyscall(\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 62,
"char_end": 136,
"line": " ssize_t ret = static_cast<ssize_t>(EnsureInitializedAndDispatchSyscall(\n"
},
{
"line_no": 4,
"char_start": 191,
"char_end": 225,
"line": " if (ret != -1 && ret > count) {\n"
},
{
"line_no": 5,
"char_start": 225,
"char_end": 286,
"line": " ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n"
},
{
"line_no": 6,
"char_start": 286,
"char_end": 348,
"line": " \"enc_untrusted_read: read result exceeds requested\");\n"
},
{
"line_no": 7,
"char_start": 348,
"char_end": 352,
"line": " }\n"
},
{
"line_no": 8,
"char_start": 352,
"char_end": 366,
"line": " return ret;\n"
}
]
} | {
"deleted": [
{
"char_start": 67,
"char_end": 70,
"chars": "urn"
}
],
"added": [
{
"char_start": 64,
"char_end": 68,
"chars": "ssiz"
},
{
"char_start": 69,
"char_end": 70,
"chars": "_"
},
{
"char_start": 71,
"char_end": 72,
"chars": " "
},
{
"char_start": 73,
"char_end": 77,
"chars": "et ="
},
{
"char_start": 189,
"char_end": 364,
"chars": ";\n if (ret != -1 && ret > count) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_read: read result exceeds requested\");\n }\n return ret"
}
]
} | github.com/google/asylo/commit/b1d120a2c7d7446d2cc58d517e20a1b184b82200 | asylo/platform/host_call/trusted/host_calls.cc | cwe-125 |
WavpackVerifySingleBlock | int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer;
uint32_t checksum_passed = 0, bcount, meta_bc;
unsigned char *dp, meta_id, c1, c2;
if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))
return FALSE;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return FALSE;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return FALSE;
if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer;
#else
unsigned char *csptr = buffer;
#endif
int wcount = (int)(dp - 2 - buffer) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return FALSE;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))
return FALSE;
}
else {
csum ^= csum >> 16;
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))
return FALSE;
}
checksum_passed++;
}
bcount -= meta_bc;
dp += meta_bc;
}
return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);
} | int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer;
uint32_t checksum_passed = 0, bcount, meta_bc;
unsigned char *dp, meta_id, c1, c2;
if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))
return FALSE;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return FALSE;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return FALSE;
if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer;
#else
unsigned char *csptr = buffer;
#endif
int wcount = (int)(dp - 2 - buffer) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return FALSE;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff))
return FALSE;
}
else {
csum ^= csum >> 16;
if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff))
return FALSE;
}
checksum_passed++;
}
bcount -= meta_bc;
dp += meta_bc;
}
return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);
} | {
"deleted": [
{
"line_no": 60,
"char_start": 1724,
"char_end": 1869,
"line": " if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))\n"
},
{
"line_no": 66,
"char_start": 1973,
"char_end": 2050,
"line": " if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))\n"
}
],
"added": [
{
"line_no": 60,
"char_start": 1724,
"char_end": 1867,
"line": " if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff))\n"
},
{
"line_no": 66,
"char_start": 1971,
"char_end": 2046,
"line": " if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff))\n"
}
]
} | {
"deleted": [
{
"char_start": 1747,
"char_end": 1749,
"chars": "++"
},
{
"char_start": 1770,
"char_end": 1771,
"chars": "*"
},
{
"char_start": 1773,
"char_end": 1775,
"chars": "++"
},
{
"char_start": 1803,
"char_end": 1804,
"chars": "*"
},
{
"char_start": 1806,
"char_end": 1808,
"chars": "++"
},
{
"char_start": 1837,
"char_end": 1838,
"chars": "*"
},
{
"char_start": 1840,
"char_end": 1842,
"chars": "++"
},
{
"char_start": 1996,
"char_end": 1998,
"chars": "++"
},
{
"char_start": 2019,
"char_end": 2020,
"chars": "*"
},
{
"char_start": 2022,
"char_end": 2024,
"chars": "++"
}
],
"added": [
{
"char_start": 1770,
"char_end": 1773,
"chars": "[1]"
},
{
"char_start": 1803,
"char_end": 1806,
"chars": "[2]"
},
{
"char_start": 1837,
"char_end": 1840,
"chars": "[3]"
},
{
"char_start": 2017,
"char_end": 2020,
"chars": "[1]"
}
]
} | github.com/dbry/WavPack/commit/bba5389dc598a92bdf2b297c3ea34620b6679b5b | src/open_utils.c | cwe-125 |
ReadVIFFImage | static Image *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
(void) ReadBlob(image,512,(unsigned char *) viff_info.comment);
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=(int) ReadBlobLong(image);
viff_info.y_offset=(int) ReadBlobLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
/*
Verify that we can read this VIFF image.
*/
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (viff_info.map_rows >
(viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
(void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
value);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=ScaleCharToQuantum(
(unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=ScaleCharToQuantum(
(unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
/*
Initialize image structure.
*/
image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse;
image->storage_class=
(viff_info.number_data_bands < 3 ? PseudoClass : DirectClass);
image->columns=viff_info.rows;
image->rows=viff_info.columns;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
else
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
pixels=(unsigned char *) AcquireQuantumMemory(max_packets,
bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(MagickRealType) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(MagickRealType) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
if (image->storage_class != PseudoClass)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p));
SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels)));
SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels)));
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(q);
SetPixelRed(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].red);
index=(ssize_t) GetPixelGreen(q);
SetPixelGreen(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].green);
index=(ssize_t) GetPixelRed(q);
SetPixelBlue(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].blue);
}
SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange-
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count != 0) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | static Image *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
(void) ReadBlob(image,512,(unsigned char *) viff_info.comment);
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=(int) ReadBlobLong(image);
viff_info.y_offset=(int) ReadBlobLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
/*
Verify that we can read this VIFF image.
*/
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (viff_info.map_rows >
(viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
(void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
value);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=ScaleCharToQuantum(
(unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=ScaleCharToQuantum(
(unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
/*
Initialize image structure.
*/
image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse;
image->storage_class=
(viff_info.number_data_bands < 3 ? PseudoClass : DirectClass);
image->columns=viff_info.rows;
image->rows=viff_info.columns;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
else
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels,
max_packets),bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(MagickRealType) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(MagickRealType) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
if (image->storage_class != PseudoClass)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(q,quantum == 0 ? 0 : QuantumRange);
SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange);
SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange);
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x+bit,quantum);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p));
SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels)));
SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels)));
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(q);
SetPixelRed(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].red);
index=(ssize_t) GetPixelGreen(q);
SetPixelGreen(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].green);
index=(ssize_t) GetPixelRed(q);
SetPixelBlue(q,image->colormap[(ssize_t)
ConstrainColormapIndex(image,index)].blue);
}
SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange-
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count != 0) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | {
"deleted": [
{
"line_no": 370,
"char_start": 12423,
"char_end": 12486,
"line": " pixels=(unsigned char *) AcquireQuantumMemory(max_packets,\n"
},
{
"line_no": 371,
"char_start": 12486,
"char_end": 12526,
"line": " bytes_per_pixel*sizeof(*pixels));\n"
}
],
"added": [
{
"line_no": 370,
"char_start": 12423,
"char_end": 12498,
"line": " pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels,\n"
},
{
"line_no": 371,
"char_start": 12498,
"char_end": 12551,
"line": " max_packets),bytes_per_pixel*sizeof(*pixels));\n"
}
]
} | {
"deleted": [
{
"char_start": 12473,
"char_end": 12474,
"chars": "m"
},
{
"char_start": 12478,
"char_end": 12481,
"chars": "ack"
},
{
"char_start": 12482,
"char_end": 12483,
"chars": "t"
}
],
"added": [
{
"char_start": 12473,
"char_end": 12480,
"chars": "MagickM"
},
{
"char_start": 12482,
"char_end": 12489,
"chars": "(number"
},
{
"char_start": 12491,
"char_end": 12493,
"chars": "ix"
},
{
"char_start": 12494,
"char_end": 12495,
"chars": "l"
},
{
"char_start": 12504,
"char_end": 12517,
"chars": "max_packets),"
}
]
} | github.com/ImageMagick/ImageMagick/commit/ca0c886abd6d3ef335eb74150cd23b89ebd17135 | coders/viff.c | cwe-125 |
core_anal_bytes | static void core_anal_bytes(RCore *core, const ut8 *buf, int len, int nops, int fmt) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
bool romem = r_config_get_i (core->config, "esil.romem");
bool stats = r_config_get_i (core->config, "esil.stats");
bool be = core->print->big_endian;
bool use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
int ret, i, j, idx, size;
const char *color = "";
const char *esilstr;
const char *opexstr;
RAnalHint *hint;
RAnalEsil *esil = NULL;
RAsmOp asmop;
RAnalOp op = {0};
ut64 addr;
bool isFirst = true;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
int totalsize = 0;
// Variables required for setting up ESIL to REIL conversion
if (use_color) {
color = core->cons->pal.label;
}
switch (fmt) {
case 'j':
r_cons_printf ("[");
break;
case 'r':
// Setup for ESIL to REIL conversion
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
break;
}
for (i = idx = ret = 0; idx < len && (!nops || (nops && i < nops)); i++, idx += ret) {
addr = core->offset + idx;
// TODO: use more anal hints
hint = r_anal_hint_get (core->anal, addr);
r_asm_set_pc (core->assembler, addr);
(void)r_asm_disassemble (core->assembler, &asmop, buf + idx, len - idx);
ret = r_anal_op (core->anal, &op, core->offset + idx, buf + idx, len - idx, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&op.esil);
opexstr = R_STRBUF_SAFEGET (&op.opex);
char *mnem = strdup (r_asm_op_get_asm (&asmop));
char *sp = strchr (mnem, ' ');
if (sp) {
*sp = 0;
if (op.prefix) {
char *arg = strdup (sp + 1);
char *sp = strchr (arg, ' ');
if (sp) {
*sp = 0;
}
free (mnem);
mnem = arg;
}
}
if (ret < 1 && fmt != 'd') {
eprintf ("Oops at 0x%08" PFMT64x " (", core->offset + idx);
for (i = idx, j = 0; i < core->blocksize && j < 3; ++i, ++j) {
eprintf ("%02x ", buf[i]);
}
eprintf ("...)\n");
free (mnem);
break;
}
size = (hint && hint->size)? hint->size: op.size;
if (fmt == 'd') {
char *opname = strdup (r_asm_op_get_asm (&asmop));
if (opname) {
r_str_split (opname, ' ');
char *d = r_asm_describe (core->assembler, opname);
if (d && *d) {
r_cons_printf ("%s: %s\n", opname, d);
free (d);
} else {
eprintf ("Unknown opcode\n");
}
free (opname);
}
} else if (fmt == 'e') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET " %s\n", color, core->offset + idx, esilstr);
} else {
r_cons_printf ("0x%" PFMT64x " %s\n", core->offset + idx, esilstr);
}
}
} else if (fmt == 's') {
totalsize += op.size;
} else if (fmt == 'r') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET "\n", color, core->offset + idx);
} else {
r_cons_printf ("0x%" PFMT64x "\n", core->offset + idx);
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
}
} else if (fmt == 'j') {
if (isFirst) {
isFirst = false;
} else {
r_cons_print (",");
}
r_cons_printf ("{\"opcode\":\"%s\",", r_asm_op_get_asm (&asmop));
{
char strsub[128] = { 0 };
// pc+33
r_parse_varsub (core->parser, NULL,
core->offset + idx,
asmop.size, r_asm_op_get_asm (&asmop),
strsub, sizeof (strsub));
{
ut64 killme = UT64_MAX;
if (r_io_read_i (core->io, op.ptr, &killme, op.refptr, be)) {
core->parser->relsub_addr = killme;
}
}
// 0x33->sym.xx
char *p = strdup (strsub);
if (p) {
r_parse_filter (core->parser, addr, core->flags, p,
strsub, sizeof (strsub), be);
free (p);
}
r_cons_printf ("\"disasm\":\"%s\",", strsub);
}
r_cons_printf ("\"mnemonic\":\"%s\",", mnem);
if (hint && hint->opcode) {
r_cons_printf ("\"ophint\":\"%s\",", hint->opcode);
}
r_cons_printf ("\"sign\":%s,", r_str_bool (op.sign));
r_cons_printf ("\"prefix\":%" PFMT64u ",", op.prefix);
r_cons_printf ("\"id\":%d,", op.id);
if (opexstr && *opexstr) {
r_cons_printf ("\"opex\":%s,", opexstr);
}
r_cons_printf ("\"addr\":%" PFMT64u ",", core->offset + idx);
r_cons_printf ("\"bytes\":\"");
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_printf ("\",");
if (op.val != UT64_MAX) {
r_cons_printf ("\"val\": %" PFMT64u ",", op.val);
}
if (op.ptr != UT64_MAX) {
r_cons_printf ("\"ptr\": %" PFMT64u ",", op.ptr);
}
r_cons_printf ("\"size\": %d,", size);
r_cons_printf ("\"type\": \"%s\",",
r_anal_optype_to_string (op.type));
if (op.reg) {
r_cons_printf ("\"reg\": \"%s\",", op.reg);
}
if (op.ireg) {
r_cons_printf ("\"ireg\": \"%s\",", op.ireg);
}
if (op.scale) {
r_cons_printf ("\"scale\":%d,", op.scale);
}
if (hint && hint->esil) {
r_cons_printf ("\"esil\": \"%s\",", hint->esil);
} else if (*esilstr) {
r_cons_printf ("\"esil\": \"%s\",", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
r_cons_printf ("\"jump\":%" PFMT64u ",", op.jump);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.refptr != -1) {
r_cons_printf ("\"refptr\":%d,", op.refptr);
}
if (op.fail != UT64_MAX) {
r_cons_printf ("\"fail\":%" PFMT64u ",", op.fail);
}
r_cons_printf ("\"cycles\":%d,", op.cycles);
if (op.failcycles) {
r_cons_printf ("\"failcycles\":%d,", op.failcycles);
}
r_cons_printf ("\"delay\":%d,", op.delay);
{
const char *p = r_anal_stackop_tostring (op.stackop);
if (p && *p && strcmp (p, "null"))
r_cons_printf ("\"stack\":\"%s\",", p);
}
if (op.stackptr) {
r_cons_printf ("\"stackptr\":%d,", op.stackptr);
}
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)
? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
r_cons_printf ("\"cond\":\"%s\",", arg);
}
}
r_cons_printf ("\"family\":\"%s\"}", r_anal_op_family_to_string (op.family));
} else {
#define printline(k, fmt, arg)\
{ \
if (use_color)\
r_cons_printf ("%s%s: " Color_RESET, color, k);\
else\
r_cons_printf ("%s: ", k);\
if (fmt) r_cons_printf (fmt, arg);\
}
printline ("address", "0x%" PFMT64x "\n", core->offset + idx);
printline ("opcode", "%s\n", r_asm_op_get_asm (&asmop));
printline ("mnemonic", "%s\n", mnem);
if (hint) {
if (hint->opcode) {
printline ("ophint", "%s\n", hint->opcode);
}
#if 0
// addr should not override core->offset + idx.. its silly
if (hint->addr != UT64_MAX) {
printline ("addr", "0x%08" PFMT64x "\n", (hint->addr + idx));
}
#endif
}
printline ("prefix", "%" PFMT64u "\n", op.prefix);
printline ("id", "%d\n", op.id);
#if 0
// no opex here to avoid lot of tests broken..and having json in here is not much useful imho
if (opexstr && *opexstr) {
printline ("opex", "%s\n", opexstr);
}
#endif
printline ("bytes", NULL, 0);
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_newline ();
if (op.val != UT64_MAX)
printline ("val", "0x%08" PFMT64x "\n", op.val);
if (op.ptr != UT64_MAX)
printline ("ptr", "0x%08" PFMT64x "\n", op.ptr);
if (op.refptr != -1)
printline ("refptr", "%d\n", op.refptr);
printline ("size", "%d\n", size);
printline ("sign", "%s\n", r_str_bool (op.sign));
printline ("type", "%s\n", r_anal_optype_to_string (op.type));
printline ("cycles", "%d\n", op.cycles);
if (op.failcycles) {
printline ("failcycles", "%d\n", op.failcycles);
}
{
const char *t2 = r_anal_optype_to_string (op.type2);
if (t2 && strcmp (t2, "null")) {
printline ("type2", "%s\n", t2);
}
}
if (op.reg) {
printline ("reg", "%s\n", op.reg);
}
if (op.ireg) {
printline ("ireg", "%s\n", op.ireg);
}
if (op.scale) {
printline ("scale", "%d\n", op.scale);
}
if (hint && hint->esil) {
printline ("esil", "%s\n", hint->esil);
} else if (*esilstr) {
printline ("esil", "%s\n", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
printline ("jump", "0x%08" PFMT64x "\n", op.jump);
}
if (op.direction != 0) {
const char * dir = op.direction == 1 ? "read"
: op.direction == 2 ? "write"
: op.direction == 4 ? "exec"
: op.direction == 8 ? "ref": "none";
printline ("direction", "%s\n", dir);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.fail != UT64_MAX) {
printline ("fail", "0x%08" PFMT64x "\n", op.fail);
}
if (op.delay) {
printline ("delay", "%d\n", op.delay);
}
printline ("stack", "%s\n", r_anal_stackop_tostring (op.stackop));
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
printline ("cond", "%s\n", arg);
}
}
printline ("family", "%s\n", r_anal_op_family_to_string (op.family));
printline ("stackop", "%s\n", r_anal_stackop_tostring (op.stackop));
if (op.stackptr) {
printline ("stackptr", "%"PFMT64u"\n", op.stackptr);
}
}
//r_cons_printf ("false: 0x%08"PFMT64x"\n", core->offset+idx);
//free (hint);
free (mnem);
r_anal_hint_free (hint);
r_anal_op_fini (&op);
}
r_anal_op_fini (&op);
if (fmt == 'j') {
r_cons_printf ("]");
r_cons_newline ();
} else if (fmt == 's') {
r_cons_printf ("%d\n", totalsize);
}
r_anal_esil_free (esil);
} | static void core_anal_bytes(RCore *core, const ut8 *buf, int len, int nops, int fmt) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
bool romem = r_config_get_i (core->config, "esil.romem");
bool stats = r_config_get_i (core->config, "esil.stats");
bool be = core->print->big_endian;
bool use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
int ret, i, j, idx, size;
const char *color = "";
const char *esilstr;
const char *opexstr;
RAnalHint *hint;
RAnalEsil *esil = NULL;
RAsmOp asmop;
RAnalOp op = {0};
ut64 addr;
bool isFirst = true;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
int totalsize = 0;
// Variables required for setting up ESIL to REIL conversion
if (use_color) {
color = core->cons->pal.label;
}
switch (fmt) {
case 'j':
r_cons_printf ("[");
break;
case 'r':
// Setup for ESIL to REIL conversion
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
break;
}
for (i = idx = ret = 0; idx < len && (!nops || (nops && i < nops)); i++, idx += ret) {
addr = core->offset + idx;
// TODO: use more anal hints
hint = r_anal_hint_get (core->anal, addr);
r_asm_set_pc (core->assembler, addr);
(void)r_asm_disassemble (core->assembler, &asmop, buf + idx, len - idx);
ret = r_anal_op (core->anal, &op, core->offset + idx, buf + idx, len - idx, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&op.esil);
opexstr = R_STRBUF_SAFEGET (&op.opex);
char *mnem = strdup (r_asm_op_get_asm (&asmop));
char *sp = strchr (mnem, ' ');
if (sp) {
*sp = 0;
if (op.prefix) {
char *arg = strdup (sp + 1);
char *sp = strchr (arg, ' ');
if (sp) {
*sp = 0;
}
free (mnem);
mnem = arg;
}
}
if (ret < 1 && fmt != 'd') {
eprintf ("Oops at 0x%08" PFMT64x " (", core->offset + idx);
for (i = idx, j = 0; i < core->blocksize && j < 3; ++i, ++j) {
eprintf ("%02x ", buf[i]);
}
eprintf ("...)\n");
free (mnem);
break;
}
size = (hint && hint->size)? hint->size: op.size;
if (fmt == 'd') {
char *opname = strdup (r_asm_op_get_asm (&asmop));
if (opname) {
r_str_split (opname, ' ');
char *d = r_asm_describe (core->assembler, opname);
if (d && *d) {
r_cons_printf ("%s: %s\n", opname, d);
free (d);
} else {
eprintf ("Unknown opcode\n");
}
free (opname);
}
} else if (fmt == 'e') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET " %s\n", color, core->offset + idx, esilstr);
} else {
r_cons_printf ("0x%" PFMT64x " %s\n", core->offset + idx, esilstr);
}
}
} else if (fmt == 's') {
totalsize += op.size;
} else if (fmt == 'r') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET "\n", color, core->offset + idx);
} else {
r_cons_printf ("0x%" PFMT64x "\n", core->offset + idx);
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
}
} else if (fmt == 'j') {
if (isFirst) {
isFirst = false;
} else {
r_cons_print (",");
}
r_cons_printf ("{\"opcode\":\"%s\",", r_asm_op_get_asm (&asmop));
{
char strsub[128] = { 0 };
// pc+33
r_parse_varsub (core->parser, NULL,
core->offset + idx,
asmop.size, r_asm_op_get_asm (&asmop),
strsub, sizeof (strsub));
{
ut64 killme = UT64_MAX;
if (r_io_read_i (core->io, op.ptr, &killme, op.refptr, be)) {
core->parser->relsub_addr = killme;
}
}
// 0x33->sym.xx
char *p = strdup (strsub);
if (p) {
r_parse_filter (core->parser, addr, core->flags, p,
strsub, sizeof (strsub), be);
free (p);
}
r_cons_printf ("\"disasm\":\"%s\",", strsub);
}
r_cons_printf ("\"mnemonic\":\"%s\",", mnem);
if (hint && hint->opcode) {
r_cons_printf ("\"ophint\":\"%s\",", hint->opcode);
}
r_cons_printf ("\"sign\":%s,", r_str_bool (op.sign));
r_cons_printf ("\"prefix\":%" PFMT64u ",", op.prefix);
r_cons_printf ("\"id\":%d,", op.id);
if (opexstr && *opexstr) {
r_cons_printf ("\"opex\":%s,", opexstr);
}
r_cons_printf ("\"addr\":%" PFMT64u ",", core->offset + idx);
r_cons_printf ("\"bytes\":\"");
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_printf ("\",");
if (op.val != UT64_MAX) {
r_cons_printf ("\"val\": %" PFMT64u ",", op.val);
}
if (op.ptr != UT64_MAX) {
r_cons_printf ("\"ptr\": %" PFMT64u ",", op.ptr);
}
r_cons_printf ("\"size\": %d,", size);
r_cons_printf ("\"type\": \"%s\",",
r_anal_optype_to_string (op.type));
if (op.reg) {
r_cons_printf ("\"reg\": \"%s\",", op.reg);
}
if (op.ireg) {
r_cons_printf ("\"ireg\": \"%s\",", op.ireg);
}
if (op.scale) {
r_cons_printf ("\"scale\":%d,", op.scale);
}
if (hint && hint->esil) {
r_cons_printf ("\"esil\": \"%s\",", hint->esil);
} else if (*esilstr) {
r_cons_printf ("\"esil\": \"%s\",", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
r_cons_printf ("\"jump\":%" PFMT64u ",", op.jump);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.refptr != -1) {
r_cons_printf ("\"refptr\":%d,", op.refptr);
}
if (op.fail != UT64_MAX) {
r_cons_printf ("\"fail\":%" PFMT64u ",", op.fail);
}
r_cons_printf ("\"cycles\":%d,", op.cycles);
if (op.failcycles) {
r_cons_printf ("\"failcycles\":%d,", op.failcycles);
}
r_cons_printf ("\"delay\":%d,", op.delay);
{
const char *p = r_anal_stackop_tostring (op.stackop);
if (p && *p && strcmp (p, "null"))
r_cons_printf ("\"stack\":\"%s\",", p);
}
if (op.stackptr) {
r_cons_printf ("\"stackptr\":%d,", op.stackptr);
}
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)
? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
r_cons_printf ("\"cond\":\"%s\",", arg);
}
}
r_cons_printf ("\"family\":\"%s\"}", r_anal_op_family_to_string (op.family));
} else {
#define printline(k, fmt, arg)\
{ \
if (use_color)\
r_cons_printf ("%s%s: " Color_RESET, color, k);\
else\
r_cons_printf ("%s: ", k);\
if (fmt) r_cons_printf (fmt, arg);\
}
printline ("address", "0x%" PFMT64x "\n", core->offset + idx);
printline ("opcode", "%s\n", r_asm_op_get_asm (&asmop));
printline ("mnemonic", "%s\n", mnem);
if (hint) {
if (hint->opcode) {
printline ("ophint", "%s\n", hint->opcode);
}
#if 0
// addr should not override core->offset + idx.. its silly
if (hint->addr != UT64_MAX) {
printline ("addr", "0x%08" PFMT64x "\n", (hint->addr + idx));
}
#endif
}
printline ("prefix", "%" PFMT64u "\n", op.prefix);
printline ("id", "%d\n", op.id);
#if 0
// no opex here to avoid lot of tests broken..and having json in here is not much useful imho
if (opexstr && *opexstr) {
printline ("opex", "%s\n", opexstr);
}
#endif
printline ("bytes", NULL, 0);
int minsz = R_MIN (len, size);
minsz = R_MAX (minsz, 0);
for (j = 0; j < minsz; j++) {
ut8 ch = ((j + idx - 1) > minsz)? 0xff: buf[j + idx];
r_cons_printf ("%02x", ch);
}
r_cons_newline ();
if (op.val != UT64_MAX) {
printline ("val", "0x%08" PFMT64x "\n", op.val);
}
if (op.ptr != UT64_MAX) {
printline ("ptr", "0x%08" PFMT64x "\n", op.ptr);
}
if (op.refptr != -1) {
printline ("refptr", "%d\n", op.refptr);
}
printline ("size", "%d\n", size);
printline ("sign", "%s\n", r_str_bool (op.sign));
printline ("type", "%s\n", r_anal_optype_to_string (op.type));
printline ("cycles", "%d\n", op.cycles);
if (op.failcycles) {
printline ("failcycles", "%d\n", op.failcycles);
}
{
const char *t2 = r_anal_optype_to_string (op.type2);
if (t2 && strcmp (t2, "null")) {
printline ("type2", "%s\n", t2);
}
}
if (op.reg) {
printline ("reg", "%s\n", op.reg);
}
if (op.ireg) {
printline ("ireg", "%s\n", op.ireg);
}
if (op.scale) {
printline ("scale", "%d\n", op.scale);
}
if (hint && hint->esil) {
printline ("esil", "%s\n", hint->esil);
} else if (*esilstr) {
printline ("esil", "%s\n", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
printline ("jump", "0x%08" PFMT64x "\n", op.jump);
}
if (op.direction != 0) {
const char * dir = op.direction == 1 ? "read"
: op.direction == 2 ? "write"
: op.direction == 4 ? "exec"
: op.direction == 8 ? "ref": "none";
printline ("direction", "%s\n", dir);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.fail != UT64_MAX) {
printline ("fail", "0x%08" PFMT64x "\n", op.fail);
}
if (op.delay) {
printline ("delay", "%d\n", op.delay);
}
printline ("stack", "%s\n", r_anal_stackop_tostring (op.stackop));
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
printline ("cond", "%s\n", arg);
}
}
printline ("family", "%s\n", r_anal_op_family_to_string (op.family));
printline ("stackop", "%s\n", r_anal_stackop_tostring (op.stackop));
if (op.stackptr) {
printline ("stackptr", "%"PFMT64u"\n", op.stackptr);
}
}
//r_cons_printf ("false: 0x%08"PFMT64x"\n", core->offset+idx);
//free (hint);
free (mnem);
r_anal_hint_free (hint);
r_anal_op_fini (&op);
}
r_anal_op_fini (&op);
if (fmt == 'j') {
r_cons_printf ("]");
r_cons_newline ();
} else if (fmt == 's') {
r_cons_printf ("%d\n", totalsize);
}
r_anal_esil_free (esil);
} | {
"deleted": [
{
"line_no": 243,
"char_start": 7313,
"char_end": 7345,
"line": "\t\t\tfor (j = 0; j < size; j++) {\n"
},
{
"line_no": 244,
"char_start": 7345,
"char_end": 7387,
"line": "\t\t\t\tr_cons_printf (\"%02x\", buf[j + idx]);\n"
},
{
"line_no": 247,
"char_start": 7414,
"char_end": 7441,
"line": "\t\t\tif (op.val != UT64_MAX)\n"
},
{
"line_no": 249,
"char_start": 7494,
"char_end": 7521,
"line": "\t\t\tif (op.ptr != UT64_MAX)\n"
},
{
"line_no": 251,
"char_start": 7574,
"char_end": 7598,
"line": "\t\t\tif (op.refptr != -1)\n"
}
],
"added": [
{
"line_no": 243,
"char_start": 7313,
"char_end": 7347,
"line": "\t\t\tint minsz = R_MIN (len, size);\n"
},
{
"line_no": 244,
"char_start": 7347,
"char_end": 7376,
"line": "\t\t\tminsz = R_MAX (minsz, 0);\n"
},
{
"line_no": 245,
"char_start": 7376,
"char_end": 7409,
"line": "\t\t\tfor (j = 0; j < minsz; j++) {\n"
},
{
"line_no": 246,
"char_start": 7409,
"char_end": 7467,
"line": "\t\t\t\tut8 ch = ((j + idx - 1) > minsz)? 0xff: buf[j + idx];\n"
},
{
"line_no": 247,
"char_start": 7467,
"char_end": 7499,
"line": "\t\t\t\tr_cons_printf (\"%02x\", ch);\n"
},
{
"line_no": 250,
"char_start": 7526,
"char_end": 7555,
"line": "\t\t\tif (op.val != UT64_MAX) {\n"
},
{
"line_no": 252,
"char_start": 7608,
"char_end": 7613,
"line": "\t\t\t}\n"
},
{
"line_no": 253,
"char_start": 7613,
"char_end": 7642,
"line": "\t\t\tif (op.ptr != UT64_MAX) {\n"
},
{
"line_no": 255,
"char_start": 7695,
"char_end": 7700,
"line": "\t\t\t}\n"
},
{
"line_no": 256,
"char_start": 7700,
"char_end": 7726,
"line": "\t\t\tif (op.refptr != -1) {\n"
},
{
"line_no": 258,
"char_start": 7771,
"char_end": 7776,
"line": "\t\t\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 7333,
"char_end": 7334,
"chars": "i"
},
{
"char_start": 7335,
"char_end": 7336,
"chars": "e"
},
{
"char_start": 7372,
"char_end": 7384,
"chars": "buf[j + idx]"
}
],
"added": [
{
"char_start": 7316,
"char_end": 7379,
"chars": "int minsz = R_MIN (len, size);\n\t\t\tminsz = R_MAX (minsz, 0);\n\t\t\t"
},
{
"char_start": 7395,
"char_end": 7396,
"chars": "m"
},
{
"char_start": 7397,
"char_end": 7399,
"chars": "ns"
},
{
"char_start": 7413,
"char_end": 7471,
"chars": "ut8 ch = ((j + idx - 1) > minsz)? 0xff: buf[j + idx];\n\t\t\t\t"
},
{
"char_start": 7494,
"char_end": 7496,
"chars": "ch"
},
{
"char_start": 7552,
"char_end": 7554,
"chars": " {"
},
{
"char_start": 7611,
"char_end": 7616,
"chars": "}\n\t\t\t"
},
{
"char_start": 7639,
"char_end": 7641,
"chars": " {"
},
{
"char_start": 7698,
"char_end": 7703,
"chars": "}\n\t\t\t"
},
{
"char_start": 7723,
"char_end": 7725,
"chars": " {"
},
{
"char_start": 7770,
"char_end": 7775,
"chars": "\n\t\t\t}"
}
]
} | github.com/radare/radare2/commit/a1bc65c3db593530775823d6d7506a457ed95267 | libr/core/cmd_anal.c | cwe-125 |
update_read_bitmap_data | static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)
{
WINPR_UNUSED(update);
if (Stream_GetRemainingLength(s) < 18)
return FALSE;
Stream_Read_UINT16(s, bitmapData->destLeft);
Stream_Read_UINT16(s, bitmapData->destTop);
Stream_Read_UINT16(s, bitmapData->destRight);
Stream_Read_UINT16(s, bitmapData->destBottom);
Stream_Read_UINT16(s, bitmapData->width);
Stream_Read_UINT16(s, bitmapData->height);
Stream_Read_UINT16(s, bitmapData->bitsPerPixel);
Stream_Read_UINT16(s, bitmapData->flags);
Stream_Read_UINT16(s, bitmapData->bitmapLength);
if (bitmapData->flags & BITMAP_COMPRESSION)
{
if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))
{
Stream_Read_UINT16(s,
bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
bitmapData->bitmapLength = bitmapData->cbCompMainBodySize;
}
bitmapData->compressed = TRUE;
}
else
bitmapData->compressed = FALSE;
if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)
return FALSE;
if (bitmapData->bitmapLength > 0)
{
bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);
if (!bitmapData->bitmapDataStream)
return FALSE;
memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);
Stream_Seek(s, bitmapData->bitmapLength);
}
return TRUE;
} | static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)
{
WINPR_UNUSED(update);
if (Stream_GetRemainingLength(s) < 18)
return FALSE;
Stream_Read_UINT16(s, bitmapData->destLeft);
Stream_Read_UINT16(s, bitmapData->destTop);
Stream_Read_UINT16(s, bitmapData->destRight);
Stream_Read_UINT16(s, bitmapData->destBottom);
Stream_Read_UINT16(s, bitmapData->width);
Stream_Read_UINT16(s, bitmapData->height);
Stream_Read_UINT16(s, bitmapData->bitsPerPixel);
Stream_Read_UINT16(s, bitmapData->flags);
Stream_Read_UINT16(s, bitmapData->bitmapLength);
if (bitmapData->flags & BITMAP_COMPRESSION)
{
if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s,
bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
bitmapData->bitmapLength = bitmapData->cbCompMainBodySize;
}
bitmapData->compressed = TRUE;
}
else
bitmapData->compressed = FALSE;
if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)
return FALSE;
if (bitmapData->bitmapLength > 0)
{
bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);
if (!bitmapData->bitmapDataStream)
return FALSE;
memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);
Stream_Seek(s, bitmapData->bitmapLength);
}
return TRUE;
} | {
"deleted": [],
"added": [
{
"line_no": 21,
"char_start": 699,
"char_end": 740,
"line": "\t\t\tif (Stream_GetRemainingLength(s) < 8)\n"
},
{
"line_no": 22,
"char_start": 740,
"char_end": 758,
"line": "\t\t\t\treturn FALSE;\n"
},
{
"line_no": 23,
"char_start": 758,
"char_end": 759,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 702,
"char_end": 762,
"chars": "if (Stream_GetRemainingLength(s) < 8)\n\t\t\t\treturn FALSE;\n\n\t\t\t"
}
]
} | github.com/FreeRDP/FreeRDP/commit/f8890a645c221823ac133dbf991f8a65ae50d637 | libfreerdp/core/update.c | cwe-125 |
autodetect_recv_bandwidth_measure_results | static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,
AUTODETECT_RSP_PDU* autodetectRspPdu)
{
BOOL success = TRUE;
if (autodetectRspPdu->headerLength != 0x0E)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU");
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */
if (rdp->autodetect->bandwidthMeasureTimeDelta > 0)
rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /
rdp->autodetect->bandwidthMeasureTimeDelta;
else
rdp->autodetect->netCharBandwidth = 0;
IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,
autodetectRspPdu->sequenceNumber);
return success;
} | static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,
AUTODETECT_RSP_PDU* autodetectRspPdu)
{
BOOL success = TRUE;
if (autodetectRspPdu->headerLength != 0x0E)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU");
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */
Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */
if (rdp->autodetect->bandwidthMeasureTimeDelta > 0)
rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /
rdp->autodetect->bandwidthMeasureTimeDelta;
else
rdp->autodetect->netCharBandwidth = 0;
IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,
autodetectRspPdu->sequenceNumber);
return success;
} | {
"deleted": [],
"added": [
{
"line_no": 10,
"char_start": 327,
"char_end": 366,
"line": "\tif (Stream_GetRemainingLength(s) < 8)\n"
},
{
"line_no": 11,
"char_start": 366,
"char_end": 379,
"line": "\t\treturn -1;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 328,
"char_end": 380,
"chars": "if (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\t"
}
]
} | github.com/FreeRDP/FreeRDP/commit/f5e73cc7c9cd973b516a618da877c87b80950b65 | libfreerdp/core/autodetect.c | cwe-125 |
ssl_parse_server_psk_hint | static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
} | static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) > end - len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
} | {
"deleted": [
{
"line_no": 23,
"char_start": 646,
"char_end": 673,
"line": " if( (*p) + len > end )\n"
}
],
"added": [
{
"line_no": 23,
"char_start": 646,
"char_end": 673,
"line": " if( (*p) > end - len )\n"
}
]
} | {
"deleted": [
{
"char_start": 659,
"char_end": 660,
"chars": "+"
},
{
"char_start": 661,
"char_end": 662,
"chars": "l"
},
{
"char_start": 665,
"char_end": 666,
"chars": ">"
},
{
"char_start": 669,
"char_end": 670,
"chars": "d"
}
],
"added": [
{
"char_start": 659,
"char_end": 660,
"chars": ">"
},
{
"char_start": 663,
"char_end": 664,
"chars": "d"
},
{
"char_start": 665,
"char_end": 666,
"chars": "-"
},
{
"char_start": 667,
"char_end": 668,
"chars": "l"
}
]
} | github.com/ARMmbed/mbedtls/commit/5224a7544c95552553e2e6be0b4a789956a6464e | library/ssl_cli.c | cwe-125 |
youngcollection | static void youngcollection (lua_State *L, global_State *g) {
GCObject **psurvival; /* to point to first non-dead survival object */
lua_assert(g->gcstate == GCSpropagate);
markold(g, g->survival, g->reallyold);
markold(g, g->finobj, g->finobjrold);
atomic(L);
/* sweep nursery and get a pointer to its last live element */
psurvival = sweepgen(L, g, &g->allgc, g->survival);
/* sweep 'survival' and 'old' */
sweepgen(L, g, psurvival, g->reallyold);
g->reallyold = g->old;
g->old = *psurvival; /* 'survival' survivals are old now */
g->survival = g->allgc; /* all news are survivals */
/* repeat for 'finobj' lists */
psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);
/* sweep 'survival' and 'old' */
sweepgen(L, g, psurvival, g->finobjrold);
g->finobjrold = g->finobjold;
g->finobjold = *psurvival; /* 'survival' survivals are old now */
g->finobjsur = g->finobj; /* all news are survivals */
sweepgen(L, g, &g->tobefnz, NULL);
finishgencycle(L, g);
} | static void youngcollection (lua_State *L, global_State *g) {
GCObject **psurvival; /* to point to first non-dead survival object */
lua_assert(g->gcstate == GCSpropagate);
markold(g, g->allgc, g->reallyold);
markold(g, g->finobj, g->finobjrold);
atomic(L);
/* sweep nursery and get a pointer to its last live element */
psurvival = sweepgen(L, g, &g->allgc, g->survival);
/* sweep 'survival' and 'old' */
sweepgen(L, g, psurvival, g->reallyold);
g->reallyold = g->old;
g->old = *psurvival; /* 'survival' survivals are old now */
g->survival = g->allgc; /* all news are survivals */
/* repeat for 'finobj' lists */
psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);
/* sweep 'survival' and 'old' */
sweepgen(L, g, psurvival, g->finobjrold);
g->finobjrold = g->finobjold;
g->finobjold = *psurvival; /* 'survival' survivals are old now */
g->finobjsur = g->finobj; /* all news are survivals */
sweepgen(L, g, &g->tobefnz, NULL);
finishgencycle(L, g);
} | {
"deleted": [
{
"line_no": 4,
"char_start": 178,
"char_end": 219,
"line": " markold(g, g->survival, g->reallyold);\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 178,
"char_end": 216,
"line": " markold(g, g->allgc, g->reallyold);\n"
}
]
} | {
"deleted": [
{
"char_start": 194,
"char_end": 200,
"chars": "surviv"
}
],
"added": [
{
"char_start": 196,
"char_end": 199,
"chars": "lgc"
}
]
} | github.com/lua/lua/commit/127e7a6c8942b362aa3c6627f44d660a4fb75312 | lgc.c | cwe-125 |
ext4_fill_super | static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
if ((data && !orig_data) || !sbi)
goto out_free_base;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock)
goto out_free_base;
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (ext4_has_feature_metadata_csum(sb)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
ret = -EFSBADCRC;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (sbi->s_es->s_mount_opts[0]) {
char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
sizeof(sbi->s_es->s_mount_opts),
GFP_KERNEL);
if (!s_mount_opts)
goto failed_mount;
if (!parse_options(s_mount_opts, sb, &journal_devnum,
&journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
s_mount_opts);
}
kfree(s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d (%d log_block_size)",
blocksize, le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le32_to_cpu(es->s_log_block_size) >
(EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log block size: %u",
le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
ext4_msg(sb, KERN_ERR,
"Number of reserved GDT blocks insanely large: %d",
le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
goto failed_mount;
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
err = bdev_dax_supported(sb, blocksize);
if (err)
goto failed_mount;
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = ext4_has_feature_bigalloc(sb);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
if (le32_to_cpu(es->s_log_cluster_size) >
(EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log cluster size: %u",
le32_to_cpu(es->s_log_cluster_size));
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
ret = -EFSCORRUPTED;
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
setup_timer(&sbi->s_err_report, print_daily_error_info,
(unsigned long) sb);
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
sb->s_cop = &ext4_cryptops;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount_wq;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount_wq;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount_wq;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount_wq;
}
sbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
sbi->s_mb_cache = ext4_xattr_create_cache();
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
(blocksize != PAGE_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Unsupported blocksize for fs encryption");
goto failed_mount_wq;
}
if (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&
!ext4_has_feature_encrypt(sb)) {
ext4_set_feature_encrypt(sb);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
ext4_set_resv_clusters(sb);
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (!err)
err = percpu_init_rwsem(&sbi->s_journal_flag_rwsem);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %.*s%s%s", descr,
(int) sizeof(sbi->s_es->s_mount_opts),
sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
memcpy(sbi->key_prefix, EXT4_KEY_DESC_PREFIX,
EXT4_KEY_DESC_PREFIX_SIZE);
sbi->key_prefix_size = EXT4_KEY_DESC_PREFIX_SIZE;
#endif
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
ext4_unregister_sysfs(sb);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
out_free_base:
kfree(sbi);
kfree(orig_data);
return err ? err : ret;
} | static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
if ((data && !orig_data) || !sbi)
goto out_free_base;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock)
goto out_free_base;
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (ext4_has_feature_metadata_csum(sb)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
ret = -EFSBADCRC;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (sbi->s_es->s_mount_opts[0]) {
char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
sizeof(sbi->s_es->s_mount_opts),
GFP_KERNEL);
if (!s_mount_opts)
goto failed_mount;
if (!parse_options(s_mount_opts, sb, &journal_devnum,
&journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
s_mount_opts);
}
kfree(s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d (%d log_block_size)",
blocksize, le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le32_to_cpu(es->s_log_block_size) >
(EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log block size: %u",
le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
ext4_msg(sb, KERN_ERR,
"Number of reserved GDT blocks insanely large: %d",
le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
goto failed_mount;
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
err = bdev_dax_supported(sb, blocksize);
if (err)
goto failed_mount;
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = ext4_has_feature_bigalloc(sb);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
if (le32_to_cpu(es->s_log_cluster_size) >
(EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log cluster size: %u",
le32_to_cpu(es->s_log_cluster_size));
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
if (ext4_has_feature_meta_bg(sb)) {
if (le32_to_cpu(es->s_first_meta_bg) >= db_count) {
ext4_msg(sb, KERN_WARNING,
"first meta block group too large: %u "
"(group descriptor block count %u)",
le32_to_cpu(es->s_first_meta_bg), db_count);
goto failed_mount;
}
}
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
ret = -EFSCORRUPTED;
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
setup_timer(&sbi->s_err_report, print_daily_error_info,
(unsigned long) sb);
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
sb->s_cop = &ext4_cryptops;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount_wq;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount_wq;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount_wq;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount_wq;
}
sbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
sbi->s_mb_cache = ext4_xattr_create_cache();
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
(blocksize != PAGE_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Unsupported blocksize for fs encryption");
goto failed_mount_wq;
}
if (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&
!ext4_has_feature_encrypt(sb)) {
ext4_set_feature_encrypt(sb);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
ext4_set_resv_clusters(sb);
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (!err)
err = percpu_init_rwsem(&sbi->s_journal_flag_rwsem);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %.*s%s%s", descr,
(int) sizeof(sbi->s_es->s_mount_opts),
sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
memcpy(sbi->key_prefix, EXT4_KEY_DESC_PREFIX,
EXT4_KEY_DESC_PREFIX_SIZE);
sbi->key_prefix_size = EXT4_KEY_DESC_PREFIX_SIZE;
#endif
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
ext4_unregister_sysfs(sb);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
out_free_base:
kfree(sbi);
kfree(orig_data);
return err ? err : ret;
} | {
"deleted": [],
"added": [
{
"line_no": 522,
"char_start": 16711,
"char_end": 16748,
"line": "\tif (ext4_has_feature_meta_bg(sb)) {\n"
},
{
"line_no": 523,
"char_start": 16748,
"char_end": 16802,
"line": "\t\tif (le32_to_cpu(es->s_first_meta_bg) >= db_count) {\n"
},
{
"line_no": 524,
"char_start": 16802,
"char_end": 16832,
"line": "\t\t\text4_msg(sb, KERN_WARNING,\n"
},
{
"line_no": 525,
"char_start": 16832,
"char_end": 16877,
"line": "\t\t\t\t \"first meta block group too large: %u \"\n"
},
{
"line_no": 526,
"char_start": 16877,
"char_end": 16919,
"line": "\t\t\t\t \"(group descriptor block count %u)\",\n"
},
{
"line_no": 527,
"char_start": 16919,
"char_end": 16969,
"line": "\t\t\t\t le32_to_cpu(es->s_first_meta_bg), db_count);\n"
},
{
"line_no": 528,
"char_start": 16969,
"char_end": 16991,
"line": "\t\t\tgoto failed_mount;\n"
},
{
"line_no": 529,
"char_start": 16991,
"char_end": 16995,
"line": "\t\t}\n"
},
{
"line_no": 530,
"char_start": 16995,
"char_end": 16998,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 16712,
"char_end": 16999,
"chars": "if (ext4_has_feature_meta_bg(sb)) {\n\t\tif (le32_to_cpu(es->s_first_meta_bg) >= db_count) {\n\t\t\text4_msg(sb, KERN_WARNING,\n\t\t\t\t \"first meta block group too large: %u \"\n\t\t\t\t \"(group descriptor block count %u)\",\n\t\t\t\t le32_to_cpu(es->s_first_meta_bg), db_count);\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\t"
}
]
} | github.com/torvalds/linux/commit/3a4b77cd47bb837b8557595ec7425f281f2ca1fe | fs/ext4/super.c | cwe-125 |
mxf_parse_structural_metadata | static int mxf_parse_structural_metadata(MXFContext *mxf)
{
MXFPackage *material_package = NULL;
int i, j, k, ret;
av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
/* TODO: handle multiple material packages (OP3x) */
for (i = 0; i < mxf->packages_count; i++) {
material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
if (material_package) break;
}
if (!material_package) {
av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
return AVERROR_INVALIDDATA;
}
mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
if (material_package->name && material_package->name[0])
av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
for (i = 0; i < material_package->tracks_count; i++) {
MXFPackage *source_package = NULL;
MXFTrack *material_track = NULL;
MXFTrack *source_track = NULL;
MXFTrack *temp_track = NULL;
MXFDescriptor *descriptor = NULL;
MXFStructuralComponent *component = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
UID *essence_container_ul = NULL;
const MXFCodecUL *codec_ul = NULL;
const MXFCodecUL *container_ul = NULL;
const MXFCodecUL *pix_fmt_ul = NULL;
AVStream *st;
AVTimecode tc;
int flags;
if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
continue;
}
if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
}
}
if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
continue;
}
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
if (!component)
continue;
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
break;
}
}
/* TODO: handle multiple source clips, only finds first valid source clip */
if(material_track->sequence->structural_components_count > 1)
av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
material_track->track_id, material_track->sequence->structural_components_count);
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
if (!component)
continue;
source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
if (!source_package) {
av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
continue;
}
for (k = 0; k < source_package->tracks_count; k++) {
if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
if (temp_track->track_id == component->source_track_id) {
source_track = temp_track;
break;
}
}
if (!source_track) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
break;
}
for (k = 0; k < mxf->essence_container_data_count; k++) {
MXFEssenceContainerData *essence_data;
if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
av_log(mxf, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
continue;
}
if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
source_track->body_sid = essence_data->body_sid;
source_track->index_sid = essence_data->index_sid;
break;
}
}
if(source_track && component)
break;
}
if (!source_track || !component || !source_package) {
if((ret = mxf_add_metadata_stream(mxf, material_track)))
goto fail_and_free;
continue;
}
if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
/* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
* This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
continue;
}
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
ret = AVERROR(ENOMEM);
goto fail_and_free;
}
st->id = material_track->track_id;
st->priv_data = source_track;
source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
/* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
* frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
else
source_track->original_duration = st->duration = component->duration;
if (st->duration == -1)
st->duration = AV_NOPTS_VALUE;
st->start_time = component->start_position;
if (material_track->edit_rate.num <= 0 ||
material_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on stream #%d, "
"defaulting to 25/1\n",
material_track->edit_rate.num,
material_track->edit_rate.den, st->index);
material_track->edit_rate = (AVRational){25, 1};
}
avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
/* ensure SourceTrack EditRate == MaterialTrack EditRate since only
* the former is accessible via st->priv_data */
source_track->edit_rate = material_track->edit_rate;
PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
st->codecpar->codec_type = codec_ul->id;
if (!descriptor) {
av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
continue;
}
PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
essence_container_ul = &descriptor->essence_container_ul;
source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
if (source_track->wrapping == UnknownWrapped)
av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
/* HACK: replacing the original key with mxf_encrypted_essence_container
* is not allowed according to s429-6, try to find correct information anyway */
if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
for (k = 0; k < mxf->metadata_sets_count; k++) {
MXFMetadataSet *metadata = mxf->metadata_sets[k];
if (metadata->type == CryptoContext) {
essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
break;
}
}
}
/* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
}
av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
avcodec_get_name(st->codecpar->codec_id));
for (k = 0; k < 16; k++) {
av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
descriptor->essence_codec_ul[k]);
if (!(k+1 & 19) || k == 5)
av_log(mxf->fc, AV_LOG_VERBOSE, ".");
}
av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
if (source_package->name && source_package->name[0])
av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
if (material_track->name && material_track->name[0])
av_dict_set(&st->metadata, "track_name", material_track->name, 0);
mxf_parse_physical_source_package(mxf, source_track, st);
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
source_track->intra_only = mxf_is_intra_only(descriptor);
container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
st->codecpar->width = descriptor->width;
st->codecpar->height = descriptor->height; /* Field height, not frame height */
switch (descriptor->frame_layout) {
case FullFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
break;
case OneField:
/* Every other line is stored and needs to be duplicated. */
av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
break; /* The correct thing to do here is fall through, but by breaking we might be
able to decode some streams at half the vertical resolution, rather than not al all.
It's also for compatibility with the old behavior. */
case MixedFields:
break;
case SegmentedFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
case SeparateFields:
av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
descriptor->video_line_map[0], descriptor->video_line_map[1],
descriptor->field_dominance);
if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
/* Detect coded field order from VideoLineMap:
* (even, even) => bottom field coded first
* (even, odd) => top field coded first
* (odd, even) => top field coded first
* (odd, odd) => bottom field coded first
*/
if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_TT;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_TB;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
} else {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_BB;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_BT;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
}
}
/* Turn field height into frame height. */
st->codecpar->height *= 2;
break;
default:
av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
}
if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
st->codecpar->format = descriptor->pix_fmt;
if (st->codecpar->format == AV_PIX_FMT_NONE) {
pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
&descriptor->essence_codec_ul);
st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
if (st->codecpar->format== AV_PIX_FMT_NONE) {
st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls,
&descriptor->essence_codec_ul)->id;
if (!st->codecpar->codec_tag) {
/* support files created before RP224v10 by defaulting to UYVY422
if subsampling is 4:2:2 and component depth is 8-bit */
if (descriptor->horiz_subsampling == 2 &&
descriptor->vert_subsampling == 1 &&
descriptor->component_depth == 8) {
st->codecpar->format = AV_PIX_FMT_UYVY422;
}
}
}
}
}
st->need_parsing = AVSTREAM_PARSE_HEADERS;
if (material_track->sequence->origin) {
av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
}
if (source_track->sequence->origin) {
av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
}
if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
st->display_aspect_ratio = descriptor->aspect_ratio;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
/* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
st->codecpar->channels = descriptor->channels;
st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample;
if (descriptor->sample_rate.den > 0) {
st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
} else {
av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
"found for stream #%d, time base forced to 1/48000\n",
descriptor->sample_rate.num, descriptor->sample_rate.den,
st->index);
avpriv_set_pts_info(st, 64, 1, 48000);
}
/* if duration is set, rescale it from EditRate to SampleRate */
if (st->duration != AV_NOPTS_VALUE)
st->duration = av_rescale_q(st->duration,
av_inv_q(material_track->edit_rate),
st->time_base);
/* TODO: implement AV_CODEC_ID_RAWAUDIO */
if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
st->need_parsing = AVSTREAM_PARSE_FULL;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
enum AVMediaType type;
container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
type = avcodec_get_type(st->codecpar->codec_id);
if (type == AVMEDIA_TYPE_SUBTITLE)
st->codecpar->codec_type = type;
if (container_ul->desc)
av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
}
if (descriptor->extradata) {
if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
}
} else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width,
&descriptor->essence_codec_ul)->id;
if (coded_width)
st->codecpar->width = coded_width;
ret = ff_generate_avci_extradata(st);
if (ret < 0)
return ret;
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
/* TODO: decode timestamps */
st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
}
}
ret = 0;
fail_and_free:
return ret;
} | static int mxf_parse_structural_metadata(MXFContext *mxf)
{
MXFPackage *material_package = NULL;
int i, j, k, ret;
av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
/* TODO: handle multiple material packages (OP3x) */
for (i = 0; i < mxf->packages_count; i++) {
material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
if (material_package) break;
}
if (!material_package) {
av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
return AVERROR_INVALIDDATA;
}
mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
if (material_package->name && material_package->name[0])
av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
for (i = 0; i < material_package->tracks_count; i++) {
MXFPackage *source_package = NULL;
MXFTrack *material_track = NULL;
MXFTrack *source_track = NULL;
MXFTrack *temp_track = NULL;
MXFDescriptor *descriptor = NULL;
MXFStructuralComponent *component = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
UID *essence_container_ul = NULL;
const MXFCodecUL *codec_ul = NULL;
const MXFCodecUL *container_ul = NULL;
const MXFCodecUL *pix_fmt_ul = NULL;
AVStream *st;
AVTimecode tc;
int flags;
if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
continue;
}
if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
}
}
if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
continue;
}
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
if (!component)
continue;
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
break;
}
}
/* TODO: handle multiple source clips, only finds first valid source clip */
if(material_track->sequence->structural_components_count > 1)
av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
material_track->track_id, material_track->sequence->structural_components_count);
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
if (!component)
continue;
source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
if (!source_package) {
av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
continue;
}
for (k = 0; k < source_package->tracks_count; k++) {
if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
if (temp_track->track_id == component->source_track_id) {
source_track = temp_track;
break;
}
}
if (!source_track) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
break;
}
for (k = 0; k < mxf->essence_container_data_count; k++) {
MXFEssenceContainerData *essence_data;
if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
av_log(mxf->fc, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
continue;
}
if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
source_track->body_sid = essence_data->body_sid;
source_track->index_sid = essence_data->index_sid;
break;
}
}
if(source_track && component)
break;
}
if (!source_track || !component || !source_package) {
if((ret = mxf_add_metadata_stream(mxf, material_track)))
goto fail_and_free;
continue;
}
if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
/* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
* This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
continue;
}
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
ret = AVERROR(ENOMEM);
goto fail_and_free;
}
st->id = material_track->track_id;
st->priv_data = source_track;
source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
/* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
* frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
else
source_track->original_duration = st->duration = component->duration;
if (st->duration == -1)
st->duration = AV_NOPTS_VALUE;
st->start_time = component->start_position;
if (material_track->edit_rate.num <= 0 ||
material_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on stream #%d, "
"defaulting to 25/1\n",
material_track->edit_rate.num,
material_track->edit_rate.den, st->index);
material_track->edit_rate = (AVRational){25, 1};
}
avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
/* ensure SourceTrack EditRate == MaterialTrack EditRate since only
* the former is accessible via st->priv_data */
source_track->edit_rate = material_track->edit_rate;
PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
st->codecpar->codec_type = codec_ul->id;
if (!descriptor) {
av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
continue;
}
PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
essence_container_ul = &descriptor->essence_container_ul;
source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
if (source_track->wrapping == UnknownWrapped)
av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
/* HACK: replacing the original key with mxf_encrypted_essence_container
* is not allowed according to s429-6, try to find correct information anyway */
if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
for (k = 0; k < mxf->metadata_sets_count; k++) {
MXFMetadataSet *metadata = mxf->metadata_sets[k];
if (metadata->type == CryptoContext) {
essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
break;
}
}
}
/* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
}
av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
avcodec_get_name(st->codecpar->codec_id));
for (k = 0; k < 16; k++) {
av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
descriptor->essence_codec_ul[k]);
if (!(k+1 & 19) || k == 5)
av_log(mxf->fc, AV_LOG_VERBOSE, ".");
}
av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
if (source_package->name && source_package->name[0])
av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
if (material_track->name && material_track->name[0])
av_dict_set(&st->metadata, "track_name", material_track->name, 0);
mxf_parse_physical_source_package(mxf, source_track, st);
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
source_track->intra_only = mxf_is_intra_only(descriptor);
container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
st->codecpar->width = descriptor->width;
st->codecpar->height = descriptor->height; /* Field height, not frame height */
switch (descriptor->frame_layout) {
case FullFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
break;
case OneField:
/* Every other line is stored and needs to be duplicated. */
av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
break; /* The correct thing to do here is fall through, but by breaking we might be
able to decode some streams at half the vertical resolution, rather than not al all.
It's also for compatibility with the old behavior. */
case MixedFields:
break;
case SegmentedFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
case SeparateFields:
av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
descriptor->video_line_map[0], descriptor->video_line_map[1],
descriptor->field_dominance);
if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
/* Detect coded field order from VideoLineMap:
* (even, even) => bottom field coded first
* (even, odd) => top field coded first
* (odd, even) => top field coded first
* (odd, odd) => bottom field coded first
*/
if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_TT;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_TB;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
} else {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_BB;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_BT;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
}
}
/* Turn field height into frame height. */
st->codecpar->height *= 2;
break;
default:
av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
}
if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
st->codecpar->format = descriptor->pix_fmt;
if (st->codecpar->format == AV_PIX_FMT_NONE) {
pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
&descriptor->essence_codec_ul);
st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
if (st->codecpar->format== AV_PIX_FMT_NONE) {
st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls,
&descriptor->essence_codec_ul)->id;
if (!st->codecpar->codec_tag) {
/* support files created before RP224v10 by defaulting to UYVY422
if subsampling is 4:2:2 and component depth is 8-bit */
if (descriptor->horiz_subsampling == 2 &&
descriptor->vert_subsampling == 1 &&
descriptor->component_depth == 8) {
st->codecpar->format = AV_PIX_FMT_UYVY422;
}
}
}
}
}
st->need_parsing = AVSTREAM_PARSE_HEADERS;
if (material_track->sequence->origin) {
av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
}
if (source_track->sequence->origin) {
av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
}
if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
st->display_aspect_ratio = descriptor->aspect_ratio;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
/* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
st->codecpar->channels = descriptor->channels;
st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample;
if (descriptor->sample_rate.den > 0) {
st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
} else {
av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
"found for stream #%d, time base forced to 1/48000\n",
descriptor->sample_rate.num, descriptor->sample_rate.den,
st->index);
avpriv_set_pts_info(st, 64, 1, 48000);
}
/* if duration is set, rescale it from EditRate to SampleRate */
if (st->duration != AV_NOPTS_VALUE)
st->duration = av_rescale_q(st->duration,
av_inv_q(material_track->edit_rate),
st->time_base);
/* TODO: implement AV_CODEC_ID_RAWAUDIO */
if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
st->need_parsing = AVSTREAM_PARSE_FULL;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
enum AVMediaType type;
container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
type = avcodec_get_type(st->codecpar->codec_id);
if (type == AVMEDIA_TYPE_SUBTITLE)
st->codecpar->codec_type = type;
if (container_ul->desc)
av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
}
if (descriptor->extradata) {
if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
}
} else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width,
&descriptor->essence_codec_ul)->id;
if (coded_width)
st->codecpar->width = coded_width;
ret = ff_generate_avci_extradata(st);
if (ret < 0)
return ret;
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
/* TODO: decode timestamps */
st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
}
}
ret = 0;
fail_and_free:
return ret;
} | {
"deleted": [
{
"line_no": 104,
"char_start": 5013,
"char_end": 5117,
"line": " av_log(mxf, AV_LOG_TRACE, \"could not resolve essence container data strong ref\\n\");\n"
}
],
"added": [
{
"line_no": 104,
"char_start": 5013,
"char_end": 5121,
"line": " av_log(mxf->fc, AV_LOG_TRACE, \"could not resolve essence container data strong ref\\n\");\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 5043,
"char_end": 5047,
"chars": "->fc"
}
]
} | github.com/FFmpeg/FFmpeg/commit/bab0716c7f4793ec42e05a5aa7e80d82a0dd4e75 | libavformat/mxfdec.c | cwe-125 |
parse_hid_report_descriptor | static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i];
/* Skip over prefix */
i++;
/* Determine data size and save the data in the proper variable */
size = PREF_SIZE(prefix);
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 3:
size = 4;
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
} | static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i++];
/* Determine data size and save the data in the proper variable */
size = (1U << PREF_SIZE(prefix)) >> 1;
if (i + size > length) {
dev_err(ddev,
"Not enough data (need %d, have %d)\n",
i + size, length);
break;
}
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 4:
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
} | {
"deleted": [
{
"line_no": 35,
"char_start": 704,
"char_end": 726,
"line": "\t\tprefix = report[i];\n"
},
{
"line_no": 36,
"char_start": 726,
"char_end": 727,
"line": "\n"
},
{
"line_no": 37,
"char_start": 727,
"char_end": 752,
"line": "\t\t/* Skip over prefix */\n"
},
{
"line_no": 38,
"char_start": 752,
"char_end": 759,
"line": "\t\ti++;\n"
},
{
"line_no": 41,
"char_start": 829,
"char_end": 857,
"line": "\t\tsize = PREF_SIZE(prefix);\n"
},
{
"line_no": 49,
"char_start": 980,
"char_end": 990,
"line": "\t\tcase 3:\n"
},
{
"line_no": 50,
"char_start": 990,
"char_end": 1003,
"line": "\t\t\tsize = 4;\n"
}
],
"added": [
{
"line_no": 35,
"char_start": 704,
"char_end": 728,
"line": "\t\tprefix = report[i++];\n"
},
{
"line_no": 38,
"char_start": 798,
"char_end": 839,
"line": "\t\tsize = (1U << PREF_SIZE(prefix)) >> 1;\n"
},
{
"line_no": 39,
"char_start": 839,
"char_end": 866,
"line": "\t\tif (i + size > length) {\n"
},
{
"line_no": 40,
"char_start": 866,
"char_end": 883,
"line": "\t\t\tdev_err(ddev,\n"
},
{
"line_no": 41,
"char_start": 883,
"char_end": 927,
"line": "\t\t\t\t\"Not enough data (need %d, have %d)\\n\",\n"
},
{
"line_no": 42,
"char_start": 927,
"char_end": 950,
"line": "\t\t\t\ti + size, length);\n"
},
{
"line_no": 43,
"char_start": 950,
"char_end": 960,
"line": "\t\t\tbreak;\n"
},
{
"line_no": 44,
"char_start": 960,
"char_end": 964,
"line": "\t\t}\n"
},
{
"line_no": 45,
"char_start": 964,
"char_end": 965,
"line": "\n"
},
{
"line_no": 53,
"char_start": 1088,
"char_end": 1098,
"line": "\t\tcase 4:\n"
}
]
} | {
"deleted": [
{
"char_start": 723,
"char_end": 755,
"chars": "];\n\n\t\t/* Skip over prefix */\n\t\ti"
},
{
"char_start": 987,
"char_end": 988,
"chars": "3"
},
{
"char_start": 989,
"char_end": 1002,
"chars": "\n\t\t\tsize = 4;"
}
],
"added": [
{
"char_start": 723,
"char_end": 725,
"chars": "++"
},
{
"char_start": 807,
"char_end": 814,
"chars": "(1U << "
},
{
"char_start": 831,
"char_end": 837,
"chars": ") >> 1"
},
{
"char_start": 839,
"char_end": 965,
"chars": "\t\tif (i + size > length) {\n\t\t\tdev_err(ddev,\n\t\t\t\t\"Not enough data (need %d, have %d)\\n\",\n\t\t\t\ti + size, length);\n\t\t\tbreak;\n\t\t}\n\n"
},
{
"char_start": 1096,
"char_end": 1097,
"chars": ":"
}
]
} | github.com/torvalds/linux/commit/a50829479f58416a013a4ccca791336af3c584c7 | drivers/input/tablet/gtco.c | cwe-125 |
fpm_log_write | int fpm_log_write(char *log_format) /* {{{ */
{
char *s, *b;
char buffer[FPM_LOG_BUFFER+1];
int token, test;
size_t len, len2;
struct fpm_scoreboard_proc_s proc, *proc_p;
struct fpm_scoreboard_s *scoreboard;
char tmp[129];
char format[129];
time_t now_epoch;
#ifdef HAVE_TIMES
clock_t tms_total;
#endif
if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) {
return -1;
}
if (!log_format) {
log_format = fpm_log_format;
test = 0;
} else {
test = 1;
}
now_epoch = time(NULL);
if (!test) {
scoreboard = fpm_scoreboard_get();
if (!scoreboard) {
zlog(ZLOG_WARNING, "unable to get scoreboard while preparing the access log");
return -1;
}
proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0);
if (!proc_p) {
zlog(ZLOG_WARNING, "[pool %s] Unable to acquire shm slot while preparing the access log", scoreboard->pool);
return -1;
}
proc = *proc_p;
fpm_scoreboard_proc_release(proc_p);
}
token = 0;
memset(buffer, '\0', sizeof(buffer));
b = buffer;
len = 0;
s = log_format;
while (*s != '\0') {
/* Test is we have place for 1 more char. */
if (len >= FPM_LOG_BUFFER) {
zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER);
len = FPM_LOG_BUFFER;
break;
}
if (!token && *s == '%') {
token = 1;
memset(format, '\0', sizeof(format)); /* reset format */
s++;
continue;
}
if (token) {
token = 0;
len2 = 0;
switch (*s) {
case '%': /* '%' */
*b = '%';
len2 = 1;
break;
#ifdef HAVE_TIMES
case 'C': /* %CPU */
if (format[0] == '\0' || !strcasecmp(format, "total")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime;
}
} else if (!strcasecmp(format, "user")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime;
}
} else if (!strcasecmp(format, "system")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime;
}
} else {
zlog(ZLOG_WARNING, "only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.2f", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.);
}
break;
#endif
case 'd': /* duration µs */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "seconds")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.);
}
/* miliseconds */
} else if (!strcasecmp(format, "miliseconds") || !strcasecmp(format, "mili")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.);
}
/* microseconds */
} else if (!strcasecmp(format, "microseconds") || !strcasecmp(format, "micro")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec);
}
} else {
zlog(ZLOG_WARNING, "only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'e': /* fastcgi env */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the environment variable must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format));
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", env ? env : "-");
}
format[0] = '\0';
break;
case 'f': /* script */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.script_filename ? proc.script_filename : "-");
}
break;
case 'l': /* content length */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.content_length);
}
break;
case 'm': /* method */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.request_method ? proc.request_method : "-");
}
break;
case 'M': /* memory */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "bytes")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.memory);
}
/* kilobytes */
} else if (!strcasecmp(format, "kilobytes") || !strcasecmp(format, "kilo")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024);
}
/* megabytes */
} else if (!strcasecmp(format, "megabytes") || !strcasecmp(format, "mega")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024 / 1024);
}
} else {
zlog(ZLOG_WARNING, "only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'n': /* pool name */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", scoreboard->pool[0] ? scoreboard->pool : "-");
}
break;
case 'o': /* header output */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the header must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
sapi_header_struct *h;
zend_llist_position pos;
sapi_headers_struct *sapi_headers = &SG(sapi_headers);
size_t format_len = strlen(format);
h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
while (h) {
char *header;
if (!h->header_len) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (!strstr(h->header, format)) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
/* test if enought char after the header name + ': ' */
if (h->header_len <= format_len + 2) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
header = h->header + format_len + 2;
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", header && *header ? header : "-");
/* found, done */
break;
}
if (!len2) {
len2 = 1;
*b = '-';
}
}
format[0] = '\0';
break;
case 'p': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getpid());
}
break;
case 'P': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getppid());
}
break;
case 'q': /* query_string */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.query_string);
}
break;
case 'Q': /* '?' */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.query_string ? "?" : "");
}
break;
case 'r': /* request URI */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.request_uri);
}
break;
case 'R': /* remote IP address */
if (!test) {
const char *tmp = fcgi_get_last_client_ip();
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp ? tmp : "-");
}
break;
case 's': /* status */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%d", SG(sapi_headers).http_response_code);
}
break;
case 'T':
case 't': /* time */
if (!test) {
time_t *t;
if (*s == 't') {
t = &proc.accepted_epoch;
} else {
t = &now_epoch;
}
if (format[0] == '\0') {
strftime(tmp, sizeof(tmp) - 1, "%d/%b/%Y:%H:%M:%S %z", localtime(t));
} else {
strftime(tmp, sizeof(tmp) - 1, format, localtime(t));
}
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp);
}
format[0] = '\0';
break;
case 'u': /* remote user */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.auth_user);
}
break;
case '{': /* complex var */
token = 1;
{
char *start;
size_t l;
start = ++s;
while (*s != '\0') {
if (*s == '}') {
l = s - start;
if (l >= sizeof(format) - 1) {
l = sizeof(format) - 1;
}
memcpy(format, start, l);
format[l] = '\0';
break;
}
s++;
}
if (s[1] == '\0') {
zlog(ZLOG_WARNING, "missing closing embrace in the access.format");
return -1;
}
}
break;
default:
zlog(ZLOG_WARNING, "Invalid token in the access.format (%%%c)", *s);
return -1;
}
if (*s != '}' && format[0] != '\0') {
zlog(ZLOG_WARNING, "embrace is not allowed for modifier %%%c", *s);
return -1;
}
s++;
if (!test) {
b += len2;
len += len2;
}
continue;
}
if (!test) {
// push the normal char to the output buffer
*b = *s;
b++;
len++;
}
s++;
}
if (!test && strlen(buffer) > 0) {
buffer[len] = '\n';
write(fpm_log_fd, buffer, len + 1);
}
return 0;
} | int fpm_log_write(char *log_format) /* {{{ */
{
char *s, *b;
char buffer[FPM_LOG_BUFFER+1];
int token, test;
size_t len, len2;
struct fpm_scoreboard_proc_s proc, *proc_p;
struct fpm_scoreboard_s *scoreboard;
char tmp[129];
char format[129];
time_t now_epoch;
#ifdef HAVE_TIMES
clock_t tms_total;
#endif
if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) {
return -1;
}
if (!log_format) {
log_format = fpm_log_format;
test = 0;
} else {
test = 1;
}
now_epoch = time(NULL);
if (!test) {
scoreboard = fpm_scoreboard_get();
if (!scoreboard) {
zlog(ZLOG_WARNING, "unable to get scoreboard while preparing the access log");
return -1;
}
proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0);
if (!proc_p) {
zlog(ZLOG_WARNING, "[pool %s] Unable to acquire shm slot while preparing the access log", scoreboard->pool);
return -1;
}
proc = *proc_p;
fpm_scoreboard_proc_release(proc_p);
}
token = 0;
memset(buffer, '\0', sizeof(buffer));
b = buffer;
len = 0;
s = log_format;
while (*s != '\0') {
/* Test is we have place for 1 more char. */
if (len >= FPM_LOG_BUFFER) {
zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER);
len = FPM_LOG_BUFFER;
break;
}
if (!token && *s == '%') {
token = 1;
memset(format, '\0', sizeof(format)); /* reset format */
s++;
continue;
}
if (token) {
token = 0;
len2 = 0;
switch (*s) {
case '%': /* '%' */
*b = '%';
len2 = 1;
break;
#ifdef HAVE_TIMES
case 'C': /* %CPU */
if (format[0] == '\0' || !strcasecmp(format, "total")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime;
}
} else if (!strcasecmp(format, "user")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime;
}
} else if (!strcasecmp(format, "system")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime;
}
} else {
zlog(ZLOG_WARNING, "only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.2f", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.);
}
break;
#endif
case 'd': /* duration µs */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "seconds")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.);
}
/* miliseconds */
} else if (!strcasecmp(format, "miliseconds") || !strcasecmp(format, "mili")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.);
}
/* microseconds */
} else if (!strcasecmp(format, "microseconds") || !strcasecmp(format, "micro")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec);
}
} else {
zlog(ZLOG_WARNING, "only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'e': /* fastcgi env */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the environment variable must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format));
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", env ? env : "-");
}
format[0] = '\0';
break;
case 'f': /* script */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.script_filename ? proc.script_filename : "-");
}
break;
case 'l': /* content length */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.content_length);
}
break;
case 'm': /* method */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.request_method ? proc.request_method : "-");
}
break;
case 'M': /* memory */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "bytes")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.memory);
}
/* kilobytes */
} else if (!strcasecmp(format, "kilobytes") || !strcasecmp(format, "kilo")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024);
}
/* megabytes */
} else if (!strcasecmp(format, "megabytes") || !strcasecmp(format, "mega")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024 / 1024);
}
} else {
zlog(ZLOG_WARNING, "only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'n': /* pool name */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", scoreboard->pool[0] ? scoreboard->pool : "-");
}
break;
case 'o': /* header output */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the header must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
sapi_header_struct *h;
zend_llist_position pos;
sapi_headers_struct *sapi_headers = &SG(sapi_headers);
size_t format_len = strlen(format);
h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
while (h) {
char *header;
if (!h->header_len) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (!strstr(h->header, format)) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
/* test if enought char after the header name + ': ' */
if (h->header_len <= format_len + 2) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
header = h->header + format_len + 2;
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", header && *header ? header : "-");
/* found, done */
break;
}
if (!len2) {
len2 = 1;
*b = '-';
}
}
format[0] = '\0';
break;
case 'p': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getpid());
}
break;
case 'P': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getppid());
}
break;
case 'q': /* query_string */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.query_string);
}
break;
case 'Q': /* '?' */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.query_string ? "?" : "");
}
break;
case 'r': /* request URI */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.request_uri);
}
break;
case 'R': /* remote IP address */
if (!test) {
const char *tmp = fcgi_get_last_client_ip();
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp ? tmp : "-");
}
break;
case 's': /* status */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%d", SG(sapi_headers).http_response_code);
}
break;
case 'T':
case 't': /* time */
if (!test) {
time_t *t;
if (*s == 't') {
t = &proc.accepted_epoch;
} else {
t = &now_epoch;
}
if (format[0] == '\0') {
strftime(tmp, sizeof(tmp) - 1, "%d/%b/%Y:%H:%M:%S %z", localtime(t));
} else {
strftime(tmp, sizeof(tmp) - 1, format, localtime(t));
}
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp);
}
format[0] = '\0';
break;
case 'u': /* remote user */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.auth_user);
}
break;
case '{': /* complex var */
token = 1;
{
char *start;
size_t l;
start = ++s;
while (*s != '\0') {
if (*s == '}') {
l = s - start;
if (l >= sizeof(format) - 1) {
l = sizeof(format) - 1;
}
memcpy(format, start, l);
format[l] = '\0';
break;
}
s++;
}
if (s[1] == '\0') {
zlog(ZLOG_WARNING, "missing closing embrace in the access.format");
return -1;
}
}
break;
default:
zlog(ZLOG_WARNING, "Invalid token in the access.format (%%%c)", *s);
return -1;
}
if (*s != '}' && format[0] != '\0') {
zlog(ZLOG_WARNING, "embrace is not allowed for modifier %%%c", *s);
return -1;
}
s++;
if (!test) {
b += len2;
len += len2;
}
if (len >= FPM_LOG_BUFFER) {
zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER);
len = FPM_LOG_BUFFER;
break;
}
continue;
}
if (!test) {
// push the normal char to the output buffer
*b = *s;
b++;
len++;
}
s++;
}
if (!test && strlen(buffer) > 0) {
buffer[len] = '\n';
write(fpm_log_fd, buffer, len + 1);
}
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 352,
"char_start": 9435,
"char_end": 9467,
"line": "\t\t\tif (len >= FPM_LOG_BUFFER) {\n"
},
{
"line_no": 353,
"char_start": 9467,
"char_end": 9581,
"line": "\t\t\t\tzlog(ZLOG_NOTICE, \"the log buffer is full (%d). The access log request has been truncated.\", FPM_LOG_BUFFER);\n"
},
{
"line_no": 354,
"char_start": 9581,
"char_end": 9607,
"line": "\t\t\t\tlen = FPM_LOG_BUFFER;\n"
},
{
"line_no": 355,
"char_start": 9607,
"char_end": 9618,
"line": "\t\t\t\tbreak;\n"
},
{
"line_no": 356,
"char_start": 9618,
"char_end": 9623,
"line": "\t\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 9438,
"char_end": 9626,
"chars": "if (len >= FPM_LOG_BUFFER) {\n\t\t\t\tzlog(ZLOG_NOTICE, \"the log buffer is full (%d). The access log request has been truncated.\", FPM_LOG_BUFFER);\n\t\t\t\tlen = FPM_LOG_BUFFER;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t"
}
]
} | github.com/php/php-src/commit/2721a0148649e07ed74468f097a28899741eb58f | sapi/fpm/fpm/fpm_log.c | cwe-125 |
load_tile | static MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,
ExceptionInfo *exception)
{
ssize_t
y;
register ssize_t
x;
register Quantum
*q;
ssize_t
count;
unsigned char
*graydata;
XCFPixelInfo
*xcfdata,
*xcfodata;
xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (XCFPixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);
SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha),q);
graydata++;
q+=GetPixelChannels(tile_image);
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);
SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);
xcfdata++;
q+=GetPixelChannels(tile_image);
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
} | static MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,
ExceptionInfo *exception)
{
ssize_t
y;
register ssize_t
x;
register Quantum
*q;
ssize_t
count;
unsigned char
*graydata;
XCFPixelInfo
*xcfdata,
*xcfodata;
xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length,
tile_image->columns*tile_image->rows),sizeof(*xcfdata));
if (xcfdata == (XCFPixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);
SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha),q);
graydata++;
q+=GetPixelChannels(tile_image);
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);
SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);
xcfdata++;
q+=GetPixelChannels(tile_image);
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
} | {
"deleted": [
{
"line_no": 24,
"char_start": 339,
"char_end": 418,
"line": " xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));\n"
}
],
"added": [
{
"line_no": 24,
"char_start": 339,
"char_end": 410,
"line": " xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length,\n"
},
{
"line_no": 25,
"char_start": 410,
"char_end": 471,
"line": " tile_image->columns*tile_image->rows),sizeof(*xcfdata));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 387,
"char_end": 397,
"chars": "MagickMax("
},
{
"char_start": 408,
"char_end": 451,
"chars": ",\n tile_image->columns*tile_image->rows)"
}
]
} | github.com/ImageMagick/ImageMagick/commit/a2e1064f288a353bc5fef7f79ccb7683759e775c | coders/xcf.c | cwe-125 |
hid_input_field | static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
} | static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
value[n] - min < field->maxusage &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->value[n] - min < field->maxusage
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& value[n] - min < field->maxusage
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
} | {
"deleted": [],
"added": [
{
"line_no": 26,
"char_start": 740,
"char_end": 782,
"line": "\t\t value[n] - min < field->maxusage &&\n"
},
{
"line_no": 39,
"char_start": 1088,
"char_end": 1134,
"line": "\t\t\t&& field->value[n] - min < field->maxusage\n"
},
{
"line_no": 45,
"char_start": 1354,
"char_end": 1393,
"line": "\t\t\t&& value[n] - min < field->maxusage\n"
}
]
} | {
"deleted": [
{
"char_start": 803,
"char_end": 803,
"chars": ""
},
{
"char_start": 1225,
"char_end": 1225,
"chars": ""
}
],
"added": [
{
"char_start": 746,
"char_end": 788,
"chars": "value[n] - min < field->maxusage &&\n\t\t "
},
{
"char_start": 1088,
"char_end": 1134,
"chars": "\t\t\t&& field->value[n] - min < field->maxusage\n"
},
{
"char_start": 1353,
"char_end": 1392,
"chars": "\n\t\t\t&& value[n] - min < field->maxusage"
}
]
} | github.com/torvalds/linux/commit/50220dead1650609206efe91f0cc116132d59b3f | drivers/hid/hid-core.c | cwe-125 |
gmc_mmx | static void gmc_mmx(uint8_t *dst, uint8_t *src,
int stride, int h, int ox, int oy,
int dxx, int dxy, int dyx, int dyy,
int shift, int r, int width, int height)
{
const int w = 8;
const int ix = ox >> (16 + shift);
const int iy = oy >> (16 + shift);
const int oxs = ox >> 4;
const int oys = oy >> 4;
const int dxxs = dxx >> 4;
const int dxys = dxy >> 4;
const int dyxs = dyx >> 4;
const int dyys = dyy >> 4;
const uint16_t r4[4] = { r, r, r, r };
const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
const uint64_t shift2 = 2 * shift;
#define MAX_STRIDE 4096U
#define MAX_H 8U
uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
int x, y;
const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
const int dxh = dxy * (h - 1);
const int dyw = dyx * (w - 1);
int need_emu = (unsigned) ix >= width - w ||
(unsigned) iy >= height - h;
if ( // non-constant fullpel offset (3% of blocks)
((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
(oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||
// uses more than 16 bits of subpel mv (only at huge resolution)
(dxx | dxy | dyx | dyy) & 15 ||
(need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
// FIXME could still use mmx for some of the rows
ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
shift, r, width, height);
return;
}
src += ix + iy * stride;
if (need_emu) {
ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);
src = edge_buf;
}
__asm__ volatile (
"movd %0, %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
:: "r" (1 << shift));
for (x = 0; x < w; x += 4) {
uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),
oxs - dxys + dxxs * (x + 1),
oxs - dxys + dxxs * (x + 2),
oxs - dxys + dxxs * (x + 3) };
uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),
oys - dyys + dyxs * (x + 1),
oys - dyys + dyxs * (x + 2),
oys - dyys + dyxs * (x + 3) };
for (y = 0; y < h; y++) {
__asm__ volatile (
"movq %0, %%mm4 \n\t"
"movq %1, %%mm5 \n\t"
"paddw %2, %%mm4 \n\t"
"paddw %3, %%mm5 \n\t"
"movq %%mm4, %0 \n\t"
"movq %%mm5, %1 \n\t"
"psrlw $12, %%mm4 \n\t"
"psrlw $12, %%mm5 \n\t"
: "+m" (*dx4), "+m" (*dy4)
: "m" (*dxy4), "m" (*dyy4));
__asm__ volatile (
"movq %%mm6, %%mm2 \n\t"
"movq %%mm6, %%mm1 \n\t"
"psubw %%mm4, %%mm2 \n\t"
"psubw %%mm5, %%mm1 \n\t"
"movq %%mm2, %%mm0 \n\t"
"movq %%mm4, %%mm3 \n\t"
"pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy)
"pmullw %%mm5, %%mm3 \n\t" // dx * dy
"pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy
"pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy)
"movd %4, %%mm5 \n\t"
"movd %3, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy
"pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy
"movd %2, %%mm5 \n\t"
"movd %1, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy)
"pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy)
"paddw %5, %%mm1 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"psrlw %6, %%mm0 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"movd %%mm0, %0 \n\t"
: "=m" (dst[x + y * stride])
: "m" (src[0]), "m" (src[1]),
"m" (src[stride]), "m" (src[stride + 1]),
"m" (*r4), "m" (shift2));
src += stride;
}
src += 4 - h * stride;
}
} | static void gmc_mmx(uint8_t *dst, uint8_t *src,
int stride, int h, int ox, int oy,
int dxx, int dxy, int dyx, int dyy,
int shift, int r, int width, int height)
{
const int w = 8;
const int ix = ox >> (16 + shift);
const int iy = oy >> (16 + shift);
const int oxs = ox >> 4;
const int oys = oy >> 4;
const int dxxs = dxx >> 4;
const int dxys = dxy >> 4;
const int dyxs = dyx >> 4;
const int dyys = dyy >> 4;
const uint16_t r4[4] = { r, r, r, r };
const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
const uint64_t shift2 = 2 * shift;
#define MAX_STRIDE 4096U
#define MAX_H 8U
uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
int x, y;
const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
const int dxh = dxy * (h - 1);
const int dyw = dyx * (w - 1);
int need_emu = (unsigned) ix >= width - w || width < w ||
(unsigned) iy >= height - h || height< h
;
if ( // non-constant fullpel offset (3% of blocks)
((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
(oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||
// uses more than 16 bits of subpel mv (only at huge resolution)
(dxx | dxy | dyx | dyy) & 15 ||
(need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
// FIXME could still use mmx for some of the rows
ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
shift, r, width, height);
return;
}
src += ix + iy * stride;
if (need_emu) {
ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);
src = edge_buf;
}
__asm__ volatile (
"movd %0, %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
:: "r" (1 << shift));
for (x = 0; x < w; x += 4) {
uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),
oxs - dxys + dxxs * (x + 1),
oxs - dxys + dxxs * (x + 2),
oxs - dxys + dxxs * (x + 3) };
uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),
oys - dyys + dyxs * (x + 1),
oys - dyys + dyxs * (x + 2),
oys - dyys + dyxs * (x + 3) };
for (y = 0; y < h; y++) {
__asm__ volatile (
"movq %0, %%mm4 \n\t"
"movq %1, %%mm5 \n\t"
"paddw %2, %%mm4 \n\t"
"paddw %3, %%mm5 \n\t"
"movq %%mm4, %0 \n\t"
"movq %%mm5, %1 \n\t"
"psrlw $12, %%mm4 \n\t"
"psrlw $12, %%mm5 \n\t"
: "+m" (*dx4), "+m" (*dy4)
: "m" (*dxy4), "m" (*dyy4));
__asm__ volatile (
"movq %%mm6, %%mm2 \n\t"
"movq %%mm6, %%mm1 \n\t"
"psubw %%mm4, %%mm2 \n\t"
"psubw %%mm5, %%mm1 \n\t"
"movq %%mm2, %%mm0 \n\t"
"movq %%mm4, %%mm3 \n\t"
"pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy)
"pmullw %%mm5, %%mm3 \n\t" // dx * dy
"pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy
"pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy)
"movd %4, %%mm5 \n\t"
"movd %3, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy
"pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy
"movd %2, %%mm5 \n\t"
"movd %1, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy)
"pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy)
"paddw %5, %%mm1 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"psrlw %6, %%mm0 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"movd %%mm0, %0 \n\t"
: "=m" (dst[x + y * stride])
: "m" (src[0]), "m" (src[1]),
"m" (src[stride]), "m" (src[stride + 1]),
"m" (*r4), "m" (shift2));
src += stride;
}
src += 4 - h * stride;
}
} | {
"deleted": [
{
"line_no": 28,
"char_start": 1008,
"char_end": 1060,
"line": " int need_emu = (unsigned) ix >= width - w ||\n"
},
{
"line_no": 29,
"char_start": 1060,
"char_end": 1110,
"line": " (unsigned) iy >= height - h;\n"
}
],
"added": [
{
"line_no": 28,
"char_start": 1008,
"char_end": 1073,
"line": " int need_emu = (unsigned) ix >= width - w || width < w ||\n"
},
{
"line_no": 29,
"char_start": 1073,
"char_end": 1135,
"line": " (unsigned) iy >= height - h || height< h\n"
},
{
"line_no": 30,
"char_start": 1135,
"char_end": 1158,
"line": " ;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1059,
"char_end": 1072,
"chars": " width < w ||"
},
{
"char_start": 1121,
"char_end": 1156,
"chars": " || height< h\n "
}
]
} | github.com/FFmpeg/FFmpeg/commit/58cf31cee7a456057f337b3102a03206d833d5e8 | libavcodec/x86/mpegvideodsp.c | cwe-125 |
decode_pointer_field | static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
#ifndef PB_ENABLE_MALLOC
PB_UNUSED(wire_type);
PB_UNUSED(field);
PB_RETURN_ERROR(stream, "no malloc support");
#else
switch (PB_HTYPE(field->type))
{
case PB_HTYPE_REQUIRED:
case PB_HTYPE_OPTIONAL:
case PB_HTYPE_ONEOF:
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)
{
/* Duplicate field, have to release the old allocation first. */
/* FIXME: Does this work correctly for oneofs? */
pb_release_single_field(field);
}
if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)field->pSize = field->tag;
}
if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
PB_LTYPE(field->type) == PB_LTYPE_BYTES)
{
/* pb_dec_string and pb_dec_bytes handle allocation themselves */
field->pData = field->pField;
return decode_basic_field(stream, field);
}
else
{
if (!allocate_field(stream, field->pField, field->data_size, 1))
return false;
field->pData = *(void**)field->pField;
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array, multiple items come in at once. */
bool status = true;
pb_size_t *size = (pb_size_t*)field->pSize;
size_t allocated_size = *size;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left)
{
if ((size_t)*size + 1 > allocated_size)
{
/* Allocate more storage. This tries to guess the
* number of remaining entries. Round the division
* upwards. */
allocated_size += (substream.bytes_left - 1) / field->data_size + 1;
if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))
{
status = false;
break;
}
}
/* Decode the array entry */
field->pData = *(char**)field->pField + field->data_size * (*size);
initialize_pointer_field(field->pData, field);
if (!decode_basic_field(&substream, field))
{
status = false;
break;
}
if (*size == PB_SIZE_MAX)
{
#ifndef PB_NO_ERRMSG
stream->errmsg = "too many array entries";
#endif
status = false;
break;
}
(*size)++;
}
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Normal repeated field, i.e. only one item at a time. */
pb_size_t *size = (pb_size_t*)field->pSize;
if (*size == PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "too many array entries");
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
(*size)++;
if (!allocate_field(stream, field->pField, field->data_size, *size))
return false;
field->pData = *(char**)field->pField + field->data_size * (*size - 1);
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
#endif
} | static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
#ifndef PB_ENABLE_MALLOC
PB_UNUSED(wire_type);
PB_UNUSED(field);
PB_RETURN_ERROR(stream, "no malloc support");
#else
switch (PB_HTYPE(field->type))
{
case PB_HTYPE_REQUIRED:
case PB_HTYPE_OPTIONAL:
case PB_HTYPE_ONEOF:
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)
{
/* Duplicate field, have to release the old allocation first. */
/* FIXME: Does this work correctly for oneofs? */
pb_release_single_field(field);
}
if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)field->pSize = field->tag;
}
if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
PB_LTYPE(field->type) == PB_LTYPE_BYTES)
{
/* pb_dec_string and pb_dec_bytes handle allocation themselves */
field->pData = field->pField;
return decode_basic_field(stream, field);
}
else
{
if (!allocate_field(stream, field->pField, field->data_size, 1))
return false;
field->pData = *(void**)field->pField;
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array, multiple items come in at once. */
bool status = true;
pb_size_t *size = (pb_size_t*)field->pSize;
size_t allocated_size = *size;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left)
{
if ((size_t)*size + 1 > allocated_size)
{
/* Allocate more storage. This tries to guess the
* number of remaining entries. Round the division
* upwards. */
allocated_size += (substream.bytes_left - 1) / field->data_size + 1;
if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))
{
status = false;
break;
}
}
/* Decode the array entry */
field->pData = *(char**)field->pField + field->data_size * (*size);
initialize_pointer_field(field->pData, field);
if (!decode_basic_field(&substream, field))
{
status = false;
break;
}
if (*size == PB_SIZE_MAX)
{
#ifndef PB_NO_ERRMSG
stream->errmsg = "too many array entries";
#endif
status = false;
break;
}
(*size)++;
}
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Normal repeated field, i.e. only one item at a time. */
pb_size_t *size = (pb_size_t*)field->pSize;
if (*size == PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "too many array entries");
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if (!allocate_field(stream, field->pField, field->data_size, (size_t)(*size + 1)))
return false;
field->pData = *(char**)field->pField + field->data_size * (*size);
(*size)++;
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
#endif
} | {
"deleted": [
{
"line_no": 110,
"char_start": 4206,
"char_end": 4233,
"line": " (*size)++;\n"
},
{
"line_no": 111,
"char_start": 4233,
"char_end": 4318,
"line": " if (!allocate_field(stream, field->pField, field->data_size, *size))\n"
},
{
"line_no": 114,
"char_start": 4365,
"char_end": 4453,
"line": " field->pData = *(char**)field->pField + field->data_size * (*size - 1);\n"
}
],
"added": [
{
"line_no": 110,
"char_start": 4206,
"char_end": 4305,
"line": " if (!allocate_field(stream, field->pField, field->data_size, (size_t)(*size + 1)))\n"
},
{
"line_no": 113,
"char_start": 4352,
"char_end": 4436,
"line": " field->pData = *(char**)field->pField + field->data_size * (*size);\n"
},
{
"line_no": 114,
"char_start": 4436,
"char_end": 4463,
"line": " (*size)++;\n"
}
]
} | {
"deleted": [
{
"char_start": 4222,
"char_end": 4249,
"chars": "(*size)++;\n "
},
{
"char_start": 4447,
"char_end": 4448,
"chars": "-"
},
{
"char_start": 4449,
"char_end": 4450,
"chars": "1"
}
],
"added": [
{
"char_start": 4283,
"char_end": 4292,
"chars": "(size_t)("
},
{
"char_start": 4297,
"char_end": 4302,
"chars": " + 1)"
},
{
"char_start": 4433,
"char_end": 4440,
"chars": ");\n "
},
{
"char_start": 4441,
"char_end": 4443,
"chars": " "
},
{
"char_start": 4444,
"char_end": 4458,
"chars": " (*size"
},
{
"char_start": 4459,
"char_end": 4461,
"chars": "++"
}
]
} | github.com/nanopb/nanopb/commit/45582f1f97f49e2abfdba1463d1e1027682d9856 | pb_decode.c | cwe-125 |
ImagingFliDecode | ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
UINT8* ptr;
int framesize;
int c, chunks, advance;
int l, lines;
int i, j, x = 0, y, ymax;
/* If not even the chunk size is present, we'd better leave */
if (bytes < 4)
return 0;
/* We don't decode anything unless we have a full chunk in the
input buffer (on the other hand, the Python part of the driver
makes sure this is always the case) */
ptr = buf;
framesize = I32(ptr);
if (framesize < I32(ptr))
return 0;
/* Make sure this is a frame chunk. The Python driver takes
case of other chunk types. */
if (I16(ptr+4) != 0xF1FA) {
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
chunks = I16(ptr+6);
ptr += 16;
bytes -= 16;
/* Process subchunks */
for (c = 0; c < chunks; c++) {
UINT8* data;
if (bytes < 10) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
data = ptr + 6;
switch (I16(ptr+4)) {
case 4: case 11:
/* FLI COLOR chunk */
break; /* ignored; handled by Python code */
case 7:
/* FLI SS2 chunk (word delta) */
lines = I16(data); data += 2;
for (l = y = 0; l < lines && y < state->ysize; l++, y++) {
UINT8* buf = (UINT8*) im->image[y];
int p, packets;
packets = I16(data); data += 2;
while (packets & 0x8000) {
/* flag word */
if (packets & 0x4000) {
y += 65536 - packets; /* skip lines */
if (y >= state->ysize) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
buf = (UINT8*) im->image[y];
} else {
/* store last byte (used if line width is odd) */
buf[state->xsize-1] = (UINT8) packets;
}
packets = I16(data); data += 2;
}
for (p = x = 0; p < packets; p++) {
x += data[0]; /* pixel skip */
if (data[1] >= 128) {
i = 256-data[1]; /* run */
if (x + i + i > state->xsize)
break;
for (j = 0; j < i; j++) {
buf[x++] = data[2];
buf[x++] = data[3];
}
data += 2 + 2;
} else {
i = 2 * (int) data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(buf + x, data + 2, i);
data += 2 + i;
x += i;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (l < lines) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 12:
/* FLI LC chunk (byte delta) */
y = I16(data); ymax = y + I16(data+2); data += 4;
for (; y < ymax && y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
int p, packets = *data++;
for (p = x = 0; p < packets; p++, x += i) {
x += data[0]; /* skip pixels */
if (data[1] & 0x80) {
i = 256-data[1]; /* run */
if (x + i > state->xsize)
break;
memset(out + x, data[2], i);
data += 3;
} else {
i = data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(out + x, data + 2, i);
data += i + 2;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (y < ymax) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 13:
/* FLI BLACK chunk */
for (y = 0; y < state->ysize; y++)
memset(im->image[y], 0, state->xsize);
break;
case 15:
/* FLI BRUN chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
data += 1; /* ignore packetcount byte */
for (x = 0; x < state->xsize; x += i) {
if (data[0] & 0x80) {
i = 256 - data[0];
if (x + i > state->xsize)
break; /* safety first */
memcpy(out + x, data + 1, i);
data += i + 1;
} else {
i = data[0];
if (x + i > state->xsize)
break; /* safety first */
memset(out + x, data[1], i);
data += 2;
}
}
if (x != state->xsize) {
/* didn't unpack whole line */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
}
break;
case 16:
/* COPY chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* buf = (UINT8*) im->image[y];
memcpy(buf, data, state->xsize);
data += state->xsize;
}
break;
case 18:
/* PSTAMP chunk */
break; /* ignored */
default:
/* unknown chunk */
/* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
advance = I32(ptr);
ptr += advance;
bytes -= advance;
}
return -1; /* end of frame */
} | ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
UINT8* ptr;
int framesize;
int c, chunks, advance;
int l, lines;
int i, j, x = 0, y, ymax;
/* If not even the chunk size is present, we'd better leave */
if (bytes < 4)
return 0;
/* We don't decode anything unless we have a full chunk in the
input buffer */
ptr = buf;
framesize = I32(ptr);
if (framesize < I32(ptr))
return 0;
/* Make sure this is a frame chunk. The Python driver takes
case of other chunk types. */
if (bytes < 8) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
if (I16(ptr+4) != 0xF1FA) {
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
chunks = I16(ptr+6);
ptr += 16;
bytes -= 16;
/* Process subchunks */
for (c = 0; c < chunks; c++) {
UINT8* data;
if (bytes < 10) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
data = ptr + 6;
switch (I16(ptr+4)) {
case 4: case 11:
/* FLI COLOR chunk */
break; /* ignored; handled by Python code */
case 7:
/* FLI SS2 chunk (word delta) */
lines = I16(data); data += 2;
for (l = y = 0; l < lines && y < state->ysize; l++, y++) {
UINT8* buf = (UINT8*) im->image[y];
int p, packets;
packets = I16(data); data += 2;
while (packets & 0x8000) {
/* flag word */
if (packets & 0x4000) {
y += 65536 - packets; /* skip lines */
if (y >= state->ysize) {
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
buf = (UINT8*) im->image[y];
} else {
/* store last byte (used if line width is odd) */
buf[state->xsize-1] = (UINT8) packets;
}
packets = I16(data); data += 2;
}
for (p = x = 0; p < packets; p++) {
x += data[0]; /* pixel skip */
if (data[1] >= 128) {
i = 256-data[1]; /* run */
if (x + i + i > state->xsize)
break;
for (j = 0; j < i; j++) {
buf[x++] = data[2];
buf[x++] = data[3];
}
data += 2 + 2;
} else {
i = 2 * (int) data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(buf + x, data + 2, i);
data += 2 + i;
x += i;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (l < lines) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 12:
/* FLI LC chunk (byte delta) */
y = I16(data); ymax = y + I16(data+2); data += 4;
for (; y < ymax && y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
int p, packets = *data++;
for (p = x = 0; p < packets; p++, x += i) {
x += data[0]; /* skip pixels */
if (data[1] & 0x80) {
i = 256-data[1]; /* run */
if (x + i > state->xsize)
break;
memset(out + x, data[2], i);
data += 3;
} else {
i = data[1]; /* chunk */
if (x + i > state->xsize)
break;
memcpy(out + x, data + 2, i);
data += i + 2;
}
}
if (p < packets)
break; /* didn't process all packets */
}
if (y < ymax) {
/* didn't process all lines */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
break;
case 13:
/* FLI BLACK chunk */
for (y = 0; y < state->ysize; y++)
memset(im->image[y], 0, state->xsize);
break;
case 15:
/* FLI BRUN chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* out = (UINT8*) im->image[y];
data += 1; /* ignore packetcount byte */
for (x = 0; x < state->xsize; x += i) {
if (data[0] & 0x80) {
i = 256 - data[0];
if (x + i > state->xsize)
break; /* safety first */
memcpy(out + x, data + 1, i);
data += i + 1;
} else {
i = data[0];
if (x + i > state->xsize)
break; /* safety first */
memset(out + x, data[1], i);
data += 2;
}
}
if (x != state->xsize) {
/* didn't unpack whole line */
state->errcode = IMAGING_CODEC_OVERRUN;
return -1;
}
}
break;
case 16:
/* COPY chunk */
for (y = 0; y < state->ysize; y++) {
UINT8* buf = (UINT8*) im->image[y];
memcpy(buf, data, state->xsize);
data += state->xsize;
}
break;
case 18:
/* PSTAMP chunk */
break; /* ignored */
default:
/* unknown chunk */
/* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */
state->errcode = IMAGING_CODEC_UNKNOWN;
return -1;
}
advance = I32(ptr);
ptr += advance;
bytes -= advance;
}
return -1; /* end of frame */
} | {
"deleted": [
{
"line_no": 15,
"char_start": 364,
"char_end": 434,
"line": " input buffer (on the other hand, the Python part of the driver\n"
},
{
"line_no": 16,
"char_start": 434,
"char_end": 480,
"line": " makes sure this is always the case) */\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 364,
"char_end": 387,
"line": " input buffer */\n"
},
{
"line_no": 26,
"char_start": 575,
"char_end": 596,
"line": " if (bytes < 8) {\n"
},
{
"line_no": 27,
"char_start": 596,
"char_end": 644,
"line": " state->errcode = IMAGING_CODEC_OVERRUN;\n"
},
{
"line_no": 28,
"char_start": 644,
"char_end": 663,
"line": " return -1;\n"
},
{
"line_no": 29,
"char_start": 663,
"char_end": 669,
"line": " }\n"
}
]
} | {
"deleted": [
{
"char_start": 384,
"char_end": 477,
"chars": "(on the other hand, the Python part of the driver\n makes sure this is always the case) "
}
],
"added": [
{
"char_start": 574,
"char_end": 668,
"chars": "\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }"
}
]
} | github.com/python-pillow/Pillow/commit/a09acd0decd8a87ccce939d5ff65dab59e7d365b | src/libImaging/FliDecode.c | cwe-125 |
saa7164_bus_get | int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg,
void *buf, int peekonly)
{
struct tmComResBusInfo *bus = &dev->bus;
u32 bytes_to_read, write_distance, curr_grp, curr_gwp,
new_grp, buf_size, space_rem;
struct tmComResInfo msg_tmp;
int ret = SAA_ERR_BAD_PARAMETER;
saa7164_bus_verify(dev);
if (msg == NULL)
return ret;
if (msg->size > dev->bus.m_wMaxReqSize) {
printk(KERN_ERR "%s() Exceeded dev->bus.m_wMaxReqSize\n",
__func__);
return ret;
}
if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) {
printk(KERN_ERR
"%s() Missing msg buf, size should be %d bytes\n",
__func__, msg->size);
return ret;
}
mutex_lock(&bus->lock);
/* Peek the bus to see if a msg exists, if it's not what we're expecting
* then return cleanly else read the message from the bus.
*/
curr_gwp = saa7164_readl(bus->m_dwGetWritePos);
curr_grp = saa7164_readl(bus->m_dwGetReadPos);
if (curr_gwp == curr_grp) {
ret = SAA_ERR_EMPTY;
goto out;
}
bytes_to_read = sizeof(*msg);
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() No message/response found\n", __func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem);
memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing,
bytes_to_read - space_rem);
} else {
/* No wrapping */
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read);
}
/* Convert from little endian to CPU */
msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size);
msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command);
msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector);
/* No need to update the read positions, because this was a peek */
/* If the caller specifically want to peek, return */
if (peekonly) {
memcpy(msg, &msg_tmp, sizeof(*msg));
goto peekout;
}
/* Check if the command/response matches what is expected */
if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) ||
(msg_tmp.controlselector != msg->controlselector) ||
(msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) {
printk(KERN_ERR "%s() Unexpected msg miss-match\n", __func__);
saa7164_bus_dumpmsg(dev, msg, buf);
saa7164_bus_dumpmsg(dev, &msg_tmp, NULL);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Get the actual command and response from the bus */
buf_size = msg->size;
bytes_to_read = sizeof(*msg) + msg->size;
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n",
__func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
if (space_rem < sizeof(*msg)) {
/* msg wraps around the ring */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);
memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,
sizeof(*msg) - space_rem);
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) -
space_rem, buf_size);
} else if (space_rem == sizeof(*msg)) {
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing, buf_size);
} else {
/* Additional data wraps around the ring */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf) {
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp +
sizeof(*msg), space_rem - sizeof(*msg));
memcpy_fromio(buf + space_rem - sizeof(*msg),
bus->m_pdwGetRing, bytes_to_read -
space_rem);
}
}
} else {
/* No wrapping */
memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg),
buf_size);
}
/* Convert from little endian to CPU */
msg->size = le16_to_cpu((__force __le16)msg->size);
msg->command = le32_to_cpu((__force __le32)msg->command);
msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);
/* Update the read positions, adjusting the ring */
saa7164_writel(bus->m_dwGetReadPos, new_grp);
peekout:
ret = SAA_OK;
out:
mutex_unlock(&bus->lock);
saa7164_bus_verify(dev);
return ret;
} | int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg,
void *buf, int peekonly)
{
struct tmComResBusInfo *bus = &dev->bus;
u32 bytes_to_read, write_distance, curr_grp, curr_gwp,
new_grp, buf_size, space_rem;
struct tmComResInfo msg_tmp;
int ret = SAA_ERR_BAD_PARAMETER;
saa7164_bus_verify(dev);
if (msg == NULL)
return ret;
if (msg->size > dev->bus.m_wMaxReqSize) {
printk(KERN_ERR "%s() Exceeded dev->bus.m_wMaxReqSize\n",
__func__);
return ret;
}
if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) {
printk(KERN_ERR
"%s() Missing msg buf, size should be %d bytes\n",
__func__, msg->size);
return ret;
}
mutex_lock(&bus->lock);
/* Peek the bus to see if a msg exists, if it's not what we're expecting
* then return cleanly else read the message from the bus.
*/
curr_gwp = saa7164_readl(bus->m_dwGetWritePos);
curr_grp = saa7164_readl(bus->m_dwGetReadPos);
if (curr_gwp == curr_grp) {
ret = SAA_ERR_EMPTY;
goto out;
}
bytes_to_read = sizeof(*msg);
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() No message/response found\n", __func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem);
memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing,
bytes_to_read - space_rem);
} else {
/* No wrapping */
memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read);
}
/* Convert from little endian to CPU */
msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size);
msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command);
msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector);
memcpy(msg, &msg_tmp, sizeof(*msg));
/* No need to update the read positions, because this was a peek */
/* If the caller specifically want to peek, return */
if (peekonly) {
goto peekout;
}
/* Check if the command/response matches what is expected */
if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) ||
(msg_tmp.controlselector != msg->controlselector) ||
(msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) {
printk(KERN_ERR "%s() Unexpected msg miss-match\n", __func__);
saa7164_bus_dumpmsg(dev, msg, buf);
saa7164_bus_dumpmsg(dev, &msg_tmp, NULL);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Get the actual command and response from the bus */
buf_size = msg->size;
bytes_to_read = sizeof(*msg) + msg->size;
/* Calculate write distance to current read position */
write_distance = 0;
if (curr_gwp >= curr_grp)
/* Write doesn't wrap around the ring */
write_distance = curr_gwp - curr_grp;
else
/* Write wraps around the ring */
write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;
if (bytes_to_read > write_distance) {
printk(KERN_ERR "%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n",
__func__);
ret = SAA_ERR_INVALID_COMMAND;
goto out;
}
/* Calculate the new read position */
new_grp = curr_grp + bytes_to_read;
if (new_grp > bus->m_dwSizeGetRing) {
/* Ring wraps */
new_grp -= bus->m_dwSizeGetRing;
space_rem = bus->m_dwSizeGetRing - curr_grp;
if (space_rem < sizeof(*msg)) {
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) -
space_rem, buf_size);
} else if (space_rem == sizeof(*msg)) {
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing, buf_size);
} else {
/* Additional data wraps around the ring */
if (buf) {
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp +
sizeof(*msg), space_rem - sizeof(*msg));
memcpy_fromio(buf + space_rem - sizeof(*msg),
bus->m_pdwGetRing, bytes_to_read -
space_rem);
}
}
} else {
/* No wrapping */
if (buf)
memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg),
buf_size);
}
/* Update the read positions, adjusting the ring */
saa7164_writel(bus->m_dwGetReadPos, new_grp);
peekout:
ret = SAA_OK;
out:
mutex_unlock(&bus->lock);
saa7164_bus_verify(dev);
return ret;
} | {
"deleted": [
{
"line_no": 82,
"char_start": 2348,
"char_end": 2387,
"line": "\t\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n"
},
{
"line_no": 127,
"char_start": 3732,
"char_end": 3767,
"line": "\t\t\t/* msg wraps around the ring */\n"
},
{
"line_no": 128,
"char_start": 3767,
"char_end": 3831,
"line": "\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);\n"
},
{
"line_no": 129,
"char_start": 3831,
"char_end": 3890,
"line": "\t\t\tmemcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,\n"
},
{
"line_no": 130,
"char_start": 3890,
"char_end": 3921,
"line": "\t\t\t\tsizeof(*msg) - space_rem);\n"
},
{
"line_no": 136,
"char_start": 4061,
"char_end": 4128,
"line": "\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"line_no": 141,
"char_start": 4251,
"char_end": 4318,
"line": "\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"line_no": 154,
"char_start": 4580,
"char_end": 4646,
"line": "\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"line_no": 159,
"char_start": 4742,
"char_end": 4783,
"line": "\t/* Convert from little endian to CPU */\n"
},
{
"line_no": 160,
"char_start": 4783,
"char_end": 4836,
"line": "\tmsg->size = le16_to_cpu((__force __le16)msg->size);\n"
},
{
"line_no": 161,
"char_start": 4836,
"char_end": 4895,
"line": "\tmsg->command = le32_to_cpu((__force __le32)msg->command);\n"
},
{
"line_no": 162,
"char_start": 4895,
"char_end": 4970,
"line": "\tmsg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);\n"
}
],
"added": [
{
"line_no": 78,
"char_start": 2206,
"char_end": 2244,
"line": "\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n"
}
]
} | {
"deleted": [
{
"char_start": 2348,
"char_end": 2387,
"chars": "\t\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n"
},
{
"char_start": 3732,
"char_end": 3921,
"chars": "\t\t\t/* msg wraps around the ring */\n\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);\n\t\t\tmemcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,\n\t\t\t\tsizeof(*msg) - space_rem);\n"
},
{
"char_start": 4061,
"char_end": 4128,
"chars": "\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"char_start": 4251,
"char_end": 4318,
"chars": "\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"char_start": 4580,
"char_end": 4646,
"chars": "\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n"
},
{
"char_start": 4741,
"char_end": 4969,
"chars": "\n\t/* Convert from little endian to CPU */\n\tmsg->size = le16_to_cpu((__force __le16)msg->size);\n\tmsg->command = le32_to_cpu((__force __le32)msg->command);\n\tmsg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);"
}
],
"added": [
{
"char_start": 2206,
"char_end": 2244,
"chars": "\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n"
},
{
"char_start": 4349,
"char_end": 4349,
"chars": ""
}
]
} | github.com/stoth68000/media-tree/commit/354dd3924a2e43806774953de536257548b5002c | drivers/media/pci/saa7164/saa7164-bus.c | cwe-125 |
parallel_process_irp_create | static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)
{
char* path = NULL;
int status;
UINT32 PathLength;
Stream_Seek(irp->input, 28);
/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */
/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */
Stream_Read_UINT32(irp->input, PathLength);
status = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,
&path, 0, NULL, NULL);
if (status < 1)
if (!(path = (char*)calloc(1, 1)))
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
parallel->id = irp->devman->id_sequence++;
parallel->file = open(parallel->path, O_RDWR);
if (parallel->file < 0)
{
irp->IoStatus = STATUS_ACCESS_DENIED;
parallel->id = 0;
}
else
{
/* all read and write operations should be non-blocking */
if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)
{
}
}
Stream_Write_UINT32(irp->output, parallel->id);
Stream_Write_UINT8(irp->output, 0);
free(path);
return irp->Complete(irp);
} | static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)
{
char* path = NULL;
int status;
WCHAR* ptr;
UINT32 PathLength;
if (!Stream_SafeSeek(irp->input, 28))
return ERROR_INVALID_DATA;
/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */
/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */
if (Stream_GetRemainingLength(irp->input) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, PathLength);
ptr = (WCHAR*)Stream_Pointer(irp->input);
if (!Stream_SafeSeek(irp->input, PathLength))
return ERROR_INVALID_DATA;
status = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);
if (status < 1)
if (!(path = (char*)calloc(1, 1)))
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
parallel->id = irp->devman->id_sequence++;
parallel->file = open(parallel->path, O_RDWR);
if (parallel->file < 0)
{
irp->IoStatus = STATUS_ACCESS_DENIED;
parallel->id = 0;
}
else
{
/* all read and write operations should be non-blocking */
if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)
{
}
}
Stream_Write_UINT32(irp->output, parallel->id);
Stream_Write_UINT8(irp->output, 0);
free(path);
return irp->Complete(irp);
} | {
"deleted": [
{
"line_no": 6,
"char_start": 132,
"char_end": 162,
"line": "\tStream_Seek(irp->input, 28);\n"
},
{
"line_no": 10,
"char_start": 330,
"char_end": 423,
"line": "\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n"
},
{
"line_no": 11,
"char_start": 423,
"char_end": 475,
"line": "\t &path, 0, NULL, NULL);\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 112,
"char_end": 125,
"line": "\tWCHAR* ptr;\n"
},
{
"line_no": 7,
"char_start": 145,
"char_end": 184,
"line": "\tif (!Stream_SafeSeek(irp->input, 28))\n"
},
{
"line_no": 8,
"char_start": 184,
"char_end": 213,
"line": "\t\treturn ERROR_INVALID_DATA;\n"
},
{
"line_no": 11,
"char_start": 336,
"char_end": 384,
"line": "\tif (Stream_GetRemainingLength(irp->input) < 4)\n"
},
{
"line_no": 12,
"char_start": 384,
"char_end": 413,
"line": "\t\treturn ERROR_INVALID_DATA;\n"
},
{
"line_no": 14,
"char_start": 458,
"char_end": 501,
"line": "\tptr = (WCHAR*)Stream_Pointer(irp->input);\n"
},
{
"line_no": 15,
"char_start": 501,
"char_end": 548,
"line": "\tif (!Stream_SafeSeek(irp->input, PathLength))\n"
},
{
"line_no": 16,
"char_start": 548,
"char_end": 577,
"line": "\t\treturn ERROR_INVALID_DATA;\n"
},
{
"line_no": 17,
"char_start": 577,
"char_end": 662,
"line": "\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n"
}
]
} | {
"deleted": [
{
"char_start": 331,
"char_end": 332,
"chars": "s"
},
{
"char_start": 333,
"char_end": 345,
"chars": "atus = Conve"
},
{
"char_start": 346,
"char_end": 367,
"chars": "tFromUnicode(CP_UTF8,"
},
{
"char_start": 368,
"char_end": 370,
"chars": "0,"
},
{
"char_start": 417,
"char_end": 422,
"chars": " / 2,"
},
{
"char_start": 424,
"char_end": 443,
"chars": " "
}
],
"added": [
{
"char_start": 113,
"char_end": 126,
"chars": "WCHAR* ptr;\n\t"
},
{
"char_start": 146,
"char_end": 151,
"chars": "if (!"
},
{
"char_start": 158,
"char_end": 162,
"chars": "Safe"
},
{
"char_start": 182,
"char_end": 211,
"chars": ")\n\t\treturn ERROR_INVALID_DATA"
},
{
"char_start": 337,
"char_end": 414,
"chars": "if (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\t"
},
{
"char_start": 459,
"char_end": 460,
"chars": "p"
},
{
"char_start": 461,
"char_end": 462,
"chars": "r"
},
{
"char_start": 499,
"char_end": 533,
"chars": ";\n\tif (!Stream_SafeSeek(irp->input"
},
{
"char_start": 545,
"char_end": 556,
"chars": "))\n\t\treturn"
},
{
"char_start": 557,
"char_end": 576,
"chars": "ERROR_INVALID_DATA;"
},
{
"char_start": 578,
"char_end": 584,
"chars": "status"
},
{
"char_start": 585,
"char_end": 586,
"chars": "="
},
{
"char_start": 587,
"char_end": 614,
"chars": "ConvertFromUnicode(CP_UTF8,"
},
{
"char_start": 615,
"char_end": 617,
"chars": "0,"
},
{
"char_start": 618,
"char_end": 622,
"chars": "ptr,"
},
{
"char_start": 623,
"char_end": 633,
"chars": "PathLength"
},
{
"char_start": 634,
"char_end": 635,
"chars": "/"
},
{
"char_start": 636,
"char_end": 638,
"chars": "2,"
}
]
} | github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7 | channels/parallel/client/parallel_main.c | cwe-125 |
tflite::GetOptionalInputTensor | const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,
const TfLiteNode* node, int index) {
const bool use_tensor = index < node->inputs->size &&
node->inputs->data[index] != kTfLiteOptionalTensor;
if (use_tensor) {
return GetMutableInput(context, node, index);
}
return nullptr;
} | const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,
const TfLiteNode* node, int index) {
return GetInput(context, node, index);
} | {
"deleted": [
{
"line_no": 3,
"char_start": 153,
"char_end": 209,
"line": " const bool use_tensor = index < node->inputs->size &&\n"
},
{
"line_no": 4,
"char_start": 209,
"char_end": 287,
"line": " node->inputs->data[index] != kTfLiteOptionalTensor;\n"
},
{
"line_no": 5,
"char_start": 287,
"char_end": 307,
"line": " if (use_tensor) {\n"
},
{
"line_no": 6,
"char_start": 307,
"char_end": 357,
"line": " return GetMutableInput(context, node, index);\n"
},
{
"line_no": 7,
"char_start": 357,
"char_end": 361,
"line": " }\n"
},
{
"line_no": 8,
"char_start": 361,
"char_end": 379,
"line": " return nullptr;\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 153,
"char_end": 194,
"line": " return GetInput(context, node, index);\n"
}
]
} | {
"deleted": [
{
"char_start": 155,
"char_end": 311,
"chars": "const bool use_tensor = index < node->inputs->size &&\n node->inputs->data[index] != kTfLiteOptionalTensor;\n if (use_tensor) {\n "
},
{
"char_start": 321,
"char_end": 328,
"chars": "Mutable"
},
{
"char_start": 355,
"char_end": 377,
"chars": ";\n }\n return nullptr"
}
],
"added": []
} | github.com/tensorflow/tensorflow/commit/00302787b788c5ff04cb6f62aed5a74d936e86c0 | tensorflow/lite/kernels/kernel_util.cc | cwe-125 |
ReadOneMNGImage | static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
} | static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
} | {
"deleted": [],
"added": [
{
"line_no": 885,
"char_start": 27353,
"char_end": 27408,
"line": " if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n"
},
{
"line_no": 886,
"char_start": 27408,
"char_end": 27436,
"line": " continue;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 27373,
"char_end": 27456,
"chars": "(i < 0) || (i >= MNG_MAX_OBJECTS))\n continue;\n if ("
}
]
} | github.com/ImageMagick/ImageMagick/commit/78d4c5db50fbab0b4beb69c46c6167f2c6513dec | coders/png.c | cwe-125 |
WriteTIFFImage | static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
imageListLength;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric,
predictor;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
if (image->exception.severity > ErrorException)
{
TIFFClose(tiff);
return(MagickFalse);
}
(void) DeleteImageProfile(image,"tiff:37724");
scene=0;
debug=IsEventLogging();
(void) debug;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
#if defined(COMPRESSION_WEBP)
case WebPCompression:
{
compress_tag=COMPRESSION_WEBP;
break;
}
#endif
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
#if defined(COMPRESSION_ZSTD)
case ZstdCompression:
{
compress_tag=COMPRESSION_ZSTD;
break;
}
#endif
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) ||
(compress_tag == COMPRESSION_CCITTFAX4))
{
if ((photometric != PHOTOMETRIC_MINISWHITE) &&
(photometric != PHOTOMETRIC_MINISBLACK))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
predictor=0;
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
break;
}
#if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality);
if (image_info->quality >= 100)
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
break;
}
#endif
#if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
100.0);
break;
}
#endif
default:
break;
}
option=GetImageOption(image_info,"tiff:predictor");
if (option != (const char * ) NULL)
predictor=(size_t) strtol(option,(char **) NULL,10);
if (predictor != 0)
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (imageListLength > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
imageListLength);
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
else
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) imageListLength;
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
{
if (red != (uint16 *) NULL)
red=(uint16 *) RelinquishMagickMemory(red);
if (green != (uint16 *) NULL)
green=(uint16 *) RelinquishMagickMemory(green);
if (blue != (uint16 *) NULL)
blue=(uint16 *) RelinquishMagickMemory(blue);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize TIFF colormap.
*/
(void) memset(red,0,65536*sizeof(*red));
(void) memset(green,0,65536*sizeof(*green));
(void) memset(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
if (image->exception.severity > ErrorException)
break;
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue);
} | static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
imageListLength;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric,
predictor;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
if (image->exception.severity > ErrorException)
{
TIFFClose(tiff);
return(MagickFalse);
}
(void) DeleteImageProfile(image,"tiff:37724");
scene=0;
debug=IsEventLogging();
(void) debug;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
#if defined(COMPRESSION_WEBP)
case WebPCompression:
{
compress_tag=COMPRESSION_WEBP;
break;
}
#endif
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
#if defined(COMPRESSION_ZSTD)
case ZstdCompression:
{
compress_tag=COMPRESSION_ZSTD;
break;
}
#endif
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) ||
(compress_tag == COMPRESSION_CCITTFAX4))
{
if ((photometric != PHOTOMETRIC_MINISWHITE) &&
(photometric != PHOTOMETRIC_MINISBLACK))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
predictor=0;
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
break;
}
#if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality);
if (image_info->quality >= 100)
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
break;
}
#endif
#if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
100.0);
break;
}
#endif
default:
break;
}
option=GetImageOption(image_info,"tiff:predictor");
if (option != (const char * ) NULL)
predictor=(size_t) strtol(option,(char **) NULL,10);
if (predictor != 0)
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (imageListLength > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
imageListLength);
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
else
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) imageListLength;
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
{
if (red != (uint16 *) NULL)
red=(uint16 *) RelinquishMagickMemory(red);
if (green != (uint16 *) NULL)
green=(uint16 *) RelinquishMagickMemory(green);
if (blue != (uint16 *) NULL)
blue=(uint16 *) RelinquishMagickMemory(blue);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize TIFF colormap.
*/
(void) memset(red,0,65536*sizeof(*red));
(void) memset(green,0,65536*sizeof(*green));
(void) memset(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
if (TIFFWriteDirectory(tiff) == 0)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(status);
} | {
"deleted": [
{
"line_no": 893,
"char_start": 30340,
"char_end": 30392,
"line": " if (image->exception.severity > ErrorException)\n"
},
{
"line_no": 894,
"char_start": 30392,
"char_end": 30405,
"line": " break;\n"
},
{
"line_no": 899,
"char_start": 30549,
"char_end": 30586,
"line": " (void) TIFFWriteDirectory(tiff);\n"
},
{
"line_no": 908,
"char_start": 30854,
"char_end": 30935,
"line": " return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue);\n"
}
],
"added": [
{
"line_no": 897,
"char_start": 30484,
"char_end": 30523,
"line": " if (TIFFWriteDirectory(tiff) == 0)\n"
},
{
"line_no": 898,
"char_start": 30523,
"char_end": 30531,
"line": " {\n"
},
{
"line_no": 899,
"char_start": 30531,
"char_end": 30559,
"line": " status=MagickFalse;\n"
},
{
"line_no": 900,
"char_start": 30559,
"char_end": 30574,
"line": " break;\n"
},
{
"line_no": 901,
"char_start": 30574,
"char_end": 30582,
"line": " }\n"
},
{
"line_no": 910,
"char_start": 30850,
"char_end": 30868,
"line": " return(status);\n"
}
]
} | {
"deleted": [
{
"char_start": 30340,
"char_end": 30405,
"chars": " if (image->exception.severity > ErrorException)\n break;\n"
},
{
"char_start": 30553,
"char_end": 30556,
"chars": "(vo"
},
{
"char_start": 30557,
"char_end": 30559,
"chars": "d)"
},
{
"char_start": 30863,
"char_end": 30880,
"chars": "image->exception."
},
{
"char_start": 30881,
"char_end": 30886,
"chars": "everi"
},
{
"char_start": 30887,
"char_end": 30901,
"chars": "y > ErrorExcep"
},
{
"char_start": 30902,
"char_end": 30917,
"chars": "ion ? MagickFal"
},
{
"char_start": 30918,
"char_end": 30932,
"chars": "e : MagickTrue"
}
],
"added": [
{
"char_start": 30489,
"char_end": 30490,
"chars": "f"
},
{
"char_start": 30491,
"char_end": 30492,
"chars": "("
},
{
"char_start": 30516,
"char_end": 30557,
"chars": " == 0)\n {\n status=MagickFalse"
},
{
"char_start": 30559,
"char_end": 30582,
"chars": " break;\n }\n"
},
{
"char_start": 30862,
"char_end": 30864,
"chars": "tu"
}
]
} | github.com/ImageMagick/ImageMagick6/commit/3c53413eb544cc567309b4c86485eae43e956112 | coders/tiff.c | cwe-125 |
adjust_scalar_min_max_vals | static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
} | static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
if (insn_bitness == 32) {
/* Relevant for 32-bit RSH: Information can propagate towards
* LSB, so it isn't sufficient to only truncate the output to
* 32 bits.
*/
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
} | {
"deleted": [
{
"line_no": 248,
"char_start": 8087,
"char_end": 8122,
"line": "\t\tcoerce_reg_to_size(&src_reg, 4);\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 409,
"char_end": 436,
"line": "\tif (insn_bitness == 32) {\n"
},
{
"line_no": 14,
"char_start": 436,
"char_end": 500,
"line": "\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n"
},
{
"line_no": 15,
"char_start": 500,
"char_end": 564,
"line": "\t\t * LSB, so it isn't sufficient to only truncate the output to\n"
},
{
"line_no": 16,
"char_start": 564,
"char_end": 578,
"line": "\t\t * 32 bits.\n"
},
{
"line_no": 17,
"char_start": 578,
"char_end": 584,
"line": "\t\t */\n"
},
{
"line_no": 18,
"char_start": 584,
"char_end": 618,
"line": "\t\tcoerce_reg_to_size(dst_reg, 4);\n"
},
{
"line_no": 19,
"char_start": 618,
"char_end": 653,
"line": "\t\tcoerce_reg_to_size(&src_reg, 4);\n"
},
{
"line_no": 20,
"char_start": 653,
"char_end": 656,
"line": "\t}\n"
},
{
"line_no": 21,
"char_start": 656,
"char_end": 657,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 8077,
"char_end": 8112,
"chars": "_reg, 4);\n\t\tcoerce_reg_to_size(&src"
}
],
"added": [
{
"char_start": 410,
"char_end": 658,
"chars": "if (insn_bitness == 32) {\n\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n\t\t * LSB, so it isn't sufficient to only truncate the output to\n\t\t * 32 bits.\n\t\t */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t\tcoerce_reg_to_size(&src_reg, 4);\n\t}\n\n\t"
}
]
} | github.com/torvalds/linux/commit/b799207e1e1816b09e7a5920fbb2d5fcf6edd681 | kernel/bpf/verifier.c | cwe-125 |
ip_cmsg_recv_checksum | static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,
int tlen, int offset)
{
__wsum csum = skb->csum;
if (skb->ip_summed != CHECKSUM_COMPLETE)
return;
if (offset != 0)
csum = csum_sub(csum,
csum_partial(skb_transport_header(skb) + tlen,
offset, 0));
put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);
} | static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,
int tlen, int offset)
{
__wsum csum = skb->csum;
if (skb->ip_summed != CHECKSUM_COMPLETE)
return;
if (offset != 0) {
int tend_off = skb_transport_offset(skb) + tlen;
csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0));
}
put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);
} | {
"deleted": [
{
"line_no": 9,
"char_start": 185,
"char_end": 203,
"line": "\tif (offset != 0)\n"
},
{
"line_no": 10,
"char_start": 203,
"char_end": 227,
"line": "\t\tcsum = csum_sub(csum,\n"
},
{
"line_no": 11,
"char_start": 227,
"char_end": 278,
"line": "\t\t\t\tcsum_partial(skb_transport_header(skb) + tlen,\n"
},
{
"line_no": 12,
"char_start": 278,
"char_end": 301,
"line": "\t\t\t\t\t offset, 0));\n"
}
],
"added": [
{
"line_no": 9,
"char_start": 185,
"char_end": 205,
"line": "\tif (offset != 0) {\n"
},
{
"line_no": 10,
"char_start": 205,
"char_end": 256,
"line": "\t\tint tend_off = skb_transport_offset(skb) + tlen;\n"
},
{
"line_no": 11,
"char_start": 256,
"char_end": 321,
"line": "\t\tcsum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0));\n"
},
{
"line_no": 12,
"char_start": 321,
"char_end": 324,
"line": "\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 205,
"char_end": 209,
"chars": "csum"
},
{
"char_start": 212,
"char_end": 244,
"chars": "csum_sub(csum,\n\t\t\t\tcsum_partial("
},
{
"char_start": 258,
"char_end": 259,
"chars": "h"
},
{
"char_start": 260,
"char_end": 264,
"chars": "ader"
},
{
"char_start": 276,
"char_end": 277,
"chars": ","
},
{
"char_start": 280,
"char_end": 283,
"chars": "\t\t\t"
}
],
"added": [
{
"char_start": 202,
"char_end": 204,
"chars": " {"
},
{
"char_start": 207,
"char_end": 219,
"chars": "int tend_off"
},
{
"char_start": 236,
"char_end": 240,
"chars": "offs"
},
{
"char_start": 241,
"char_end": 242,
"chars": "t"
},
{
"char_start": 254,
"char_end": 255,
"chars": ";"
},
{
"char_start": 258,
"char_end": 262,
"chars": "csum"
},
{
"char_start": 263,
"char_end": 264,
"chars": "="
},
{
"char_start": 265,
"char_end": 279,
"chars": "csum_sub(csum,"
},
{
"char_start": 280,
"char_end": 297,
"chars": "skb_checksum(skb,"
},
{
"char_start": 298,
"char_end": 307,
"chars": "tend_off,"
},
{
"char_start": 320,
"char_end": 323,
"chars": "\n\t}"
}
]
} | github.com/torvalds/linux/commit/ca4ef4574f1ee5252e2cd365f8f5d5bafd048f32 | net/ipv4/ip_sockglue.c | cwe-125 |
HPHP::SimpleParser::TryParse | static bool TryParse(const char* inp, int length,
TypedValue* buf, Variant& out,
JSONContainerType container_type, bool is_tsimplejson) {
SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);
bool ok = parser.parseValue();
parser.skipSpace();
if (!ok || parser.p != inp + length) {
// Unsupported, malformed, or trailing garbage. Release entire stack.
tvDecRefRange(buf, parser.top);
return false;
}
out = Variant::attach(*--parser.top);
return true;
} | static bool TryParse(const char* inp, int length,
TypedValue* buf, Variant& out,
JSONContainerType container_type, bool is_tsimplejson) {
SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);
bool ok = parser.parseValue();
if (!ok ||
(parser.skipSpace(), parser.p != inp + length)) {
// Unsupported, malformed, or trailing garbage. Release entire stack.
tvDecRefRange(buf, parser.top);
return false;
}
out = Variant::attach(*--parser.top);
return true;
} | {
"deleted": [
{
"line_no": 6,
"char_start": 296,
"char_end": 320,
"line": " parser.skipSpace();\n"
},
{
"line_no": 7,
"char_start": 320,
"char_end": 363,
"line": " if (!ok || parser.p != inp + length) {\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 296,
"char_end": 311,
"line": " if (!ok ||\n"
},
{
"line_no": 7,
"char_start": 311,
"char_end": 369,
"line": " (parser.skipSpace(), parser.p != inp + length)) {\n"
}
]
} | {
"deleted": [
{
"char_start": 318,
"char_end": 334,
"chars": ";\n if (!ok ||"
}
],
"added": [
{
"char_start": 300,
"char_end": 320,
"chars": "if (!ok ||\n ("
},
{
"char_start": 338,
"char_end": 339,
"chars": ","
},
{
"char_start": 364,
"char_end": 365,
"chars": ")"
}
]
} | github.com/facebook/hhvm/commit/bd586671a3c22eb2f07e55f11b3ce64e1f7961e7 | hphp/runtime/ext/json/JSON_parser.cpp | cwe-125 |
_gdContributionsCalc | static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
} | static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
} | {
"deleted": [
{
"line_no": 28,
"char_start": 847,
"char_end": 882,
"line": "\t\tres->ContribRow[u].Left = iLeft;\n"
},
{
"line_no": 29,
"char_start": 882,
"char_end": 919,
"line": "\t\tres->ContribRow[u].Right = iRight;\n"
},
{
"line_no": 30,
"char_start": 919,
"char_end": 920,
"line": "\n"
}
],
"added": [
{
"line_no": 37,
"char_start": 1052,
"char_end": 1087,
"line": "\t\tres->ContribRow[u].Left = iLeft;\n"
},
{
"line_no": 38,
"char_start": 1087,
"char_end": 1124,
"line": "\t\tres->ContribRow[u].Right = iRight;\n"
},
{
"line_no": 39,
"char_start": 1124,
"char_end": 1125,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 849,
"char_end": 922,
"chars": "res->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\t"
}
],
"added": [
{
"char_start": 1050,
"char_end": 1123,
"chars": "\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;"
}
]
} | github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a | src/gd_interpolation.c | cwe-125 |
Get8BIMProperty | static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
} | static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
} | {
"deleted": [],
"added": [
{
"line_no": 90,
"char_start": 2403,
"char_end": 2453,
"line": " if ((count < 0) || ((size_t) count > length))\n"
},
{
"line_no": 91,
"char_start": 2453,
"char_end": 2461,
"line": " {\n"
},
{
"line_no": 92,
"char_start": 2461,
"char_end": 2480,
"line": " length=0; \n"
},
{
"line_no": 93,
"char_start": 2480,
"char_end": 2498,
"line": " continue;\n"
},
{
"line_no": 94,
"char_start": 2498,
"char_end": 2506,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2412,
"char_end": 2515,
"chars": "count < 0) || ((size_t) count > length))\n {\n length=0; \n continue;\n }\n if (("
}
]
} | github.com/ImageMagick/ImageMagick/commit/dd84447b63a71fa8c3f47071b09454efc667767b | MagickCore/property.c | cwe-125 |
parse_string | static const char *parse_string(cJSON *item,const char *str,const char **ep)
{
const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {*ep=str;return 0;} /* not a string! */
while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */
item->type=cJSON_String;
ptr=str+1;ptr2=out;
while (ptr < end_ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */
if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
return ptr;
} | static const char *parse_string(cJSON *item,const char *str,const char **ep)
{
const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {*ep=str;return 0;} /* not a string! */
while (*end_ptr!='\"' && *end_ptr && ++len)
{
if (*end_ptr++ == '\\')
{
if (*end_ptr == '\0')
{
/* prevent buffer overflow when last input character is a backslash */
return 0;
}
end_ptr++; /* Skip escaped quotes. */
}
}
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */
item->type=cJSON_String;
ptr=str+1;ptr2=out;
while (ptr < end_ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */
if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
return ptr;
} | {
"deleted": [
{
"line_no": 5,
"char_start": 222,
"char_end": 224,
"line": "\t\n"
},
{
"line_no": 6,
"char_start": 224,
"char_end": 331,
"line": "\twhile (*end_ptr!='\\\"' && *end_ptr && ++len) if (*end_ptr++ == '\\\\') end_ptr++;\t/* Skip escaped quotes. */\n"
},
{
"line_no": 7,
"char_start": 331,
"char_end": 333,
"line": "\t\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 222,
"char_end": 223,
"line": "\n"
},
{
"line_no": 6,
"char_start": 223,
"char_end": 268,
"line": "\twhile (*end_ptr!='\\\"' && *end_ptr && ++len)\n"
},
{
"line_no": 7,
"char_start": 268,
"char_end": 271,
"line": "\t{\n"
},
{
"line_no": 8,
"char_start": 271,
"char_end": 300,
"line": "\t if (*end_ptr++ == '\\\\')\n"
},
{
"line_no": 9,
"char_start": 300,
"char_end": 307,
"line": "\t {\n"
},
{
"line_no": 10,
"char_start": 307,
"char_end": 331,
"line": "\t\tif (*end_ptr == '\\0')\n"
},
{
"line_no": 11,
"char_start": 331,
"char_end": 335,
"line": "\t\t{\n"
},
{
"line_no": 12,
"char_start": 335,
"char_end": 412,
"line": "\t\t /* prevent buffer overflow when last input character is a backslash */\n"
},
{
"line_no": 13,
"char_start": 412,
"char_end": 428,
"line": "\t\t return 0;\n"
},
{
"line_no": 14,
"char_start": 428,
"char_end": 432,
"line": "\t\t}\n"
},
{
"line_no": 15,
"char_start": 432,
"char_end": 472,
"line": "\t\tend_ptr++;\t/* Skip escaped quotes. */\n"
},
{
"line_no": 16,
"char_start": 472,
"char_end": 479,
"line": "\t }\n"
},
{
"line_no": 17,
"char_start": 479,
"char_end": 482,
"line": "\t}\n"
},
{
"line_no": 18,
"char_start": 482,
"char_end": 483,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 222,
"char_end": 223,
"chars": "\t"
}
],
"added": [
{
"char_start": 267,
"char_end": 275,
"chars": "\n\t{\n\t "
},
{
"char_start": 299,
"char_end": 301,
"chars": "\n\t"
},
{
"char_start": 302,
"char_end": 434,
"chars": " {\n\t\tif (*end_ptr == '\\0')\n\t\t{\n\t\t /* prevent buffer overflow when last input character is a backslash */\n\t\t return 0;\n\t\t}\n\t\t"
},
{
"char_start": 473,
"char_end": 482,
"chars": " }\n\t}\n"
}
]
} | github.com/DaveGamble/cJSON/commit/94df772485c92866ca417d92137747b2e3b0a917 | cJSON.c | cwe-125 |
dbd_st_prepare | dbd_st_prepare(
SV *sth,
imp_sth_t *imp_sth,
char *statement,
SV *attribs)
{
int i;
SV **svp;
dTHX;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
char *str_ptr, *str_last_ptr;
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
int limit_flag=0;
#endif
#endif
int col_type, prepare_retval;
MYSQL_BIND *bind, *bind_end;
imp_sth_phb_t *fbind;
#endif
D_imp_xxh(sth);
D_imp_dbh_from_sth;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n",
MYSQL_VERSION_ID, statement);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Set default value of 'mysql_server_prepare' attribute for sth from dbh */
imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare;
if (attribs)
{
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20);
imp_sth->use_server_side_prepare = (svp) ?
SvTRUE(*svp) : imp_dbh->use_server_side_prepare;
svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5);
if(svp && SvTRUE(*svp)) {
#if MYSQL_ASYNC
imp_sth->is_async = TRUE;
imp_sth->use_server_side_prepare = FALSE;
#else
do_error(sth, 2000,
"Async support was not built into this version of DBD::mysql", "HY000");
return 0;
#endif
}
}
imp_sth->fetch_done= 0;
#endif
imp_sth->done_desc= 0;
imp_sth->result= NULL;
imp_sth->currow= 0;
/* Set default value of 'mysql_use_result' attribute for sth from dbh */
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16);
imp_sth->use_mysql_use_result= svp ?
SvTRUE(*svp) : imp_dbh->use_mysql_use_result;
for (i= 0; i < AV_ATTRIB_LAST; i++)
imp_sth->av_attr[i]= Nullav;
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set, check restrictions\n");
/*
This code is here because placeholder support is not implemented for
statements with :-
1. LIMIT < 5.0.7
2. CALL < 5.5.3 (Added support for out & inout parameters)
In these cases we have to disable server side prepared statements
NOTE: These checks could cause a false positive on statements which
include columns / table names that match "call " or " limit "
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
"\t\tneed to test for LIMIT & CALL\n");
#else
"\t\tneed to test for restrictions\n");
#endif
str_last_ptr = statement + strlen(statement);
for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++)
{
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
/*
Place holders not supported in LIMIT's
*/
if (limit_flag)
{
if (*str_ptr == '?')
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tLIMIT and ? found, set to use_server_side_prepare=0\n");
/* ... then we do not want to try server side prepare (use emulation) */
imp_sth->use_server_side_prepare= 0;
break;
}
}
else if (str_ptr < str_last_ptr - 6 &&
isspace(*(str_ptr + 0)) &&
tolower(*(str_ptr + 1)) == 'l' &&
tolower(*(str_ptr + 2)) == 'i' &&
tolower(*(str_ptr + 3)) == 'm' &&
tolower(*(str_ptr + 4)) == 'i' &&
tolower(*(str_ptr + 5)) == 't' &&
isspace(*(str_ptr + 6)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n");
limit_flag= 1;
}
#endif
/*
Place holders not supported in CALL's
*/
if (str_ptr < str_last_ptr - 4 &&
tolower(*(str_ptr + 0)) == 'c' &&
tolower(*(str_ptr + 1)) == 'a' &&
tolower(*(str_ptr + 2)) == 'l' &&
tolower(*(str_ptr + 3)) == 'l' &&
isspace(*(str_ptr + 4)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n");
imp_sth->use_server_side_prepare= 0;
break;
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set\n");
/* do we really need this? If we do, we should return, not just continue */
if (imp_sth->stmt)
fprintf(stderr,
"ERROR: Trying to prepare new stmt while we have \
already not closed one \n");
imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql);
if (! imp_sth->stmt)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tERROR: Unable to return MYSQL_STMT structure \
from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n",
mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql));
}
prepare_retval= mysql_stmt_prepare(imp_sth->stmt,
statement,
strlen(statement));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare returned %d\n",
prepare_retval);
if (prepare_retval)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare %d %s\n",
mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt));
/* For commands that are not supported by server side prepared statement
mechanism lets try to pass them through regular API */
if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tSETTING imp_sth->use_server_side_prepare to 0\n");
imp_sth->use_server_side_prepare= 0;
}
else
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_sqlstate(imp_dbh->pmysql));
mysql_stmt_close(imp_sth->stmt);
imp_sth->stmt= NULL;
return FALSE;
}
}
else
{
DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt);
/* mysql_stmt_param_count */
if (DBIc_NUM_PARAMS(imp_sth) > 0)
{
int has_statement_fields= imp_sth->stmt->fields != 0;
/* Allocate memory for bind variables */
imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->has_been_bound= 0;
/* Initialize ph variables with NULL values */
for (i= 0,
bind= imp_sth->bind,
fbind= imp_sth->fbind,
bind_end= bind+DBIc_NUM_PARAMS(imp_sth);
bind < bind_end ;
bind++, fbind++, i++ )
{
/*
if this statement has a result set, field types will be
correctly identified. If there is no result set, such as
with an INSERT, fields will not be defined, and all buffer_type
will default to MYSQL_TYPE_VAR_STRING
*/
col_type= (has_statement_fields ?
imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING);
bind->buffer_type= mysql_to_perl_type(col_type);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type);
bind->buffer= NULL;
bind->length= &(fbind->length);
bind->is_null= (char*) &(fbind->is_null);
fbind->is_null= 1;
fbind->length= 0;
}
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Count the number of parameters (driver, vs server-side) */
if (imp_sth->use_server_side_prepare == 0)
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#else
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#endif
/* Allocate memory for parameters */
imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth));
DBIc_IMPSET_on(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n");
return 1;
} | dbd_st_prepare(
SV *sth,
imp_sth_t *imp_sth,
char *statement,
SV *attribs)
{
int i;
SV **svp;
dTHX;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
char *str_ptr, *str_last_ptr;
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
int limit_flag=0;
#endif
#endif
int prepare_retval;
MYSQL_BIND *bind, *bind_end;
imp_sth_phb_t *fbind;
#endif
D_imp_xxh(sth);
D_imp_dbh_from_sth;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n",
MYSQL_VERSION_ID, statement);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Set default value of 'mysql_server_prepare' attribute for sth from dbh */
imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare;
if (attribs)
{
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20);
imp_sth->use_server_side_prepare = (svp) ?
SvTRUE(*svp) : imp_dbh->use_server_side_prepare;
svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5);
if(svp && SvTRUE(*svp)) {
#if MYSQL_ASYNC
imp_sth->is_async = TRUE;
imp_sth->use_server_side_prepare = FALSE;
#else
do_error(sth, 2000,
"Async support was not built into this version of DBD::mysql", "HY000");
return 0;
#endif
}
}
imp_sth->fetch_done= 0;
#endif
imp_sth->done_desc= 0;
imp_sth->result= NULL;
imp_sth->currow= 0;
/* Set default value of 'mysql_use_result' attribute for sth from dbh */
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16);
imp_sth->use_mysql_use_result= svp ?
SvTRUE(*svp) : imp_dbh->use_mysql_use_result;
for (i= 0; i < AV_ATTRIB_LAST; i++)
imp_sth->av_attr[i]= Nullav;
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set, check restrictions\n");
/*
This code is here because placeholder support is not implemented for
statements with :-
1. LIMIT < 5.0.7
2. CALL < 5.5.3 (Added support for out & inout parameters)
In these cases we have to disable server side prepared statements
NOTE: These checks could cause a false positive on statements which
include columns / table names that match "call " or " limit "
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
"\t\tneed to test for LIMIT & CALL\n");
#else
"\t\tneed to test for restrictions\n");
#endif
str_last_ptr = statement + strlen(statement);
for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++)
{
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
/*
Place holders not supported in LIMIT's
*/
if (limit_flag)
{
if (*str_ptr == '?')
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tLIMIT and ? found, set to use_server_side_prepare=0\n");
/* ... then we do not want to try server side prepare (use emulation) */
imp_sth->use_server_side_prepare= 0;
break;
}
}
else if (str_ptr < str_last_ptr - 6 &&
isspace(*(str_ptr + 0)) &&
tolower(*(str_ptr + 1)) == 'l' &&
tolower(*(str_ptr + 2)) == 'i' &&
tolower(*(str_ptr + 3)) == 'm' &&
tolower(*(str_ptr + 4)) == 'i' &&
tolower(*(str_ptr + 5)) == 't' &&
isspace(*(str_ptr + 6)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n");
limit_flag= 1;
}
#endif
/*
Place holders not supported in CALL's
*/
if (str_ptr < str_last_ptr - 4 &&
tolower(*(str_ptr + 0)) == 'c' &&
tolower(*(str_ptr + 1)) == 'a' &&
tolower(*(str_ptr + 2)) == 'l' &&
tolower(*(str_ptr + 3)) == 'l' &&
isspace(*(str_ptr + 4)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n");
imp_sth->use_server_side_prepare= 0;
break;
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set\n");
/* do we really need this? If we do, we should return, not just continue */
if (imp_sth->stmt)
fprintf(stderr,
"ERROR: Trying to prepare new stmt while we have \
already not closed one \n");
imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql);
if (! imp_sth->stmt)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tERROR: Unable to return MYSQL_STMT structure \
from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n",
mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql));
}
prepare_retval= mysql_stmt_prepare(imp_sth->stmt,
statement,
strlen(statement));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare returned %d\n",
prepare_retval);
if (prepare_retval)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare %d %s\n",
mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt));
/* For commands that are not supported by server side prepared statement
mechanism lets try to pass them through regular API */
if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tSETTING imp_sth->use_server_side_prepare to 0\n");
imp_sth->use_server_side_prepare= 0;
}
else
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_sqlstate(imp_dbh->pmysql));
mysql_stmt_close(imp_sth->stmt);
imp_sth->stmt= NULL;
return FALSE;
}
}
else
{
DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt);
/* mysql_stmt_param_count */
if (DBIc_NUM_PARAMS(imp_sth) > 0)
{
/* Allocate memory for bind variables */
imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->has_been_bound= 0;
/* Initialize ph variables with NULL values */
for (i= 0,
bind= imp_sth->bind,
fbind= imp_sth->fbind,
bind_end= bind+DBIc_NUM_PARAMS(imp_sth);
bind < bind_end ;
bind++, fbind++, i++ )
{
bind->buffer_type= MYSQL_TYPE_STRING;
bind->buffer= NULL;
bind->length= &(fbind->length);
bind->is_null= (char*) &(fbind->is_null);
fbind->is_null= 1;
fbind->length= 0;
}
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Count the number of parameters (driver, vs server-side) */
if (imp_sth->use_server_side_prepare == 0)
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#else
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#endif
/* Allocate memory for parameters */
imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth));
DBIc_IMPSET_on(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n");
return 1;
} | {
"deleted": [
{
"line_no": 17,
"char_start": 324,
"char_end": 356,
"line": " int col_type, prepare_retval;\n"
},
{
"line_no": 213,
"char_start": 7021,
"char_end": 7083,
"line": " int has_statement_fields= imp_sth->stmt->fields != 0;\n"
},
{
"line_no": 227,
"char_start": 7601,
"char_end": 7614,
"line": " /*\n"
},
{
"line_no": 228,
"char_start": 7614,
"char_end": 7682,
"line": " if this statement has a result set, field types will be\n"
},
{
"line_no": 229,
"char_start": 7682,
"char_end": 7751,
"line": " correctly identified. If there is no result set, such as\n"
},
{
"line_no": 230,
"char_start": 7751,
"char_end": 7827,
"line": " with an INSERT, fields will not be defined, and all buffer_type\n"
},
{
"line_no": 231,
"char_start": 7827,
"char_end": 7877,
"line": " will default to MYSQL_TYPE_VAR_STRING\n"
},
{
"line_no": 232,
"char_start": 7877,
"char_end": 7890,
"line": " */\n"
},
{
"line_no": 233,
"char_start": 7890,
"char_end": 7934,
"line": " col_type= (has_statement_fields ?\n"
},
{
"line_no": 234,
"char_start": 7934,
"char_end": 8007,
"line": " imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING);\n"
},
{
"line_no": 235,
"char_start": 8007,
"char_end": 8008,
"line": "\n"
},
{
"line_no": 236,
"char_start": 8008,
"char_end": 8068,
"line": " bind->buffer_type= mysql_to_perl_type(col_type);\n"
},
{
"line_no": 237,
"char_start": 8068,
"char_end": 8069,
"line": "\n"
},
{
"line_no": 238,
"char_start": 8069,
"char_end": 8115,
"line": " if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n"
},
{
"line_no": 239,
"char_start": 8115,
"char_end": 8214,
"line": " PerlIO_printf(DBIc_LOGPIO(imp_xxh), \"\\t\\tmysql_to_perl_type returned %d\\n\", col_type);\n"
},
{
"line_no": 240,
"char_start": 8214,
"char_end": 8215,
"line": "\n"
}
],
"added": [
{
"line_no": 17,
"char_start": 324,
"char_end": 346,
"line": " int prepare_retval;\n"
},
{
"line_no": 226,
"char_start": 7529,
"char_end": 7578,
"line": " bind->buffer_type= MYSQL_TYPE_STRING;\n"
}
]
} | {
"deleted": [
{
"char_start": 330,
"char_end": 340,
"chars": "col_type, "
},
{
"char_start": 7029,
"char_end": 7091,
"chars": "int has_statement_fields= imp_sth->stmt->fields != 0;\n "
},
{
"char_start": 7611,
"char_end": 7679,
"chars": "/*\n if this statement has a result set, field types will "
},
{
"char_start": 7680,
"char_end": 7704,
"chars": "e\n correctly "
},
{
"char_start": 7705,
"char_end": 7707,
"chars": "de"
},
{
"char_start": 7708,
"char_end": 7713,
"chars": "tifie"
},
{
"char_start": 7714,
"char_end": 7815,
"chars": ". If there is no result set, such as\n with an INSERT, fields will not be defined, and all "
},
{
"char_start": 7826,
"char_end": 7908,
"chars": "\n will default to MYSQL_TYPE_VAR_STRING\n */\n col_type"
},
{
"char_start": 7910,
"char_end": 7986,
"chars": "(has_statement_fields ?\n imp_sth->stmt->fields[i].type :"
},
{
"char_start": 8004,
"char_end": 8005,
"chars": ")"
},
{
"char_start": 8006,
"char_end": 8214,
"chars": "\n\n bind->buffer_type= mysql_to_perl_type(col_type);\n\n if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n PerlIO_printf(DBIc_LOGPIO(imp_xxh), \"\\t\\tmysql_to_perl_type returned %d\\n\", col_type);\n"
}
],
"added": [
{
"char_start": 7060,
"char_end": 7060,
"chars": ""
},
{
"char_start": 7543,
"char_end": 7545,
"chars": "->"
}
]
} | github.com/perl5-dbi/DBD-mysql/commit/793b72b1a0baa5070adacaac0e12fd995a6fbabe | dbdimp.c | cwe-125 |
get_uncompressed_data | get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
} | get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
*buff = __archive_read_ahead(a, minimum, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
} | {
"deleted": [
{
"line_no": 10,
"char_start": 264,
"char_end": 269,
"line": "\t\t/*\n"
},
{
"line_no": 11,
"char_start": 269,
"char_end": 320,
"line": "\t\t * Note: '1' here is a performance optimization.\n"
},
{
"line_no": 12,
"char_start": 320,
"char_end": 380,
"line": "\t\t * Recall that the decompression layer returns a count of\n"
},
{
"line_no": 13,
"char_start": 380,
"char_end": 439,
"line": "\t\t * available bytes; asking for more than that forces the\n"
},
{
"line_no": 14,
"char_start": 439,
"char_end": 491,
"line": "\t\t * decompressor to combine reads by copying data.\n"
},
{
"line_no": 15,
"char_start": 491,
"char_end": 497,
"line": "\t\t */\n"
},
{
"line_no": 16,
"char_start": 497,
"char_end": 549,
"line": "\t\t*buff = __archive_read_ahead(a, 1, &bytes_avail);\n"
}
],
"added": [
{
"line_no": 10,
"char_start": 264,
"char_end": 322,
"line": "\t\t*buff = __archive_read_ahead(a, minimum, &bytes_avail);\n"
}
]
} | {
"deleted": [
{
"char_start": 266,
"char_end": 499,
"chars": "/*\n\t\t * Note: '1' here is a performance optimization.\n\t\t * Recall that the decompression layer returns a count of\n\t\t * available bytes; asking for more than that forces the\n\t\t * decompressor to combine reads by copying data.\n\t\t */\n\t\t"
},
{
"char_start": 531,
"char_end": 532,
"chars": "1"
}
],
"added": [
{
"char_start": 298,
"char_end": 305,
"chars": "minimum"
}
]
} | github.com/libarchive/libarchive/commit/65a23f5dbee4497064e9bb467f81138a62b0dae1 | libarchive/archive_read_support_format_7zip.c | cwe-125 |
security_fips_decrypt | BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
size_t olen;
if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen))
return FALSE;
return TRUE;
} | BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
size_t olen;
if (!rdp || !rdp->fips_decrypt)
return FALSE;
if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen))
return FALSE;
return TRUE;
} | {
"deleted": [],
"added": [
{
"line_no": 5,
"char_start": 84,
"char_end": 117,
"line": "\tif (!rdp || !rdp->fips_decrypt)\n"
},
{
"line_no": 6,
"char_start": 117,
"char_end": 133,
"line": "\t\treturn FALSE;\n"
},
{
"line_no": 7,
"char_start": 133,
"char_end": 134,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 90,
"char_end": 140,
"chars": "rdp || !rdp->fips_decrypt)\n\t\treturn FALSE;\n\n\tif (!"
}
]
} | github.com/FreeRDP/FreeRDP/commit/d6cd14059b257318f176c0ba3ee0a348826a9ef8 | libfreerdp/core/security.c | cwe-125 |
update_read_icon_info | static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)
{
BYTE* newBitMask;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */
if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp);
return FALSE;
}
Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */
Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */
/* cbColorTable is only present when bpp is 1, 4 or 8 */
switch (iconInfo->bpp)
{
case 1:
case 4:
case 8:
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */
break;
default:
iconInfo->cbColorTable = 0;
break;
}
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */
Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)
return FALSE;
/* bitsMask */
newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);
if (!newBitMask)
{
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
return FALSE;
}
iconInfo->bitsMask = newBitMask;
Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);
/* colorTable */
if (iconInfo->colorTable == NULL)
{
if (iconInfo->cbColorTable)
{
iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);
if (!iconInfo->colorTable)
return FALSE;
}
}
else if (iconInfo->cbColorTable)
{
BYTE* new_tab;
new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);
if (!new_tab)
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
return FALSE;
}
iconInfo->colorTable = new_tab;
}
else
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
if (iconInfo->colorTable)
Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);
/* bitsColor */
newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);
if (!newBitMask)
{
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
return FALSE;
}
iconInfo->bitsColor = newBitMask;
Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);
return TRUE;
} | static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)
{
BYTE* newBitMask;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */
if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp);
return FALSE;
}
Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */
Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */
/* cbColorTable is only present when bpp is 1, 4 or 8 */
switch (iconInfo->bpp)
{
case 1:
case 4:
case 8:
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */
break;
default:
iconInfo->cbColorTable = 0;
break;
}
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */
Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */
/* bitsMask */
newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);
if (!newBitMask)
{
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
return FALSE;
}
iconInfo->bitsMask = newBitMask;
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)
return FALSE;
Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);
/* colorTable */
if (iconInfo->colorTable == NULL)
{
if (iconInfo->cbColorTable)
{
iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);
if (!iconInfo->colorTable)
return FALSE;
}
}
else if (iconInfo->cbColorTable)
{
BYTE* new_tab;
new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);
if (!new_tab)
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
return FALSE;
}
iconInfo->colorTable = new_tab;
}
else
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
if (iconInfo->colorTable)
{
if (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)
return FALSE;
Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);
}
/* bitsColor */
newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);
if (!newBitMask)
{
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
return FALSE;
}
iconInfo->bitsColor = newBitMask;
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)
return FALSE;
Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);
return TRUE;
} | {
"deleted": [
{
"line_no": 44,
"char_start": 1148,
"char_end": 1230,
"line": "\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n"
},
{
"line_no": 45,
"char_start": 1230,
"char_end": 1246,
"line": "\t\treturn FALSE;\n"
},
{
"line_no": 46,
"char_start": 1246,
"char_end": 1247,
"line": "\n"
}
],
"added": [
{
"line_no": 55,
"char_start": 1369,
"char_end": 1427,
"line": "\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n"
},
{
"line_no": 56,
"char_start": 1427,
"char_end": 1443,
"line": "\t\treturn FALSE;\n"
},
{
"line_no": 91,
"char_start": 2086,
"char_end": 2089,
"line": "\t{\n"
},
{
"line_no": 92,
"char_start": 2089,
"char_end": 2150,
"line": "\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n"
},
{
"line_no": 93,
"char_start": 2150,
"char_end": 2167,
"line": "\t\t\treturn FALSE;\n"
},
{
"line_no": 95,
"char_start": 2231,
"char_end": 2234,
"line": "\t}\n"
},
{
"line_no": 108,
"char_start": 2462,
"char_end": 2521,
"line": "\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n"
},
{
"line_no": 109,
"char_start": 2521,
"char_end": 2537,
"line": "\t\treturn FALSE;\n"
}
]
} | {
"deleted": [
{
"char_start": 1149,
"char_end": 1248,
"chars": "if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n\t\treturn FALSE;\n\n\t"
},
{
"char_start": 2368,
"char_end": 2368,
"chars": ""
}
],
"added": [
{
"char_start": 1164,
"char_end": 1164,
"chars": ""
},
{
"char_start": 1369,
"char_end": 1443,
"chars": "\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n\t\treturn FALSE;\n"
},
{
"char_start": 2086,
"char_end": 2167,
"chars": "\t{\n\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n\t\t\treturn FALSE;\n"
},
{
"char_start": 2230,
"char_end": 2233,
"chars": "\n\t}"
},
{
"char_start": 2460,
"char_end": 2535,
"chars": ";\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n\t\treturn FALSE"
}
]
} | github.com/FreeRDP/FreeRDP/commit/6b2bc41935e53b0034fe5948aeeab4f32e80f30f | libfreerdp/core/window.c | cwe-125 |
usbhid_parse | static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
for (n = 0; n < hdesc->bNumDescriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
} | static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
int num_descriptors;
size_t offset = offsetof(struct hid_descriptor, desc);
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
if (hdesc->bLength < sizeof(struct hid_descriptor)) {
dbg_hid("hid descriptor is too short\n");
return -EINVAL;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
num_descriptors = min_t(int, hdesc->bNumDescriptors,
(hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));
for (n = 0; n < num_descriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
} | {
"deleted": [
{
"line_no": 36,
"char_start": 1218,
"char_end": 1264,
"line": "\tfor (n = 0; n < hdesc->bNumDescriptors; n++)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 331,
"char_end": 353,
"line": "\tint num_descriptors;\n"
},
{
"line_no": 12,
"char_start": 353,
"char_end": 409,
"line": "\tsize_t offset = offsetof(struct hid_descriptor, desc);\n"
},
{
"line_no": 35,
"char_start": 1214,
"char_end": 1269,
"line": "\tif (hdesc->bLength < sizeof(struct hid_descriptor)) {\n"
},
{
"line_no": 36,
"char_start": 1269,
"char_end": 1313,
"line": "\t\tdbg_hid(\"hid descriptor is too short\\n\");\n"
},
{
"line_no": 37,
"char_start": 1313,
"char_end": 1331,
"line": "\t\treturn -EINVAL;\n"
},
{
"line_no": 38,
"char_start": 1331,
"char_end": 1334,
"line": "\t}\n"
},
{
"line_no": 39,
"char_start": 1334,
"char_end": 1335,
"line": "\n"
},
{
"line_no": 43,
"char_start": 1417,
"char_end": 1471,
"line": "\tnum_descriptors = min_t(int, hdesc->bNumDescriptors,\n"
},
{
"line_no": 44,
"char_start": 1471,
"char_end": 1545,
"line": "\t (hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));\n"
},
{
"line_no": 45,
"char_start": 1545,
"char_end": 1546,
"line": "\n"
},
{
"line_no": 46,
"char_start": 1546,
"char_end": 1585,
"line": "\tfor (n = 0; n < num_descriptors; n++)\n"
}
]
} | {
"deleted": [
{
"char_start": 1219,
"char_end": 1220,
"chars": "f"
},
{
"char_start": 1226,
"char_end": 1227,
"chars": "="
},
{
"char_start": 1228,
"char_end": 1230,
"chars": "0;"
},
{
"char_start": 1231,
"char_end": 1232,
"chars": "n"
},
{
"char_start": 1233,
"char_end": 1234,
"chars": "<"
},
{
"char_start": 1243,
"char_end": 1244,
"chars": "N"
},
{
"char_start": 1246,
"char_end": 1247,
"chars": "D"
}
],
"added": [
{
"char_start": 331,
"char_end": 409,
"chars": "\tint num_descriptors;\n\tsize_t offset = offsetof(struct hid_descriptor, desc);\n"
},
{
"char_start": 1215,
"char_end": 1336,
"chars": "if (hdesc->bLength < sizeof(struct hid_descriptor)) {\n\t\tdbg_hid(\"hid descriptor is too short\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\t"
},
{
"char_start": 1418,
"char_end": 1430,
"chars": "num_descript"
},
{
"char_start": 1432,
"char_end": 1433,
"chars": "s"
},
{
"char_start": 1434,
"char_end": 1441,
"chars": "= min_t"
},
{
"char_start": 1442,
"char_end": 1443,
"chars": "i"
},
{
"char_start": 1444,
"char_end": 1446,
"chars": "t,"
},
{
"char_start": 1447,
"char_end": 1472,
"chars": "hdesc->bNumDescriptors,\n\t"
},
{
"char_start": 1473,
"char_end": 1476,
"chars": " "
},
{
"char_start": 1479,
"char_end": 1480,
"chars": "("
},
{
"char_start": 1488,
"char_end": 1564,
"chars": "Length - offset) / sizeof(struct hid_class_descriptor));\n\n\tfor (n = 0; n < n"
},
{
"char_start": 1566,
"char_end": 1568,
"chars": "_d"
}
]
} | github.com/torvalds/linux/commit/f043bfc98c193c284e2cd768fefabe18ac2fed9b | drivers/hid/usbhid/hid-core.c | cwe-125 |
HPHP::exif_process_APP12 | static void exif_process_APP12(image_info_type *ImageInfo,
char *buffer, size_t length) {
size_t l1, l2=0;
if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company",
TAG_NONE, TAG_FMT_STRING, l1, buffer+2);
if (length > 2+l1+1) {
l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1);
exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info",
TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);
}
}
} | static void exif_process_APP12(image_info_type *ImageInfo,
char *buffer, size_t length) {
size_t l1, l2=0;
if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company",
TAG_NONE, TAG_FMT_STRING, l1, buffer+2);
if (length > 2+l1+1) {
l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);
exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info",
TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);
}
}
} | {
"deleted": [
{
"line_no": 8,
"char_start": 339,
"char_end": 393,
"line": " l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1);\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 339,
"char_end": 393,
"line": " l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);\n"
}
]
} | {
"deleted": [
{
"char_start": 388,
"char_end": 389,
"chars": "+"
}
],
"added": [
{
"char_start": 388,
"char_end": 389,
"chars": "-"
}
]
} | github.com/facebook/hhvm/commit/f1cd34e63c2a0d9702be3d41462db7bfd0ae7da3 | hphp/runtime/ext/gd/ext_gd.cpp | cwe-125 |
modbus_reply | int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
} | int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bits = req[offset + 5];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bytes = req[offset + 5];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
} | {
"deleted": [
{
"line_no": 140,
"char_start": 6054,
"char_end": 6106,
"line": " if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {\n"
},
{
"line_no": 171,
"char_start": 7556,
"char_end": 7613,
"line": " if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {\n"
}
],
"added": [
{
"line_no": 138,
"char_start": 5989,
"char_end": 6028,
"line": " int nb_bits = req[offset + 5];\n"
},
{
"line_no": 141,
"char_start": 6093,
"char_end": 6165,
"line": " if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {\n"
},
{
"line_no": 170,
"char_start": 7545,
"char_end": 7585,
"line": " int nb_bytes = req[offset + 5];\n"
},
{
"line_no": 173,
"char_start": 7655,
"char_end": 7733,
"line": " if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 6001,
"char_end": 6040,
"chars": "nb_bits = req[offset + 5];\n int "
},
{
"char_start": 6136,
"char_end": 6156,
"chars": " < nb || nb_bits * 8"
},
{
"char_start": 7557,
"char_end": 7597,
"chars": "nb_bytes = req[offset + 5];\n int "
},
{
"char_start": 7703,
"char_end": 7724,
"chars": " < nb || nb_bytes * 8"
}
]
} | github.com/stephane/libmodbus/commit/5ccdf5ef79d742640355d1132fa9e2abc7fbaefc | src/modbus.c | cwe-125 |
store_versioninfo_gnu_verneed | static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
//XXX we should use DT_VERNEEDNUM instead of sh_info
//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
vstart += entry->vn_aux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
//if entry->vn_next is 0 it iterate infinitely
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
} | static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
ut8 *end, *need = NULL;
const char *section_name = "";
Elf_(Shdr) *link_shdr = NULL;
const char *link_section_name = "";
Sdb *sdb_vernaux = NULL;
Sdb *sdb_version = NULL;
Sdb *sdb = NULL;
int i, cnt;
if (!bin || !bin->dynstr) {
return NULL;
}
if (shdr->sh_link > bin->ehdr.e_shnum) {
return NULL;
}
if (shdr->sh_size < 1) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {
bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n");
goto beach;
}
end = need + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "num_entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {
goto beach;
}
if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {
goto beach;
}
i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);
if (i < 0)
goto beach;
//XXX we should use DT_VERNEEDNUM instead of sh_info
//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html
for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {
int j, isum;
ut8 *vstart = need + i;
Elf_(Verneed) vvn = {0};
if (vstart + sizeof (Elf_(Verneed)) > end) {
goto beach;
}
Elf_(Verneed) *entry = &vvn;
char key[32] = {0};
sdb_version = sdb_new0 ();
if (!sdb_version) {
goto beach;
}
j = 0;
vvn.vn_version = READ16 (vstart, j)
vvn.vn_cnt = READ16 (vstart, j)
vvn.vn_file = READ32 (vstart, j)
vvn.vn_aux = READ32 (vstart, j)
vvn.vn_next = READ32 (vstart, j)
sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0);
sdb_num_set (sdb_version, "idx", i, 0);
if (entry->vn_file > bin->dynstr_size) {
goto beach;
}
{
char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);
sdb_set (sdb_version, "file_name", s, 0);
free (s);
}
sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0);
st32 vnaux = entry->vn_aux;
if (vnaux < 1) {
goto beach;
}
vstart += vnaux;
for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {
int k;
Elf_(Vernaux) * aux = NULL;
Elf_(Vernaux) vaux = {0};
sdb_vernaux = sdb_new0 ();
if (!sdb_vernaux) {
goto beach;
}
aux = (Elf_(Vernaux)*)&vaux;
k = 0;
vaux.vna_hash = READ32 (vstart, k)
vaux.vna_flags = READ16 (vstart, k)
vaux.vna_other = READ16 (vstart, k)
vaux.vna_name = READ32 (vstart, k)
vaux.vna_next = READ32 (vstart, k)
if (aux->vna_name > bin->dynstr_size) {
goto beach;
}
sdb_num_set (sdb_vernaux, "idx", isum, 0);
if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {
char name [16];
strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);
name[sizeof(name)-1] = 0;
sdb_set (sdb_vernaux, "name", name, 0);
}
sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0);
sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0);
isum += aux->vna_next;
vstart += aux->vna_next;
snprintf (key, sizeof (key), "vernaux%d", j);
sdb_ns_set (sdb_version, key, sdb_vernaux);
}
if ((int)entry->vn_next < 0) {
bprintf ("Invalid vn_next\n");
break;
}
i += entry->vn_next;
snprintf (key, sizeof (key), "version%d", cnt );
sdb_ns_set (sdb, key, sdb_version);
//if entry->vn_next is 0 it iterate infinitely
if (!entry->vn_next) {
break;
}
}
free (need);
return sdb;
beach:
free (need);
sdb_free (sdb_vernaux);
sdb_free (sdb_version);
sdb_free (sdb);
return NULL;
} | {
"deleted": [
{
"line_no": 85,
"char_start": 2490,
"char_end": 2517,
"line": "\t\tvstart += entry->vn_aux;\n"
}
],
"added": [
{
"line_no": 85,
"char_start": 2490,
"char_end": 2520,
"line": "\t\tst32 vnaux = entry->vn_aux;\n"
},
{
"line_no": 86,
"char_start": 2520,
"char_end": 2539,
"line": "\t\tif (vnaux < 1) {\n"
},
{
"line_no": 87,
"char_start": 2539,
"char_end": 2554,
"line": "\t\t\tgoto beach;\n"
},
{
"line_no": 88,
"char_start": 2554,
"char_end": 2558,
"line": "\t\t}\n"
},
{
"line_no": 89,
"char_start": 2558,
"char_end": 2577,
"line": "\t\tvstart += vnaux;\n"
}
]
} | {
"deleted": [
{
"char_start": 2492,
"char_end": 2493,
"chars": "v"
},
{
"char_start": 2496,
"char_end": 2498,
"chars": "rt"
},
{
"char_start": 2499,
"char_end": 2500,
"chars": "+"
}
],
"added": [
{
"char_start": 2494,
"char_end": 2499,
"chars": "32 vn"
},
{
"char_start": 2500,
"char_end": 2502,
"chars": "ux"
},
{
"char_start": 2515,
"char_end": 2572,
"chars": "aux;\n\t\tif (vnaux < 1) {\n\t\t\tgoto beach;\n\t\t}\n\t\tvstart += vn"
}
]
} | github.com/radare/radare2/commit/c6d0076c924891ad9948a62d89d0bcdaf965f0cd | libr/bin/format/elf/elf.c | cwe-125 |
ReadWPGImage | static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
} | static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
} | {
"deleted": [
{
"line_no": 485,
"char_start": 16143,
"char_end": 16191,
"line": " ldblk,sizeof(*BImgBuff));\n"
}
],
"added": [
{
"line_no": 485,
"char_start": 16143,
"char_end": 16193,
"line": " ldblk+1,sizeof(*BImgBuff));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 16170,
"char_end": 16172,
"chars": "+1"
}
]
} | github.com/ImageMagick/ImageMagick/commit/bef1e4f637d8f665bc133a9c6d30df08d983bc3a | coders/wpg.c | cwe-125 |
gf_m2ts_process_pmt | static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 info_length, pos, desc_len, evt_type, nb_es,i;
u32 nb_sections;
u32 data_size;
u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;
unsigned char *data;
GF_M2TS_Section *section;
GF_Err e = GF_OK;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
nb_es = 0;
/*skip if already received but no update detected (eg same data) */
if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
return;
}
if (pmt->sec->demux_restarted) {
pmt->sec->demux_restarted = 0;
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n"));
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];
info_length = ((data[2]&0xf)<<8) | data[3];
if (info_length != 0) {
/* ...Read Descriptors ... */
u8 tag, len;
u32 first_loop_len = 0;
tag = data[4];
len = data[5];
while (info_length > first_loop_len) {
if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {
u32 size;
GF_BitStream *iod_bs;
iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);
if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);
gf_bs_del(iod_bs );
if (e==GF_OK) {
/*remember program number for service/program selection*/
if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;
/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/
if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {
gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
pmt->program->pmt_iod = NULL;
}
}
} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {
GF_BitStream *metadatapd_bs;
GF_M2TS_MetadataPointerDescriptor *metapd;
metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);
metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);
gf_bs_del(metadatapd_bs);
if (metapd->application_format_identifier == GF_M2TS_META_ID3 &&
metapd->format_identifier == GF_M2TS_META_ID3 &&
metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {
/*HLS ID3 Metadata */
pmt->program->metadata_pointer_descriptor = metapd;
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_pointer_descriptor_del(metapd);
}
} else {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag));
}
first_loop_len += 2 + len;
}
}
if (data_size <= 4 + info_length) return;
data += 4 + info_length;
data_size -= 4 + info_length;
pos = 0;
/* count de number of program related PMT received */
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(prog->pmt_pid == pmt->pid) {
break;
}
}
nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;
while (pos<data_size) {
GF_M2TS_PES *pes = NULL;
GF_M2TS_SECTION_ES *ses = NULL;
GF_M2TS_ES *es = NULL;
Bool inherit_pcr = 0;
u32 pid, stream_type, reg_desc_format;
stream_type = data[0];
pid = ((data[1] & 0x1f) << 8) | data[2];
desc_len = ((data[3] & 0xf) << 8) | data[4];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type));
switch (stream_type) {
/* PES */
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_DCII:
case GF_M2TS_VIDEO_MPEG4:
case GF_M2TS_SYSTEMS_MPEG4_PES:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_MVCD:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
inherit_pcr = 1;
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_DTS:
case GF_M2TS_MHAS_MAIN:
case GF_M2TS_MHAS_AUX:
case GF_M2TS_SUBTITLE_DVB:
case GF_M2TS_METADATA_PES:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
if (inherit_pcr)
pes->flags |= GF_M2TS_INHERIT_PCR;
es = (GF_M2TS_ES *)pes;
break;
case GF_M2TS_PRIVATE_DATA:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
es = (GF_M2TS_ES *)pes;
break;
/* Sections */
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
/* carriage of ISO_IEC_14496 data in sections */
if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {
/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost
one SL packet in the AU so we must wait for the complete section again*/
ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);
/*create OD container*/
if (!pmt->program->additional_ods) {
pmt->program->additional_ods = gf_list_new();
ts->has_4on2 = 1;
}
}
break;
case GF_M2TS_13818_6_ANNEX_A:
case GF_M2TS_13818_6_ANNEX_B:
case GF_M2TS_13818_6_ANNEX_C:
case GF_M2TS_13818_6_ANNEX_D:
case GF_M2TS_PRIVATE_SECTION:
case GF_M2TS_QUALITY_SEC:
case GF_M2TS_MORE_SEC:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
es->pid = pid;
es->service_id = pmt->program->number;
if (stream_type == GF_M2TS_PRIVATE_SECTION) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_QUALITY_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_MORE_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid));
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid));
}
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
//ses->sec->service_id = pmt->program->number;
break;
case GF_M2TS_MPE_SECTIONS:
if (! ts->prefix_present) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid));
#ifdef GPAC_ENABLE_MPE
es = gf_dvb_mpe_section_new();
if (es->flags & GF_M2TS_ES_IS_SECTION) {
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);
}
#endif
break;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
break;
}
if (es) {
es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;
es->program = pmt->program;
es->pid = pid;
es->component_tag = -1;
}
pos += 5;
data += 5;
while (desc_len) {
u8 tag = data[0];
u32 len = data[1];
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes)
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);
/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/
switch (reg_desc_format) {
case GF_M2TS_RA_STREAM_AC3:
es->stream_type = GF_M2TS_AUDIO_AC3;
break;
case GF_M2TS_RA_STREAM_VC1:
es->stream_type = GF_M2TS_VIDEO_VC1;
break;
case GF_M2TS_RA_STREAM_GPAC:
if (len==8) {
es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);
es->flags |= GF_M2TS_GPAC_CODEC_ID;
break;
}
default:
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) ));
break;
}
break;
case GF_M2TS_DVB_EAC3_DESCRIPTOR:
es->stream_type = GF_M2TS_AUDIO_EC3;
break;
case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:
{
u32 id = data[2]<<8 | data[3];
if ((id == 0xB) && ses && !ses->sec) {
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
}
}
break;
case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:
if (pes) {
pes->sub.language[0] = data[2];
pes->sub.language[1] = data[3];
pes->sub.language[2] = data[4];
pes->sub.type = data[5];
pes->sub.composition_page_id = (data[6]<<8) | data[7];
pes->sub.ancillary_page_id = (data[8]<<8) | data[9];
}
es->stream_type = GF_M2TS_DVB_SUBTITLE;
break;
case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:
{
es->component_tag = data[2];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number));
}
break;
case GF_M2TS_DVB_TELETEXT_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_TELETEXT;
break;
case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_VBI;
break;
case GF_M2TS_HIERARCHY_DESCRIPTOR:
if (pes) {
u8 hierarchy_embedded_layer_index;
GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);
/*u32 skip = */gf_bs_read_int(hbs, 16);
/*u8 res1 = */gf_bs_read_int(hbs, 1);
/*u8 temp_scal = */gf_bs_read_int(hbs, 1);
/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);
/*u8 quality_scal = */gf_bs_read_int(hbs, 1);
/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);
/*u8 res2 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);
/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);
/*u8 res3 = */gf_bs_read_int(hbs, 1);
hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);
/*u8 res4 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);
gf_bs_del(hbs);
pes->depends_on_pid = 1+hierarchy_embedded_layer_index;
}
break;
case GF_M2TS_METADATA_DESCRIPTOR:
{
GF_BitStream *metadatad_bs;
GF_M2TS_MetadataDescriptor *metad;
metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);
metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);
gf_bs_del(metadatad_bs);
if (metad->application_format_identifier == GF_M2TS_META_ID3 &&
metad->format_identifier == GF_M2TS_META_ID3) {
/*HLS ID3 Metadata */
if (pes) {
pes->metadata_descriptor = metad;
pes->stream_type = GF_M2TS_METADATA_ID3_HLS;
}
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_descriptor_del(metad);
}
}
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag));
break;
}
}
data += len+2;
pos += len+2;
if (desc_len < len+2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) );
break;
}
desc_len-=len+2;
}
if (es && !es->stream_type) {
gf_free(es);
es = NULL;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
}
if (!es) continue;
if (ts->ess[pid]) {
//this is component reuse across programs, overwrite the previously declared stream ...
if (status & GF_M2TS_TABLE_FOUND) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) );
//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
//skip assignment below
es = NULL;
}
/*watchout for pmt update - FIXME this likely won't work in most cases*/
else {
GF_M2TS_ES *o_es = ts->ess[es->pid];
if ((o_es->stream_type == es->stream_type)
&& ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))
&& (o_es->mpeg4_es_id == es->mpeg4_es_id)
&& ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)
) {
gf_free(es);
es = NULL;
} else {
gf_m2ts_es_del(o_es, ts);
ts->ess[es->pid] = NULL;
}
}
}
if (es) {
ts->ess[es->pid] = es;
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
}
if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;
else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;
}
//Table 2-139, implied hierarchy indexes
if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (es->depends_on_pid) continue;
switch (es->stream_type) {
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
es->depends_on_pid = 1;
break;
case GF_M2TS_VIDEO_SHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
es->depends_on_pid = 3;
break;
case GF_M2TS_VIDEO_MHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
if (!nb_hevc_temp) es->depends_on_pid = 2;
else es->depends_on_pid = 3;
break;
}
}
}
if (nb_es) {
u32 i;
//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *an_es = NULL;
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (!es->depends_on_pid) continue;
//fixeme we are not always assured that hierarchy_layer_index matches the stream index...
//+1 is because our first stream is the PMT
an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);
if (an_es) {
es->depends_on_pid = an_es->pid;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"));
es->depends_on_pid = 0;
}
}
evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;
if (ts->on_event) ts->on_event(ts, evt_type, pmt->program);
} else {
/* if we found no new ES it's simply a repeat of the PMT */
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
}
} | static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 info_length, pos, desc_len, evt_type, nb_es,i;
u32 nb_sections;
u32 data_size;
u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;
unsigned char *data;
GF_M2TS_Section *section;
GF_Err e = GF_OK;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
nb_es = 0;
/*skip if already received but no update detected (eg same data) */
if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
return;
}
if (pmt->sec->demux_restarted) {
pmt->sec->demux_restarted = 0;
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n"));
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];
info_length = ((data[2]&0xf)<<8) | data[3];
if (info_length != 0) {
/* ...Read Descriptors ... */
u8 tag, len;
u32 first_loop_len = 0;
tag = data[4];
len = data[5];
while (info_length > first_loop_len) {
if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {
u32 size;
GF_BitStream *iod_bs;
iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);
if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);
gf_bs_del(iod_bs );
if (e==GF_OK) {
/*remember program number for service/program selection*/
if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;
/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/
if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {
gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
pmt->program->pmt_iod = NULL;
}
}
} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {
GF_BitStream *metadatapd_bs;
GF_M2TS_MetadataPointerDescriptor *metapd;
metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);
metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);
gf_bs_del(metadatapd_bs);
if (metapd->application_format_identifier == GF_M2TS_META_ID3 &&
metapd->format_identifier == GF_M2TS_META_ID3 &&
metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {
/*HLS ID3 Metadata */
pmt->program->metadata_pointer_descriptor = metapd;
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_pointer_descriptor_del(metapd);
}
} else {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag));
}
first_loop_len += 2 + len;
}
}
if (data_size <= 4 + info_length) return;
data += 4 + info_length;
data_size -= 4 + info_length;
pos = 0;
/* count de number of program related PMT received */
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(prog->pmt_pid == pmt->pid) {
break;
}
}
nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;
while (pos<data_size) {
GF_M2TS_PES *pes = NULL;
GF_M2TS_SECTION_ES *ses = NULL;
GF_M2TS_ES *es = NULL;
Bool inherit_pcr = 0;
u32 pid, stream_type, reg_desc_format;
stream_type = data[0];
pid = ((data[1] & 0x1f) << 8) | data[2];
desc_len = ((data[3] & 0xf) << 8) | data[4];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type));
switch (stream_type) {
/* PES */
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_DCII:
case GF_M2TS_VIDEO_MPEG4:
case GF_M2TS_SYSTEMS_MPEG4_PES:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_MVCD:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
inherit_pcr = 1;
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_DTS:
case GF_M2TS_MHAS_MAIN:
case GF_M2TS_MHAS_AUX:
case GF_M2TS_SUBTITLE_DVB:
case GF_M2TS_METADATA_PES:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
if (inherit_pcr)
pes->flags |= GF_M2TS_INHERIT_PCR;
es = (GF_M2TS_ES *)pes;
break;
case GF_M2TS_PRIVATE_DATA:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
es = (GF_M2TS_ES *)pes;
break;
/* Sections */
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
/* carriage of ISO_IEC_14496 data in sections */
if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {
/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost
one SL packet in the AU so we must wait for the complete section again*/
ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);
/*create OD container*/
if (!pmt->program->additional_ods) {
pmt->program->additional_ods = gf_list_new();
ts->has_4on2 = 1;
}
}
break;
case GF_M2TS_13818_6_ANNEX_A:
case GF_M2TS_13818_6_ANNEX_B:
case GF_M2TS_13818_6_ANNEX_C:
case GF_M2TS_13818_6_ANNEX_D:
case GF_M2TS_PRIVATE_SECTION:
case GF_M2TS_QUALITY_SEC:
case GF_M2TS_MORE_SEC:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
es->pid = pid;
es->service_id = pmt->program->number;
if (stream_type == GF_M2TS_PRIVATE_SECTION) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_QUALITY_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_MORE_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid));
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid));
}
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
//ses->sec->service_id = pmt->program->number;
break;
case GF_M2TS_MPE_SECTIONS:
if (! ts->prefix_present) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid));
#ifdef GPAC_ENABLE_MPE
es = gf_dvb_mpe_section_new();
if (es->flags & GF_M2TS_ES_IS_SECTION) {
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);
}
#endif
break;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
break;
}
if (es) {
es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;
es->program = pmt->program;
es->pid = pid;
es->component_tag = -1;
}
pos += 5;
data += 5;
while (desc_len) {
u8 tag = data[0];
u32 len = data[1];
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes)
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);
/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/
switch (reg_desc_format) {
case GF_M2TS_RA_STREAM_AC3:
es->stream_type = GF_M2TS_AUDIO_AC3;
break;
case GF_M2TS_RA_STREAM_VC1:
es->stream_type = GF_M2TS_VIDEO_VC1;
break;
case GF_M2TS_RA_STREAM_GPAC:
if (len==8) {
es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);
es->flags |= GF_M2TS_GPAC_CODEC_ID;
break;
}
default:
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) ));
break;
}
break;
case GF_M2TS_DVB_EAC3_DESCRIPTOR:
es->stream_type = GF_M2TS_AUDIO_EC3;
break;
case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:
{
u32 id = data[2]<<8 | data[3];
if ((id == 0xB) && ses && !ses->sec) {
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
}
}
break;
case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:
if (pes) {
pes->sub.language[0] = data[2];
pes->sub.language[1] = data[3];
pes->sub.language[2] = data[4];
pes->sub.type = data[5];
pes->sub.composition_page_id = (data[6]<<8) | data[7];
pes->sub.ancillary_page_id = (data[8]<<8) | data[9];
}
es->stream_type = GF_M2TS_DVB_SUBTITLE;
break;
case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:
{
es->component_tag = data[2];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number));
}
break;
case GF_M2TS_DVB_TELETEXT_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_TELETEXT;
break;
case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_VBI;
break;
case GF_M2TS_HIERARCHY_DESCRIPTOR:
if (pes) {
u8 hierarchy_embedded_layer_index;
GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);
/*u32 skip = */gf_bs_read_int(hbs, 16);
/*u8 res1 = */gf_bs_read_int(hbs, 1);
/*u8 temp_scal = */gf_bs_read_int(hbs, 1);
/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);
/*u8 quality_scal = */gf_bs_read_int(hbs, 1);
/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);
/*u8 res2 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);
/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);
/*u8 res3 = */gf_bs_read_int(hbs, 1);
hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);
/*u8 res4 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);
gf_bs_del(hbs);
pes->depends_on_pid = 1+hierarchy_embedded_layer_index;
}
break;
case GF_M2TS_METADATA_DESCRIPTOR:
{
GF_BitStream *metadatad_bs;
GF_M2TS_MetadataDescriptor *metad;
metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);
metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);
gf_bs_del(metadatad_bs);
if (metad->application_format_identifier == GF_M2TS_META_ID3 &&
metad->format_identifier == GF_M2TS_META_ID3) {
/*HLS ID3 Metadata */
if (pes) {
pes->metadata_descriptor = metad;
pes->stream_type = GF_M2TS_METADATA_ID3_HLS;
}
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_descriptor_del(metad);
}
}
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag));
break;
}
}
data += len+2;
pos += len+2;
if (desc_len < len+2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) );
break;
}
desc_len-=len+2;
}
if (es && !es->stream_type) {
gf_free(es);
es = NULL;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
}
if (!es) continue;
if (ts->ess[pid]) {
//this is component reuse across programs, overwrite the previously declared stream ...
if (status & GF_M2TS_TABLE_FOUND) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) );
//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
//skip assignment below
es = NULL;
}
/*watchout for pmt update - FIXME this likely won't work in most cases*/
else {
GF_M2TS_ES *o_es = ts->ess[es->pid];
if ((o_es->stream_type == es->stream_type)
&& ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))
&& (o_es->mpeg4_es_id == es->mpeg4_es_id)
&& ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)
) {
gf_free(es);
es = NULL;
} else {
gf_m2ts_es_del(o_es, ts);
ts->ess[es->pid] = NULL;
}
}
}
if (es) {
ts->ess[es->pid] = es;
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;
else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;
}
}
//Table 2-139, implied hierarchy indexes
if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (es->depends_on_pid) continue;
switch (es->stream_type) {
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
es->depends_on_pid = 1;
break;
case GF_M2TS_VIDEO_SHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
es->depends_on_pid = 3;
break;
case GF_M2TS_VIDEO_MHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
if (!nb_hevc_temp) es->depends_on_pid = 2;
else es->depends_on_pid = 3;
break;
}
}
}
if (nb_es) {
u32 i;
//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *an_es = NULL;
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (!es->depends_on_pid) continue;
//fixeme we are not always assured that hierarchy_layer_index matches the stream index...
//+1 is because our first stream is the PMT
an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);
if (an_es) {
es->depends_on_pid = an_es->pid;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"));
es->depends_on_pid = 0;
}
}
evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;
if (ts->on_event) ts->on_event(ts, evt_type, pmt->program);
} else {
/* if we found no new ES it's simply a repeat of the PMT */
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
}
} | {
"deleted": [
{
"line_no": 413,
"char_start": 14239,
"char_end": 14243,
"line": "\t\t}\n"
},
{
"line_no": 415,
"char_start": 14244,
"char_end": 14300,
"line": "\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n"
},
{
"line_no": 416,
"char_start": 14300,
"char_end": 14375,
"line": "\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n"
},
{
"line_no": 417,
"char_start": 14375,
"char_end": 14436,
"line": "\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n"
},
{
"line_no": 418,
"char_start": 14436,
"char_end": 14511,
"line": "\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n"
},
{
"line_no": 419,
"char_start": 14511,
"char_end": 14572,
"line": "\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n"
},
{
"line_no": 420,
"char_start": 14572,
"char_end": 14647,
"line": "\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n"
}
],
"added": [
{
"line_no": 414,
"char_start": 14240,
"char_end": 14297,
"line": "\t\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n"
},
{
"line_no": 415,
"char_start": 14297,
"char_end": 14373,
"line": "\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n"
},
{
"line_no": 416,
"char_start": 14373,
"char_end": 14435,
"line": "\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n"
},
{
"line_no": 417,
"char_start": 14435,
"char_end": 14511,
"line": "\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n"
},
{
"line_no": 418,
"char_start": 14511,
"char_end": 14573,
"line": "\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n"
},
{
"line_no": 419,
"char_start": 14573,
"char_end": 14649,
"line": "\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n"
},
{
"line_no": 420,
"char_start": 14649,
"char_end": 14653,
"line": "\t\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 14239,
"char_end": 14240,
"chars": "\t"
},
{
"char_start": 14241,
"char_end": 14244,
"chars": "}\n\n"
}
],
"added": [
{
"char_start": 14240,
"char_end": 14241,
"chars": "\t"
},
{
"char_start": 14297,
"char_end": 14298,
"chars": "\t"
},
{
"char_start": 14373,
"char_end": 14374,
"chars": "\t"
},
{
"char_start": 14437,
"char_end": 14438,
"chars": "\t"
},
{
"char_start": 14511,
"char_end": 14512,
"chars": "\t"
},
{
"char_start": 14575,
"char_end": 14576,
"chars": "\t"
},
{
"char_start": 14648,
"char_end": 14652,
"chars": "\n\t\t}"
}
]
} | github.com/gpac/gpac/commit/2320eb73afba753b39b7147be91f7be7afc0eeb7 | src/media_tools/mpegts.c | cwe-125 |
next_line | next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b, *avail, nl);
if (len >= 0)
len += tested;
}
return (len);
} | next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b + len, *avail - len, nl);
if (len >= 0)
len += tested;
}
return (len);
} | {
"deleted": [
{
"line_no": 38,
"char_start": 933,
"char_end": 972,
"line": "\t\tlen = get_line_size(*b, *avail, nl);\n"
}
],
"added": [
{
"line_no": 38,
"char_start": 933,
"char_end": 984,
"line": "\t\tlen = get_line_size(*b + len, *avail - len, nl);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 957,
"char_end": 963,
"chars": " + len"
},
{
"char_start": 971,
"char_end": 977,
"chars": " - len"
}
]
} | github.com/libarchive/libarchive/commit/eec077f52bfa2d3f7103b4b74d52572ba8a15aca | libarchive/archive_read_support_format_mtree.c | cwe-125 |
X86_insn_reg_intel | x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
// not found
return 0;
} | x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
static bool intel_regs_sorted = false;
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
if (insn_regs_intel_sorted[0].insn > id ||
insn_regs_intel_sorted[last].insn < id) {
return 0;
}
while (first <= last) {
mid = (first + last) / 2;
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
}
// not found
return 0;
} | {
"deleted": [
{
"line_no": 5,
"char_start": 148,
"char_end": 199,
"line": "\tunsigned int mid = ARR_SIZE(insn_regs_intel) / 2;\n"
},
{
"line_no": 29,
"char_start": 780,
"char_end": 808,
"line": "\t\tmid = (first + last) / 2;\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 71,
"char_end": 111,
"line": "\tstatic bool intel_regs_sorted = false;\n"
},
{
"line_no": 6,
"char_start": 188,
"char_end": 207,
"line": "\tunsigned int mid;\n"
},
{
"line_no": 17,
"char_start": 464,
"char_end": 508,
"line": "\tif (insn_regs_intel_sorted[0].insn > id ||\n"
},
{
"line_no": 18,
"char_start": 508,
"char_end": 553,
"line": "\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n"
},
{
"line_no": 19,
"char_start": 553,
"char_end": 565,
"line": "\t\treturn 0;\n"
},
{
"line_no": 20,
"char_start": 565,
"char_end": 568,
"line": "\t}\n"
},
{
"line_no": 21,
"char_start": 568,
"char_end": 569,
"line": "\n"
},
{
"line_no": 23,
"char_start": 594,
"char_end": 622,
"line": "\t\tmid = (first + last) / 2;\n"
}
]
} | {
"deleted": [
{
"char_start": 165,
"char_end": 197,
"chars": " = ARR_SIZE(insn_regs_intel) / 2"
},
{
"char_start": 779,
"char_end": 807,
"chars": "\n\t\tmid = (first + last) / 2;"
}
],
"added": [
{
"char_start": 72,
"char_end": 112,
"chars": "static bool intel_regs_sorted = false;\n\t"
},
{
"char_start": 465,
"char_end": 570,
"chars": "if (insn_regs_intel_sorted[0].insn > id ||\n\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n\t\treturn 0;\n\t}\n\n\t"
},
{
"char_start": 593,
"char_end": 621,
"chars": "\n\t\tmid = (first + last) / 2;"
}
]
} | github.com/aquynh/capstone/commit/87a25bb543c8e4c09b48d4b4a6c7db31ce58df06 | arch/X86/X86Mapping.c | cwe-125 |
r_bin_java_line_number_table_attr_new | R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 curpos, offset = 0;
RBinJavaLineNumberAttribute *lnattr;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;
attr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.line_number_table_attr.line_number_table = r_list_newf (free);
ut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;
RList *linenum_list = attr->info.line_number_table_attr.line_number_table;
if (linenum_len > sz) {
free (attr);
return NULL;
}
for (i = 0; i < linenum_len; i++) {
curpos = buf_offset + offset;
// printf ("%llx %llx \n", curpos, sz);
// XXX if (curpos + 8 >= sz) break;
lnattr = R_NEW0 (RBinJavaLineNumberAttribute);
if (!lnattr) {
break;
}
lnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->file_offset = curpos;
lnattr->size = 4;
r_list_append (linenum_list, lnattr);
}
attr->size = offset;
return attr;
} | R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 curpos, offset = 0;
RBinJavaLineNumberAttribute *lnattr;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;
attr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.line_number_table_attr.line_number_table = r_list_newf (free);
ut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;
RList *linenum_list = attr->info.line_number_table_attr.line_number_table;
if (linenum_len > sz) {
free (attr);
return NULL;
}
for (i = 0; i < linenum_len; i++) {
curpos = buf_offset + offset;
// printf ("%llx %llx \n", curpos, sz);
// XXX if (curpos + 8 >= sz) break;
lnattr = R_NEW0 (RBinJavaLineNumberAttribute);
if (!lnattr) {
break;
}
if (offset + 8 >= sz) {
break;
}
lnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->file_offset = curpos;
lnattr->size = 4;
r_list_append (linenum_list, lnattr);
}
attr->size = offset;
return attr;
} | {
"deleted": [],
"added": [
{
"line_no": 29,
"char_start": 996,
"char_end": 1022,
"line": "\t\tif (offset + 8 >= sz) {\n"
},
{
"line_no": 30,
"char_start": 1022,
"char_end": 1032,
"line": "\t\t\tbreak;\n"
},
{
"line_no": 31,
"char_start": 1032,
"char_end": 1036,
"line": "\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 998,
"char_end": 1038,
"chars": "if (offset + 8 >= sz) {\n\t\t\tbreak;\n\t\t}\n\t\t"
}
]
} | github.com/radare/radare2/commit/eb0fb72b3c5307ec8e33effb6bf947e38cfdffe8 | shlr/java/class.c | cwe-125 |
decode_studio_vop_header | static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
} | static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->interlaced_dct = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 9,
"char_start": 195,
"char_end": 222,
"line": " s->interlaced_dct = 0;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 202,
"char_end": 229,
"chars": "interlaced_dct = 0;\n s->"
}
]
} | github.com/FFmpeg/FFmpeg/commit/1f686d023b95219db933394a7704ad9aa5f01cbb | libavcodec/mpeg4videodec.c | cwe-125 |
str_lower_case_match | str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
} | str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (t >= tend) return 0;
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
} | {
"deleted": [],
"added": [
{
"line_no": 12,
"char_start": 373,
"char_end": 407,
"line": " if (t >= tend) return 0;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 383,
"char_end": 417,
"chars": "t >= tend) return 0;\n if ("
}
]
} | github.com/kkos/oniguruma/commit/d3e402928b6eb3327f8f7d59a9edfa622fec557b | src/regexec.c | cwe-125 |
HPHP::SimpleParser::handleBackslash | bool handleBackslash(signed char& out) {
char ch = *p++;
switch (ch) {
case 0: return false;
case '"': out = ch; return true;
case '\\': out = ch; return true;
case '/': out = ch; return true;
case 'b': out = '\b'; return true;
case 'f': out = '\f'; return true;
case 'n': out = '\n'; return true;
case 'r': out = '\r'; return true;
case 't': out = '\t'; return true;
case 'u': {
if (UNLIKELY(is_tsimplejson)) {
auto const ch1 = *p++;
auto const ch2 = *p++;
auto const dch3 = dehexchar(*p++);
auto const dch4 = dehexchar(*p++);
if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {
return false;
}
out = (dch3 << 4) | dch4;
return true;
} else {
uint16_t u16cp = 0;
for (int i = 0; i < 4; i++) {
auto const hexv = dehexchar(*p++);
if (hexv < 0) return false; // includes check for end of string
u16cp <<= 4;
u16cp |= hexv;
}
if (u16cp > 0x7f) {
return false;
} else {
out = u16cp;
return true;
}
}
}
default: return false;
}
} | bool handleBackslash(signed char& out) {
char ch = *p++;
switch (ch) {
case 0: return false;
case '"': out = ch; return true;
case '\\': out = ch; return true;
case '/': out = ch; return true;
case 'b': out = '\b'; return true;
case 'f': out = '\f'; return true;
case 'n': out = '\n'; return true;
case 'r': out = '\r'; return true;
case 't': out = '\t'; return true;
case 'u': {
if (UNLIKELY(is_tsimplejson)) {
auto const ch1 = *p++;
if (UNLIKELY(ch1 != '0')) return false;
auto const ch2 = *p++;
if (UNLIKELY(ch2 != '0')) return false;
auto const dch3 = dehexchar(*p++);
if (UNLIKELY(dch3 < 0)) return false;
auto const dch4 = dehexchar(*p++);
if (UNLIKELY(dch4 < 0)) return false;
out = (dch3 << 4) | dch4;
return true;
} else {
uint16_t u16cp = 0;
for (int i = 0; i < 4; i++) {
auto const hexv = dehexchar(*p++);
if (hexv < 0) return false; // includes check for end of string
u16cp <<= 4;
u16cp |= hexv;
}
if (u16cp > 0x7f) {
return false;
} else {
out = u16cp;
return true;
}
}
}
default: return false;
}
} | {
"deleted": [
{
"line_no": 19,
"char_start": 646,
"char_end": 722,
"line": " if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n"
},
{
"line_no": 20,
"char_start": 722,
"char_end": 748,
"line": " return false;\n"
},
{
"line_no": 21,
"char_start": 748,
"char_end": 760,
"line": " }\n"
}
],
"added": [
{
"line_no": 16,
"char_start": 523,
"char_end": 573,
"line": " if (UNLIKELY(ch1 != '0')) return false;\n"
},
{
"line_no": 18,
"char_start": 606,
"char_end": 656,
"line": " if (UNLIKELY(ch2 != '0')) return false;\n"
},
{
"line_no": 20,
"char_start": 701,
"char_end": 749,
"line": " if (UNLIKELY(dch3 < 0)) return false;\n"
},
{
"line_no": 22,
"char_start": 794,
"char_end": 842,
"line": " if (UNLIKELY(dch4 < 0)) return false;\n"
}
]
} | {
"deleted": [
{
"char_start": 669,
"char_end": 709,
"chars": "ch1 != '0' || ch2 != '0' || dch3 < 0 || "
},
{
"char_start": 720,
"char_end": 734,
"chars": "{\n "
},
{
"char_start": 747,
"char_end": 759,
"chars": "\n }"
}
],
"added": [
{
"char_start": 533,
"char_end": 583,
"chars": "if (UNLIKELY(ch1 != '0')) return false;\n "
},
{
"char_start": 616,
"char_end": 666,
"chars": "if (UNLIKELY(ch2 != '0')) return false;\n "
},
{
"char_start": 711,
"char_end": 759,
"chars": "if (UNLIKELY(dch3 < 0)) return false;\n "
}
]
} | github.com/facebook/hhvm/commit/b3679121bb3c7017ff04b4c08402ffff5cf59b13 | hphp/runtime/ext/json/JSON_parser.cpp | cwe-125 |
avr_op_analyze | static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
// initialize op struct
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
// process opcode
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
// copy default cycles/size values
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
// op->fail = addr + op->size;
op->addr = addr;
// start void esil expression
r_strbuf_setf (&op->esil, "");
// handle opcode
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
// eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr);
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
// remove trailing coma (COMETE LA COMA)
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
// ignore reserved opcodes (if they have not been caught by the previous loop)
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
// An unknown or invalid option has appeared.
// -- Throw pokeball!
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
// launch esil trap (for communicating upper layers about this weird
// and stinky situation
r_strbuf_set (&op->esil, "1,$");
return NULL;
} | static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
if (len < 2) {
return NULL;
}
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
// initialize op struct
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
// process opcode
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
// copy default cycles/size values
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
// op->fail = addr + op->size;
op->addr = addr;
// start void esil expression
r_strbuf_setf (&op->esil, "");
// handle opcode
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
// eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr);
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
// remove trailing coma (COMETE LA COMA)
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
// ignore reserved opcodes (if they have not been caught by the previous loop)
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
// An unknown or invalid option has appeared.
// -- Throw pokeball!
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
// launch esil trap (for communicating upper layers about this weird
// and stinky situation
r_strbuf_set (&op->esil, "1,$");
return NULL;
} | {
"deleted": [],
"added": [
{
"line_no": 3,
"char_start": 142,
"char_end": 158,
"line": "\tif (len < 2) {\n"
},
{
"line_no": 4,
"char_start": 158,
"char_end": 173,
"line": "\t\treturn NULL;\n"
},
{
"line_no": 5,
"char_start": 173,
"char_end": 176,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 143,
"char_end": 177,
"chars": "if (len < 2) {\n\t\treturn NULL;\n\t}\n\t"
}
]
} | github.com/radare/radare2/commit/b35530fa0681b27eba084de5527037ebfb397422 | libr/anal/p/anal_avr.c | cwe-125 |
uas_switch_interface | static int uas_switch_interface(struct usb_device *udev,
struct usb_interface *intf)
{
int alt;
alt = uas_find_uas_alt_setting(intf);
if (alt < 0)
return alt;
return usb_set_interface(udev,
intf->altsetting[0].desc.bInterfaceNumber, alt);
} | static int uas_switch_interface(struct usb_device *udev,
struct usb_interface *intf)
{
struct usb_host_interface *alt;
alt = uas_find_uas_alt_setting(intf);
if (!alt)
return -ENODEV;
return usb_set_interface(udev, alt->desc.bInterfaceNumber,
alt->desc.bAlternateSetting);
} | {
"deleted": [
{
"line_no": 4,
"char_start": 91,
"char_end": 101,
"line": "\tint alt;\n"
},
{
"line_no": 7,
"char_start": 141,
"char_end": 155,
"line": "\tif (alt < 0)\n"
},
{
"line_no": 8,
"char_start": 155,
"char_end": 169,
"line": "\t\treturn alt;\n"
},
{
"line_no": 10,
"char_start": 170,
"char_end": 202,
"line": "\treturn usb_set_interface(udev,\n"
},
{
"line_no": 11,
"char_start": 202,
"char_end": 254,
"line": "\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 91,
"char_end": 124,
"line": "\tstruct usb_host_interface *alt;\n"
},
{
"line_no": 7,
"char_start": 164,
"char_end": 175,
"line": "\tif (!alt)\n"
},
{
"line_no": 8,
"char_start": 175,
"char_end": 193,
"line": "\t\treturn -ENODEV;\n"
},
{
"line_no": 10,
"char_start": 194,
"char_end": 254,
"line": "\treturn usb_set_interface(udev, alt->desc.bInterfaceNumber,\n"
},
{
"line_no": 11,
"char_start": 254,
"char_end": 287,
"line": "\t\t\talt->desc.bAlternateSetting);\n"
}
]
} | {
"deleted": [
{
"char_start": 149,
"char_end": 153,
"chars": " < 0"
},
{
"char_start": 164,
"char_end": 167,
"chars": "alt"
},
{
"char_start": 201,
"char_end": 211,
"chars": "\n\t\t\tintf->"
},
{
"char_start": 214,
"char_end": 225,
"chars": "setting[0]."
},
{
"char_start": 247,
"char_end": 248,
"chars": " "
}
],
"added": [
{
"char_start": 92,
"char_end": 108,
"chars": "struct usb_host_"
},
{
"char_start": 111,
"char_end": 117,
"chars": "erface"
},
{
"char_start": 118,
"char_end": 119,
"chars": "*"
},
{
"char_start": 169,
"char_end": 170,
"chars": "!"
},
{
"char_start": 184,
"char_end": 191,
"chars": "-ENODEV"
},
{
"char_start": 225,
"char_end": 228,
"chars": " al"
},
{
"char_start": 253,
"char_end": 257,
"chars": "\n\t\t\t"
},
{
"char_start": 260,
"char_end": 284,
"chars": "->desc.bAlternateSetting"
}
]
} | github.com/torvalds/linux/commit/786de92b3cb26012d3d0f00ee37adf14527f35c4 | drivers/usb/storage/uas.c | cwe-125 |
sh_op | static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data)
return 0;
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
} | static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data || len < 2) {
return 0;
}
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
} | {
"deleted": [
{
"line_no": 4,
"char_start": 112,
"char_end": 124,
"line": "\tif (!data)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 112,
"char_end": 137,
"line": "\tif (!data || len < 2) {\n"
},
{
"line_no": 6,
"char_start": 149,
"char_end": 152,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 122,
"char_end": 133,
"chars": " || len < 2"
},
{
"char_start": 134,
"char_end": 136,
"chars": " {"
},
{
"char_start": 148,
"char_end": 151,
"chars": "\n\t}"
}
]
} | github.com/radare/radare2/commit/77c47cf873dd55b396da60baa2ca83bbd39e4add | libr/anal/p/anal_sh.c | cwe-125 |
ReadPSDChannelPixels | static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
} | static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),
exception),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
} | {
"deleted": [
{
"line_no": 72,
"char_start": 1913,
"char_end": 1960,
"line": " GetPixelIndex(image,q),q);\n"
}
],
"added": [
{
"line_no": 72,
"char_start": 1913,
"char_end": 1986,
"line": " ConstrainColormapIndex(image,GetPixelIndex(image,q),\n"
},
{
"line_no": 73,
"char_start": 1986,
"char_end": 2023,
"line": " exception),q);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1933,
"char_end": 1962,
"chars": "ConstrainColormapIndex(image,"
},
{
"char_start": 1983,
"char_end": 2017,
"chars": "),\n exception"
}
]
} | github.com/ImageMagick/ImageMagick/commit/e14fd0a2801f73bdc123baf4fbab97dec55919eb | coders/psd.c | cwe-125 |
ape_decode_frame | static int ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
// for old files coefficients were not interleaved,
// so we need to decode all of them at once
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
} | static int ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
uint64_t decoded_buffer_size;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
// for old files coefficients were not interleaved,
// so we need to decode all of them at once
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
av_assert0(decoded_buffer_size <= INT_MAX);
av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
} | {
"deleted": [
{
"line_no": 67,
"char_start": 2347,
"char_end": 2392,
"line": " if (!nblocks || nblocks > INT_MAX) {\n"
},
{
"line_no": 93,
"char_start": 3163,
"char_end": 3220,
"line": " av_fast_malloc(&s->decoded_buffer, &s->decoded_size,\n"
},
{
"line_no": 94,
"char_start": 3220,
"char_end": 3301,
"line": " 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 349,
"char_end": 383,
"line": " uint64_t decoded_buffer_size;\n"
},
{
"line_no": 68,
"char_start": 2381,
"char_end": 2463,
"line": " if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {\n"
},
{
"line_no": 94,
"char_start": 3234,
"char_end": 3323,
"line": " decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);\n"
},
{
"line_no": 95,
"char_start": 3323,
"char_end": 3371,
"line": " av_assert0(decoded_buffer_size <= INT_MAX);\n"
},
{
"line_no": 96,
"char_start": 3371,
"char_end": 3450,
"line": " av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);\n"
}
]
} | {
"deleted": [
{
"char_start": 3167,
"char_end": 3186,
"chars": "av_fast_malloc(&s->"
},
{
"char_start": 3200,
"char_end": 3213,
"chars": ", &s->decoded"
},
{
"char_start": 3218,
"char_end": 3231,
"chars": ",\n "
},
{
"char_start": 3232,
"char_end": 3238,
"chars": " "
}
],
"added": [
{
"char_start": 349,
"char_end": 383,
"chars": " uint64_t decoded_buffer_size;\n"
},
{
"char_start": 2422,
"char_end": 2459,
"chars": " / 2 / sizeof(*s->decoded_buffer) - 8"
},
{
"char_start": 3258,
"char_end": 3259,
"chars": "="
},
{
"char_start": 3261,
"char_end": 3263,
"chars": "LL"
},
{
"char_start": 3321,
"char_end": 3447,
"chars": ";\n av_assert0(decoded_buffer_size <= INT_MAX);\n av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size"
}
]
} | github.com/FFmpeg/FFmpeg/commit/ba4beaf6149f7241c8bd85fe853318c2f6837ad0 | libavcodec/apedec.c | cwe-125 |